【问题标题】:Logout and clear cookies programatically from controller in spring boot在 Spring Boot 中以编程方式从控制器注销和清除 cookie
【发布时间】:2021-11-20 06:53:48
【问题描述】:

我想在我的家庭控制器中使用下面箭头指示的行中使用 Spring Boot 安全性以编程方式注销。

我尝试过的事情: 我在看this 文章,我不清楚 /logout 是如何以及何时调用的?我不希望用户使用按钮注销或转到注销端点。

我还观看了 YT 视频 here,但它再次使用了 /logout 的表单操作。它使用注销 URL 和注销成功 URL。

我可以使用 logoutSuccessHandler 清除 cookie,但我不知道如何以编程方式调用注销,然后调用 logoutSuccesHandler。

   @RequestMapping("/")
        public String index(Principal principal) throws IsimConnectionException {
            Authentication authentication = (Authentication) principal;
    
    
            if ((authentication.getPrincipal() != null) && (authentication.isAuthenticated())) {
                
                String shortname = (String)authentication.getPrincipal();
    
                sessionScopedLdapUser.shortname(shortname);
    
                
                if (isimConn.hasid()) {
                    **** ---> here I would like to logout and clear cookies
                    return "hasid";
                } else {
                    return "needsLinking";
                }
    
            }
            return "index";
        }

这是我的网络安全配置类:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger log = LoggerFactory.getLogger(WebSecurityConfig.class);

    @Autowired
    private LdapAuthenticationProvider authProvider;

    /**
     * Defines the web based security configuration.
     *
     * @param   http It allows configuring web based security for specific http requests.
     * @throws  Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/css/**", "/js/**", "/images/**", "/sw.js").permitAll()
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin()
                    .loginPage("/login") //custom login page
                    .permitAll() // permit everyone the /login page
                .and()
                    .logout()
                    .permitAll()
                    .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK));

    }

    /**
     * Sets a custom authentication provider.
     *
     * @param   auth SecurityBuilder used to create an AuthenticationManager.
     * @throws  Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
    }



}

【问题讨论】:

  • 嗨@Toerktumlare,正如我在上面的代码中在我的问题中描述的那样,根据我的家庭控制器中的业务逻辑,我决定何时注销用户并使所有cookies无效。

标签: spring spring-security


【解决方案1】:
public void logout(HttpServletRequest request, HttpServletResponse response) {
    boolean isSecure = false;
    String contextPath = null;
    if (request != null) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        isSecure = request.isSecure();
        contextPath = request.getContextPath();
    }
    SecurityContext context = SecurityContextHolder.getContext();
    SecurityContextHolder.clearContext();
    context.setAuthentication(null);
    if (response != null) {
        Cookie cookie = new Cookie("JSESSIONID", null);
        String cookiePath = StringUtils.hasText(contextPath) ? contextPath : "/";
        cookie.setPath(cookiePath);
        cookie.setMaxAge(0);
        cookie.setSecure(isSecure);
        response.addCookie(cookie);
    }
}

您可以在任何地方调用上述方法从 Spring Security 中注销。您可以为请求和响应传递 null,但在这种情况下它不会使 http 会话无效并清除 cookie。

【讨论】:

  • 非常感谢@shazin。您在答案中编写的注销方法是否也会使 sessionscoped bean 无效?
  • 另外,如果我理解正确,如果使用您的注销方法,我的 webconfig 类中不需要以下配置。这是正确的@shazin吗? .and().logout().permitAll().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))
  • @Anuska 第一个问题的答案是的,如果您通过请求,那么理论上它将使会话无效,从而使所有会话范围的 bean 无效。第二个问题,是的,您不需要该部分,因为您没有调用/logout url 来注销
  • 太棒了。非常感谢@shazin。
猜你喜欢
  • 2016-05-03
  • 1970-01-01
  • 2021-11-05
  • 2015-06-17
  • 2019-03-18
  • 2011-06-03
  • 2020-06-25
  • 2015-09-24
  • 2011-02-18
相关资源
最近更新 更多