使用spring secuity自定义退出

我们查看源码

从默认的退出api入口,

http.logout();

进入logout方法,

public LogoutConfigurer<HttpSecurity> logout() throws Exception {
    return getOrApply(new LogoutConfigurer<HttpSecurity>());
}

我们查看LogoutConfigurer类,默认的退出的url地址是/logout,默认的退出成功跳转的url地址是/login?logout

public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>> extends
        AbstractHttpConfigurer<LogoutConfigurer<H>, H> {
    private List<LogoutHandler> logoutHandlers = new ArrayList<LogoutHandler>();
    private SecurityContextLogoutHandler contextLogoutHandler = new SecurityContextLogoutHandler();
    //默认的退出成功跳转的url地址是/login?logout
    private String logoutSuccessUrl = "/login?logout";
    private LogoutSuccessHandler logoutSuccessHandler;
    //默认的退出的url地址是/logout
    private String logoutUrl = "/logout";
    private RequestMatcher logoutRequestMatcher;
    private boolean permitAll;
    private boolean customLogoutSuccess;

    private LinkedHashMap<RequestMatcher, LogoutSuccessHandler> defaultLogoutSuccessHandlerMappings =
            new LinkedHashMap<RequestMatcher, LogoutSuccessHandler>();

    /**
     * Creates a new instance
     * @see HttpSecurity#logout()
     */
    public LogoutConfigurer() {
    }
    ...

再往下看,LogoutConfigurer类的getLogoutRequestMatcher()方法,

    @SuppressWarnings("unchecked")
    private RequestMatcher getLogoutRequestMatcher(H http) {
        if (logoutRequestMatcher != null) {
            return logoutRequestMatcher;
        }
        if (http.getConfigurer(CsrfConfigurer.class) != null) {
            this.logoutRequestMatcher = new AntPathRequestMatcher(this.logoutUrl, "POST");
        }
        else {
            this.logoutRequestMatcher = new OrRequestMatcher(
                new AntPathRequestMatcher(this.logoutUrl, "GET"),
                new AntPathRequestMatcher(this.logoutUrl, "POST"),
                new AntPathRequestMatcher(this.logoutUrl, "PUT"),
                new AntPathRequestMatcher(this.logoutUrl, "DELETE")
            );
        }
        return this.logoutRequestMatcher;
    }

如果是启用了csrf模式,退出是使用的post类型,如果没有启动csrf那么启动的是else中的逻辑。

不使用csrf模式,在登录和退出的时候,post请求必须要有token,在login.jsp和logout.jsp中定义如下就是为了设置token。

<input type="hidden" name="${ _csrf.parameterName}" value="${ _csrf.token}" />

spring secuity默认的退出

上面大概看了一下默认的退出源码,我们先使用spring secuity默认的退出,

  • 配置类

我们禁用了csrf模式,配置了默认的http.logout();

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("GUEST");
        auth.inMemoryAuthentication().withUser("zhihao.miao").password("123456").roles("USER");
        auth.inMemoryAuthentication().withUser("lisi").password("12345678").roles("USER", "ADMIN");
    }

    protected void configure(HttpSecurity http) throws Exception {

        //禁用csrf模式
        http.csrf().disable();

        http.authorizeRequests().antMatchers("/hello").hasRole("GUEST");
        http.authorizeRequests().antMatchers("/home").hasRole("USER");
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN");

        //登录的跳转页面,和登录的动作url不应该有权限认证。
        http.authorizeRequests().antMatchers("/sys/login").permitAll();
        //配置登出页面的跳转url地址也有权限访问,不去跳转到登录页面
        http.authorizeRequests().antMatchers("/sys/logout").permitAll();
        http.authorizeRequests().antMatchers("/**/*.html").permitAll();
        http.authorizeRequests().antMatchers("/**/*.css").permitAll();
        http.authorizeRequests().antMatchers("/**/*.js").permitAll();
        http.authorizeRequests().antMatchers("/**/*.png").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();


        http.formLogin().
                loginPage("/sys/login").
                loginProcessingUrl("/doLogin").
                failureForwardUrl("/sys/loginFail").   //使用forward的方式,能拿到具体失败的原因,并且会将错误信息以SPRING_SECURITY_LAST_EXCEPTION的key的形式将AuthenticationException对象保存到request域中
                        defaultSuccessUrl("/public/login/ok.html"). //如果直接访问登录页面,则登录成功后重定向到这个页面,否则跳转到之前想要访问的页面
                        permitAll();

        //logout默认的url是 /logout,如果csrf启用,则请求方式是POST,否则请求方式是GET、POST、PUT、DELETE
        http.logout();
    }
}
  • 定义controller

我们访问这个/sys/logout的url地址的时候,跳转到退出页面

    @GetMapping("/sys/logout")
    public String logout(){
        return "/jsp/logout";
    }
  • 定义退出页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
