Log out doesn't work in Spring Boot application (POST method not supported)

DP_*_*DP_ 3 java authentication spring kotlin spring-boot

I have a Spring Boot application with the following configuration

@Configuration
@EnableWebSecurity
open class WebSecurityConfig : WebSecurityConfigurerAdapter() {
    override fun configure(http:HttpSecurity) {
        http
            .authorizeRequests()
                .antMatchers("/css/**", "/js/**", "/fonts/**")
                .permitAll().and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .logout() 
                .logoutSuccessUrl("/login") 
                .permitAll()
            .and().csrf().disable()
    }
    @Autowired
    fun configureGlobal(auth:AuthenticationManagerBuilder) {
        auth
            .inMemoryAuthentication()
                .withUser("usr@provider.com").password("test").roles("USER")
    }
}
Run Code Online (Sandbox Code Playgroud)

When I try to log out, I get the error

There was an unexpected error (type=Method Not Allowed, status=405). Request method 'POST' not supported

How can I fix it?

How to reproduce

  1. 查看此存储库中的代码。
  2. gradle bootRun
  3. 转到http://localhost:8080,分别输入usr@provider.comtest作为用户名和密码。
  4. 按退出按钮。

更新 1:这也不起作用。

http
    .authorizeRequests()
        .antMatchers("/css/**", "/js/**", "/fonts/**", "/logout??")
        .permitAll().and()
    .formLogin()
        .loginPage("/login")
        .permitAll()
        .and()
    .authorizeRequests()
        .anyRequest().authenticated()
        .and()
    .csrf().disable()
Run Code Online (Sandbox Code Playgroud)

小智 5

我不熟悉 Thymeleaf,但至少这会给你一些想法。

问题不在于您的 SecurityConfig,而在于

th:action="@{/注销}"

(不重定向到 /logout,检查 Chrome 或 Firefox 中的网络选项卡)。

如果我用它替换它

动作=“/注销”

然后它完美地工作。