Spring Boot OAuth2 security session doesn't get clear when Logout

1.8k Views Asked by At

I used the following configuration but the user still exists. It has not clear the cookies.So how to clear the session and cookies?

.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").deleteCookies("JSESSIONID")
.invalidateHttpSession(true) ;

After that I used following code then it gets error "redirect_uri_mismatch"

@RequestMapping(value = "/logout", method = RequestMethod.POST)
public String logout(HttpServletRequest request,
                   HttpServletResponse response) {

    HttpSession session = request.getSession(false);
    if (request.isRequestedSessionIdValid() && session != null) {
        session.invalidate();
    }
    for (Cookie cookie : request.getCookies()) {
        cookie.setMaxAge(0);
        cookie.setValue(null);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    return  ("/new");
}

Then I used below code it gets error "redirect_uri_mismatch" again

@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){
        new SecurityContextLogoutHandler().logout(request, response, auth);
    }
    return "redirect:/new";
}

I used above codes seperately but nothing happens

1

There are 1 best solutions below

0
On

The default login is .formlogin() so I used .oauth2Login() then it worked.

.and()
.oauth2Login()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").deleteCookies("JSESSIONID")
.invalidateHttpSession(true) ;

And also I used defualt spring oauth configuration

@GetMapping("/secured")
public String securedPage(Model model, OAuth2AuthenticationToken authentication) {

    OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(authentication.getAuthorizedClientRegistrationId(), authentication.getName());

    String userInfoEndpointUri = client.getClientRegistration()
            .getProviderDetails()
            .getUserInfoEndpoint()
            .getUri();

    if (!StringUtils.isEmpty(userInfoEndpointUri)) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + client.getAccessToken().getTokenValue());

        HttpEntity<String> entity = new HttpEntity<String>("", headers);

        ResponseEntity<Map> response = restTemplate.exchange(userInfoEndpointUri, HttpMethod.GET, entity, Map.class);
        Map userAttributes = response.getBody();
        model.addAttribute("name", userAttributes.get("name"));
    }

    return "/secured";