</head>
<body>
<a href="/logout">GET logout</a>
<br />
<form action="/logout" method="post">
    <input type="hidden" name="${ _csrf.parameterName}" value="${ _csrf.token}" />
    <input type="submit" value="POST Logout"/>
</form>
</body>
</html>
  • 启动服务,测试一下

访问http://localhost:8001/hello,跳转到登录页面http://localhost:8001/sys/login,输入正确的用户名密码之后跳转到http://localhost:8001/hello,我们想退出,访问http://localhost:8001/sys/logout,跳转到我们定义的退出页面,因为我们禁用了csrf模式,所以退出的请求方式是GETPOSTPUTDELETE

我们打开另外一个标签栏,点击get请求,退出成功跳转到登录页面,我们再去之前的标签栏刷新http://localhost:8001/hello请求,发现又跳转到登录页面http://localhost:8001/sys/login

自定义退出

默认的推出url是/logout。我们这边定制的url及一些handler

  • 配置类如下:

我们定义了退出url,以及退出url的请求类型是get,定义了三个退出handler,定义了一个退出成功的handler

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("GUEST");
        auth.inMemoryAuthentication().withUser("zhihao.miao").password("123456").roles("USER");
        auth.inMemoryAuthentication().withUser("lisi").password("12345678").roles("USER", "ADMIN");
    }

    protected void configure(HttpSecurity http) throws Exception {

        //禁用csrf模式
        http.csrf().disable();

        http.authorizeRequests().antMatchers("/hello").hasRole("GUEST");
        http.authorizeRequests().antMatchers("/home").hasRole("USER");
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN");

        //登录的跳转页面,和登录的动作url不应该有权限认证。
        http.authorizeRequests().antMatchers("/sys/login").permitAll();
        //配置登出页面的跳转url地址也有权限访问,不去跳转到登录页面
        http.authorizeRequests().antMatchers("/sys/logout").permitAll();
        http.authorizeRequests().antMatchers("/**/*.html").permitAll();
        http.authorizeRequests().antMatchers("/**/*.css").permitAll();
        http.authorizeRequests().antMatchers("/**/*.js").permitAll();
        http.authorizeRequests().antMatchers("/**/*.png").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();


        http.formLogin().
                loginPage("/sys/login").
                loginProcessingUrl("/doLogin").
                failureForwardUrl("/sys/loginFail").   //使用forward的方式,能拿到具体失败的原因,并且会将错误信息以SPRING_SECURITY_LAST_EXCEPTION的key的形式将AuthenticationException对象保存到request域中
                        defaultSuccessUrl("/public/login/ok.html"). //如果直接访问登录页面,则登录成功后重定向到这个页面,否则跳转到之前想要访问的页面
                        permitAll();

        //定制退出
        http.logout()
                //.logoutUrl("/sys/doLogout")  //只支持定制退出url
                //支持定制退出url以及httpmethod
                .logoutRequestMatcher(new AntPathRequestMatcher("/sys/doLogout", "GET"))
                .addLogoutHandler((request,response,authentication) -> System.out.println("=====1====="))
                .addLogoutHandler((request,response,authentication) -> System.out.println("=====2======"))
                .addLogoutHandler((request,response,authentication) -> System.out.println("=====3======"))
                .logoutSuccessHandler(((request, response, authentication) -> {
                    System.out.println("=====4=======");
                    response.sendRedirect("/html/logoutsuccess1.html");
                }))
                //.logoutSuccessUrl("/html/logoutsuccess2.html")  //成功退出的时候跳转的页面
                //.deleteCookies()  //底层也是使用Handler实现的额
                //清除认证信息
                .clearAuthentication(true)
                .invalidateHttpSession(true)
        ;  //使session失效
    }
}
  • 修改登出页面

修改get请求的链接地址是我们新配置的退出url。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
</head>
<body>
<a href="/sys/doLogout">GET logout</a>
<br />
<form action="/logout" method="post">
    <input type="hidden" name="${ _csrf.parameterName}" value="${ _csrf.token}" />
    <input type="submit" value="POST Logout"/>
</form>
</body>
</html>

  • 定义自己的退出成功页面

logoutsuccess1.html页面的内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    logout1 success
</body>
</html>
  • 启动服务,测试一下

访问http://localhost:8001/hello,跳转到登录页面http://localhost:8001/sys/login,输入正确的用户名密码之后跳转到http://localhost:8001/hello,我们想退出,访问http://localhost:8001/sys/logout,跳转到我们定义的退出页面


我们打开另外一个标签栏,点击get请求,退出成功跳转到登录页面,我们再去之前的标签栏刷新http://localhost:8001/hello请求,发现又跳转到登录页面http://localhost:8001/sys/login

控制台打印:

[INFO] Session id node02vrs7ek2u7dfhgwg8q9azjxv0 swapped for new id node011kk0zpcbnr3p14se8mkozjue21
=====1=====
=====2======
=====3======
[INFO] Session node011kk0zpcbnr3p14se8mkozjue21 already being invalidated
=====4=======
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容