首页 > 解决方案 > 为什么 /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?

标签: javaspringspring-bootspring-securityspring-session

解决方案


我通过logoutSuccessHandler设置解决了这个问题:

http
    .logout()
    .invalidateHttpSession(true)
    .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK));

现在/logout调用返回200 OK


推荐阅读