Spring Security 使用logoutUrl和logoutSuccessUrl跳转显示404异常错误

当前文章收录状态:
未收录

解决方案

因为 spring security 在开启 csrf 防护的情况下,/logout 必须是以 POST 方法提交才行,<a> 标签请求是 GET 方法,所以报 404

1.很有可能开启了CSRF防护,可以关闭【不建议】

http.csrf().disable();

2.以 form 表单的形式请求 /logout 接口

<form th:action="@{/logout}" method="post">
<input type="hidden" name="${_csrf.parameterName }" value="${_csrf.token }"/>
<input type="submit" value="logout">
</form>
<form th:action="@{/logout}" method="post">
    <input type="hidden" name="${_csrf.parameterName }" value="${_csrf.token }"/>
    <input type="submit" value="logout">
</form>
<form th:action="@{/logout}" method="post"> <input type="hidden" name="${_csrf.parameterName }" value="${_csrf.token }"/> <input type="submit" value="logout"> </form>

3.在 spring security 的配置中,添加 /logout 能够以 GET 请求的配置

@Override
protected void configure(Http<a href="https://www.zym88.cn/tag/security" title="更多关于 Security 的文章" target="_blank">Security</a> http) throws Exception {
http.logout()
.<a href="https://www.zym88.cn/tag/logouturl" title="更多关于 logoutUrl 的文章" target="_blank">logoutUrl</a>("/logout")
.<a href="https://www.zym88.cn/tag/logoutsuccessurl" title="更多关于 logoutSuccessUrl 的文章" target="_blank">logoutSuccessUrl</a>("/home")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.and();
}
@Override
    protected void configure(Http<a href="https://www.zym88.cn/tag/security" title="更多关于 Security 的文章" target="_blank">Security</a> http) throws Exception {
        http.logout()
                .<a href="https://www.zym88.cn/tag/logouturl" title="更多关于 logoutUrl 的文章" target="_blank">logoutUrl</a>("/logout")
                .<a href="https://www.zym88.cn/tag/logoutsuccessurl" title="更多关于 logoutSuccessUrl 的文章" target="_blank">logoutSuccessUrl</a>("/home")
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
                .deleteCookies("JSESSIONID")
                .invalidateHttpSession(true)
                .and();
    }
@Override protected void configure(HttpSecurity http) throws Exception { http.logout() .logoutUrl("/logout") .logoutSuccessUrl("/home") .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET")) .deleteCookies("JSESSIONID") .invalidateHttpSession(true) .and(); }
© 版权声明
THE END
我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=270198dipw4ko
点赞6赞赏 分享
Seeing your adorable smile is the absolute best part of my day.
看见你可爱的笑容绝对是我一天中最美好的事
评论 抢沙发

请登录后发表评论

    暂无评论内容