How to logout from spring security?




Asked on March 09, 2018
   Hello,

  I have tried the following methods to logout from spring security. But unable to logout:

   Method:1
@RequestMapping("/exit")
    public void exit(HttpServletRequest request, HttpServletResponse response) {
        new SecurityContextLogoutHandler().logout(request, null, null);
        try {
              response.sendRedirect(request.getHeader("http://localhost:4200"));
              } catch (Exception e) {
          //  e.printStackTrace();

        }
    }

Method:2

@RequestMapping(value = "/logout1")
public String logout1(){
try {
        //HttpServletRequest request = null;
HttpSession session = request.getSession(false);
            session.invalidate();

        if (session != null) {

            session.invalidate();
        }

        SecurityContextHolder.clearContext();
        return "s";

    } catch (Exception e) {
        //logger.log(LogLevel.INFO, "Problem logging out.");
System.out.println("inside catch\n\n");

    return "ERROR"+e.getMessage();
    }
}

Method:3

@RequestMapping(value = {"/clear"})
public String clear(HttpServletRequest request,HttpServletResponse response){
HttpSession session= request.getSession(false);
    SecurityContextHolder.clearContext();
         session= request.getSession(false);
        if(session != null) {
            session.invalidate();
        }
        for(javax.servlet.http.Cookie cookie : request.getCookies()) {
            cookie.setMaxAge(0);
        }

    return "logout";
}



How do I fix this?


Thanks & Regards
Shilpa Kulkarni





Replied on March 09, 2018
You need to configure logout in configuration file.

1. In case of JavaConfig:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAppUserDetailsService myAppUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/user/**").hasAnyRole("ADMIN","USER")
.and().formLogin()  //login configuration
                .loginPage("/customLogin.jsp")
                .loginProcessingUrl("/appLogin")
                .usernameParameter("app_username")
                .passwordParameter("app_password")
                .defaultSuccessUrl("/user/home")
.and().logout()    //logout configuration
.logoutUrl("/appLogout") 
.logoutSuccessUrl("/customLogin.jsp")
.and().exceptionHandling() //exception handling configuration
.accessDeniedPage("/user/error");
}
        @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
                auth.userDetailsService(myAppUserDetailsService).passwordEncoder(passwordEncoder());
}
        @Bean
        public PasswordEncoder passwordEncoder() {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            return passwordEncoder;
        }
}   
Logout URL will be /appLogout

2. In case of XML configuration:

<http>
<intercept-url  pattern="/user/**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
<form-login 
   login-page="/customLogin.jsp" 
   login-processing-url="/appLogin"
   username-parameter="app_username"
   password-parameter="app_password"
   default-target-url="/user/home"/>
<logout 
   logout-url="/appLogout" 
   logout-success-url="/customLogin.jsp"/>  
<access-denied-handler error-page="/user/error"/>
</http>

Logout URL will be /appLogout

3. Now In view, create form as follows.

      <form action="<%=request.getContextPath()%>/appLogout" method="POST">
        <input type="submit" value="Logout"/>
        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
      </form> 


Find the link for complete example.




Replied on March 12, 2018
Thank you for the reply. 
I have added java config code in my configuration file. But I am getting "404 Not Found" error.
I have added the following code in my micro-service api-gateway's configuration file.

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
@EnableOAuth2Sso
public class Application extends WebSecurityConfigurerAdapter {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**/*.html","/login","/appLogout","/","/microservice1/viewall","/microservice2/getall")
.permitAll()
.anyRequest().authenticated()
.and()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and().logout()    //logout configuration
.logoutUrl("/appLogout") 
.logoutSuccessUrl("/login")
.and().exceptionHandling() //exception handling configuration
.accessDeniedPage("/");
}
}





Replied on March 12, 2018
You should not include logout URL into antMatchers
404 means application did not find URL. The URL should be 

<%=request.getContextPath()%>/appLogout

For example 

Http://localhost:8080/spring-app/appLogout





Replied on March 14, 2018
This 404 error resolved. It is going to logoutUrl  and logoutSuccessUrl. But functionality is not getting achieved. It is coming back to the landing page (May be it is using session or cookie and getting loggedin). 

Can you please provide solution for this?



Replied on March 14, 2018
Only those URL patterns configured in antMatchers will be secured. Configure all URL patterns which needs to be authenticated.  For example 

.antMatchers("/microservice/**")

All URLs starting with /microservice will be authenticated.

/login should not be in antMatchers



Write Answer










©2024 concretepage.com | Privacy Policy | Contact Us