【问题标题】:Custom logout with method使用方法自定义注销
【发布时间】:2018-07-14 06:22:23
【问题描述】:

我正在使用 Spring Boot 和 Spring Security 编写一个 Web 项目。

我想以方法而不是 URL /logout 注销。例如:一个控制器方法获取一个 URL,然后这个方法做一些事情并注销。

我的 Spring Security 配置:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error").permitAll()
            .and()
        .logout().permitAll();
}

但我不知道如何使用方法注销。我应该在SecurityConfig.class 中做什么?没有网址的退出方法应该怎么做?

【问题讨论】:

  • 为什么?因为您确实绕过了许多注销功能,然后您需要自己复制这些功能......(Spring Security 所做的更多,只是使手头的会话无效)。
  • 我只想用一个方法而不是 url 注销。我只想知道我应该调用哪个对象,以及当我发现用户做错事时我应该调用哪个方法来注销。 @dur

标签: spring spring-boot spring-security


【解决方案1】:

您可以在 Controller 中创建一个方法,并使用 SecurityContextLogoutHandler 类的方法 logout 来注销当前用户。

@RequestMapping(value="/custom-logout", method = RequestMethod.GET)
public String customLogout(HttpServletRequest request, HttpServletResponse response) {
    // Get the Spring Authentication object of the current request.
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    // In case you are not filtering the users of this request url.
    if (authentication != null){    
        new SecurityContextLogoutHandler().logout(request, response, authentication); // <= This is the call you are looking for.
    }
    return "redirect:/login-page";
}

【讨论】:

    【解决方案2】:
    .logout()
        .logoutUrl("/logoutUrl")
        .logoutSuccessUrl("/index.html?logout=true")
        .logoutSuccessHandler(logoutHandler)
        .invalidateHttpSession(true)
    

    此注销用户即清除SecurityContext,并在成功注销后重定向到页面index.html?logout=true。 您还可以定义一个实现 LogoutHandler 的 LogoutSuccessHandler,并实现 onLogoutSuccess() 为您的用例添加任何注销后逻辑。 Spring 提供了一些 LogoutHandler 的实现,例如 SecurityContextLogoutHandler、SimpleUrlLogoutSuccessHandler 等。在 spring 安全文档中查看更多信息。 invalidateHttpSession(true) 使您的 httpsession 无效。

    【讨论】:

    • 谢谢你的回答,但我不是用另一个url注销,我只是想要一个注销服务器的方法。例如我想在某个时候在main函数中注销。我该怎么办?在某些功能中,我发现用户做了我不想做的事情(例如错误的参数),我需要注销。我应该怎么做? @Praneeth Ramesh
    • 你的意思是任何方法里面的任何东西,你只是想注销用户。在 SpringSecurity Logout 中只是意味着清除 Securitycontext。只需调用 SecurityContextHolder.clearContext();会做的。此外,您可能希望使 HttpSession.invalidate(); 无效根据您的用例,您可能还必须考虑清除 cookie 和内容。或者 HttpServletRequest.logout() 这也是一种更简洁的方法。
    • 非常感谢,在您的指导下,我完成了! @Praneeth Ramesh
    猜你喜欢
    • 1970-01-01
    • 2019-08-30
    • 2012-09-29
    • 2014-03-31
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多