调用 spring security 默认的 logout 接口报 404
thymeleaf 前端代码:
<div class="dropdown-menu dropdown-menu-left" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" th:href="@{/logout}">退出</a>
</div>
请问是啥情况?
1 个解决方案
因为 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>
3.在 spring security 的配置中,添加 /logout
能够以 GET
请求的配置
@EnableWebSecurity
@EnableGlobalMethodSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
/**
* http 权限控制
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 资源访问控制
http.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/home")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.and();
}
}