java - 为什么 /logout 调用会抛出“方法不允许”?
问题描述
我的应用程序使用 Spring Session (with Redis)。我使用自定义登录控制器,因为我使用外部 React 客户端,而不是默认的 Spring 登录页面。
登录控制器:
@PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE)
public String login(@RequestBody LoginDataTo loginData) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
loginData.getEmail(),
loginData.getPassword());
Authentication authentication = this.authenticationManager.authenticate(token);
SecurityContextHolder
.getContext()
.setAuthentication(authentication);
return "OK";
}
安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
http
.httpBasic().disable()
.formLogin().disable() // login form is disable, because i use external React client
.csrf().disable()
.cors().disable();
http
.logout()
.logoutUrl("/logout")
.invalidateHttpSession(true);
http
.authorizeRequests()
.antMatchers("/login").anonymous()
.antMatchers("/logout").authenticated()
.anyRequest().authenticated();
}
所以.../login
端点的工作是正确的。但是/logout
端点工作不正确。调用/logout
时,返回json:
{
"timestamp": "2021-03-30T13:45:09.142+00:00",
"status": 405,
"error": "Method Not Allowed",
"message": "",
"path": "/login"
}
这是我在 Postman 中使用的请求:
GET http://localhost:8080/logout
cookie 和 session 都被删除了,说明 logout 的工作是正确的,但是为什么会返回这个 json?
解决方案
我通过logoutSuccessHandler
设置解决了这个问题:
http
.logout()
.invalidateHttpSession(true)
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK));
现在/logout
调用返回200 OK。
推荐阅读
- c++ - 仅将需要的数据从一个大文件复制到另一个
- javascript - jQuery + SVG:无法访问 iFrame 中的 SVG 元素
- android - 没有这样的实例方法:'com.example.android.instagramclone.Login.LoginActivity.getCurrentUser'
- java - JPA/Hibernate 只写字段,没有读取
- intrinsics - 如何广播 __m256i 的最低单词?
- r - 如何使用 purrr 中的 map 和 dplyr 中的 mutate 来生成 glm 汇总表?
- uitableview - 错误当我从 tableview Swift 中删除一行时
- javascript - 使用 Jquery 删除所选项目(不在选项字段内)
- html - 如何使用按钮和HTML修复导航栏悬停问题
- language-agnostic - 迭代列表并执行两个操作的单个函数,或者每个执行自己的操作并分别迭代列表的两个函数?