How to logout from spring security?

Asked on March 09, 2018

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

    public void exit(HttpServletRequest request, HttpServletResponse response) {
        new SecurityContextLogoutHandler().logout(request, null, null);
        try {
              } catch (Exception e) {
          //  e.printStackTrace();



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

        if (session != null) {


        return "s";

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

    return "ERROR"+e.getMessage();


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

    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:

public class SecurityConfig extends WebSecurityConfigurerAdapter {
private MyAppUserDetailsService myAppUserDetailsService;
protected void configure(HttpSecurity http) throws Exception {
.and().formLogin()  //login configuration
.and().logout()    //logout configuration
.and().exceptionHandling() //exception handling configuration
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        public PasswordEncoder passwordEncoder() {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            return passwordEncoder;
Logout URL will be /appLogout

2. In case of XML configuration:

<intercept-url  pattern="/user/**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
<access-denied-handler error-page="/user/error"/>

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}"/>

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.

public class Application extends WebSecurityConfigurerAdapter {

public static void main(String[] args) {, args);

public void configure(HttpSecurity http) throws Exception {
.and().logout()    //logout configuration
.and().exceptionHandling() //exception handling configuration

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


For example 


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 


All URLs starting with /microservice will be authenticated.

/login should not be in antMatchers

Write Answer

©2024 | Privacy Policy | Contact Us