注销时,Spring Boot OAuth2安全会话无法清除

时间:2018-10-01 06:36:09

标签: google-oauth spring-boot-gradle-plugin

我使用了以下配置,但用户仍然存在。它尚未清除cookie。那么如何清除会话和cookie?

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

之后,我使用下面的代码,然后出现错误“ 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");
}

然后我用下面的代码再次得到错误“ redirect_uri_mismatch”

@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";
}

我分别使用了上面的代码,但没有任何反应

1 个答案:

答案 0 :(得分:0)

默认登录名是.formlogin(),所以我使用了.oauth2Login()然后就可以了。

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

我也使用了defualt spring oauth配置

@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";