使用spring secuity自定義退出

我們查看源碼

從默認(rèn)的退出api入口,

http.logout();

進(jìn)入logout方法,

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

我們查看LogoutConfigurer類,默認(rèn)的退出的url地址是/logout,默認(rèn)的退出成功跳轉(zhuǎn)的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();
    //默認(rèn)的退出成功跳轉(zhuǎn)的url地址是/login?logout
    private String logoutSuccessUrl = "/login?logout";
    private LogoutSuccessHandler logoutSuccessHandler;
    //默認(rèn)的退出的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類型,如果沒(méi)有啟動(dòng)csrf那么啟動(dòng)的是else中的邏輯。

不使用csrf模式,在登錄和退出的時(shí)候,post請(qǐng)求必須要有token,在login.jsp和logout.jsp中定義如下就是為了設(shè)置token。

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

spring secuity默認(rèn)的退出

上面大概看了一下默認(rèn)的退出源碼,我們先使用spring secuity默認(rèn)的退出,

  • 配置類

我們禁用了csrf模式,配置了默認(rèn)的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");

        //登錄的跳轉(zhuǎn)頁(yè)面,和登錄的動(dòng)作url不應(yīng)該有權(quán)限認(rèn)證。
        http.authorizeRequests().antMatchers("/sys/login").permitAll();
        //配置登出頁(yè)面的跳轉(zhuǎn)url地址也有權(quán)限訪問(wèn),不去跳轉(zhuǎn)到登錄頁(yè)面
        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的方式,能拿到具體失敗的原因,并且會(huì)將錯(cuò)誤信息以SPRING_SECURITY_LAST_EXCEPTION的key的形式將AuthenticationException對(duì)象保存到request域中
                        defaultSuccessUrl("/public/login/ok.html"). //如果直接訪問(wèn)登錄頁(yè)面,則登錄成功后重定向到這個(gè)頁(yè)面,否則跳轉(zhuǎn)到之前想要訪問(wèn)的頁(yè)面
                        permitAll();

        //logout默認(rèn)的url是 /logout,如果csrf啟用,則請(qǐng)求方式是POST,否則請(qǐng)求方式是GET、POST、PUT、DELETE
        http.logout();
    }
}
  • 定義controller

我們?cè)L問(wèn)這個(gè)/sys/logout的url地址的時(shí)候,跳轉(zhuǎn)到退出頁(yè)面

    @GetMapping("/sys/logout")
    public String logout(){
        return "/jsp/logout";
    }
  • 定義退出頁(yè)面
<%@ 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>
  • 啟動(dòng)服務(wù),測(cè)試一下

訪問(wèn)http://localhost:8001/hello,跳轉(zhuǎn)到登錄頁(yè)面http://localhost:8001/sys/login,輸入正確的用戶名密碼之后跳轉(zhuǎn)到http://localhost:8001/hello,我們想退出,訪問(wèn)http://localhost:8001/sys/logout,跳轉(zhuǎn)到我們定義的退出頁(yè)面,因?yàn)槲覀兘昧薱srf模式,所以退出的請(qǐng)求方式是GET、POST、PUT、DELETE

我們打開(kāi)另外一個(gè)標(biāo)簽欄,點(diǎn)擊get請(qǐng)求,退出成功跳轉(zhuǎn)到登錄頁(yè)面,我們?cè)偃ブ暗臉?biāo)簽欄刷新http://localhost:8001/hello請(qǐng)求,發(fā)現(xiàn)又跳轉(zhuǎn)到登錄頁(yè)面http://localhost:8001/sys/login。

自定義退出

默認(rèn)的推出url是/logout。我們這邊定制的url及一些handler

  • 配置類如下:

我們定義了退出url,以及退出url的請(qǐng)求類型是get,定義了三個(gè)退出handler,定義了一個(gè)退出成功的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");

        //登錄的跳轉(zhuǎn)頁(yè)面,和登錄的動(dòng)作url不應(yīng)該有權(quán)限認(rèn)證。
        http.authorizeRequests().antMatchers("/sys/login").permitAll();
        //配置登出頁(yè)面的跳轉(zhuǎn)url地址也有權(quán)限訪問(wèn),不去跳轉(zhuǎn)到登錄頁(yè)面
        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的方式,能拿到具體失敗的原因,并且會(huì)將錯(cuò)誤信息以SPRING_SECURITY_LAST_EXCEPTION的key的形式將AuthenticationException對(duì)象保存到request域中
                        defaultSuccessUrl("/public/login/ok.html"). //如果直接訪問(wèn)登錄頁(yè)面,則登錄成功后重定向到這個(gè)頁(yè)面,否則跳轉(zhuǎn)到之前想要訪問(wèn)的頁(yè)面
                        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")  //成功退出的時(shí)候跳轉(zhuǎn)的頁(yè)面
                //.deleteCookies()  //底層也是使用Handler實(shí)現(xiàn)的額
                //清除認(rèn)證信息
                .clearAuthentication(true)
                .invalidateHttpSession(true)
        ;  //使session失效
    }
}
  • 修改登出頁(yè)面

修改get請(qǐng)求的鏈接地址是我們新配置的退出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>

  • 定義自己的退出成功頁(yè)面

logoutsuccess1.html頁(yè)面的內(nèi)容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    logout1 success
</body>
</html>
  • 啟動(dòng)服務(wù),測(cè)試一下

訪問(wèn)http://localhost:8001/hello,跳轉(zhuǎn)到登錄頁(yè)面http://localhost:8001/sys/login,輸入正確的用戶名密碼之后跳轉(zhuǎn)到http://localhost:8001/hello,我們想退出,訪問(wèn)http://localhost:8001/sys/logout,跳轉(zhuǎn)到我們定義的退出頁(yè)面


我們打開(kāi)另外一個(gè)標(biāo)簽欄,點(diǎn)擊get請(qǐng)求,退出成功跳轉(zhuǎn)到登錄頁(yè)面,我們?cè)偃ブ暗臉?biāo)簽欄刷新http://localhost:8001/hello請(qǐng)求,發(fā)現(xiàn)又跳轉(zhuǎn)到登錄頁(yè)面http://localhost:8001/sys/login。

控制臺(tái)打印:

[INFO] Session id node02vrs7ek2u7dfhgwg8q9azjxv0 swapped for new id node011kk0zpcbnr3p14se8mkozjue21
=====1=====
=====2======
=====3======
[INFO] Session node011kk0zpcbnr3p14se8mkozjue21 already being invalidated
=====4=======
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容