【发布时间】:2021-06-26 13:59:33
【问题描述】:
我的应用使用 Spring Session(使用 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呢?
【问题讨论】:
-
@Zhenyria 默认注销重定向到登录页面。此重定向是一个
GET请求,但您的登录控制器没有GET的映射。这就是你的问题的原因。要解决此问题,请为GET添加到控制器的映射或更改默认重定向(就像您在回答中所做的那样)。
标签: java spring spring-boot spring-security spring-session