当前位置: > > > SpringBoot - 安全管理框架Spring Security使用详解7(注销登录配置)

SpringBoot - 安全管理框架Spring Security使用详解7(注销登录配置)

    默认情况下,Spring Security 提供了注销接口是 /logout,访问这个接口即可注销当前登录用户并且自动跳转到登录页。如果需要修改注销接口,或者想在注销时做一些业务逻辑,或者注销后不是跳转到登录页而是返回一段 JSON 提示,只需在一些简单配置即可。

七、注销登录配置

1,样例代码

首先修改 Spring Security 配置,增加相关的自定义配置代码:
  • 开启并设置注销登录的 URL
  • 在注销是做一些数据清除工作。
  • 注销后返回一段 JSON 提示,而是不是跳转到登录页。
@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
    // 指定密码的加密方式
    @SuppressWarnings("deprecation")
    @Bean
    PasswordEncoder passwordEncoder(){
        // 不对密码进行加密
        return NoOpPasswordEncoder.getInstance();
    }

    // 配置用户及其对应的角色
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("root").password("123").roles("DBA")
                .and()
                .withUser("admin").password("123").roles("ADMIN")
                .and()
                .withUser("hangge").password("123").roles("USER");
    }
    // 配置 URL 访问权限
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() // 开启 HttpSecurity 配置
            .antMatchers("/db/**").hasRole("DBA") // db/** 模式URL需DBA角色
            .antMatchers("/admin/**").hasRole("ADMIN") // admin/** 模式URL需ADMIN角色
            .antMatchers("/user/**").hasRole("USER") // user/** 模式URL需USER角色
            .anyRequest().authenticated() // 用户访问其它URL都必须认证后访问(登录后访问)
            .and().formLogin().loginProcessingUrl("/login").permitAll() // 开启表单登录并配置登录接口
            .and().logout() // 开启注销登录的配置
            .logoutUrl("/logout") // 配置注销登录请求URL为"/logout"(默认也就是 /logout)
            .clearAuthentication(true) // 清除身份认证信息
            .invalidateHttpSession(true) // 使 session 失效
            // 配置一个 LogoutHandler,开发者可以在这里完成一些数据清除工做
            .addLogoutHandler(new LogoutHandler() {
                @Override
                public void logout(HttpServletRequest req,
                                   HttpServletResponse resp,
                                   Authentication auth) {
                    System.out.println("注销登录,开始清除Cookie。");
                }
            })
            // 配置一个 LogoutSuccessHandler,开发者可以在这里处理注销成功后的业务逻辑
            .logoutSuccessHandler(new LogoutSuccessHandler() {
                @Override
                public void onLogoutSuccess(HttpServletRequest req,
                                            HttpServletResponse resp,
                                            Authentication auth)
                        throws IOException, ServletException {
                    // 我们可以跳转到登录页面
                    // resp.sendRedirect("/login");

                    // 也可以返回一段JSON提示
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    resp.setStatus(200);
                    Map<String, Object> map = new HashMap<>();
                    map.put("status", 200);
                    map.put("msg", "注销成功!");
                    ObjectMapper om = new ObjectMapper();
                    out.write(om.writeValueAsString(map));
                    out.flush();
                    out.close();
                }
            })
            .and().csrf().disable(); // 关闭csrf
    }
}

2,运行测试 

(1)用户登录后,我们访问 /logout 接口进行注销。注销后页面上返回如下信息,而是不是跳转到登录页面。

(2)控制台输出如下:
评论0