注销不适用于 Spring Boot 和 Spring Security

taw*_*hid 0 spring spring-security logout thymeleaf

这是我使用 Spring Boot 和 Spring Security 的代码。问题是当我曾经注销(使用Thyemleaf)时,注销对我不起作用。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private DataSource dataSource;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth
            .jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery("select username as principal, password as credentials,active from users where username=?")
                .authoritiesByUsernameQuery("select username as principal,roles as role from users_roles where username=?")
                .rolePrefix("ROLE_")
                .passwordEncoder(new Md5PasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .formLogin()
                .loginPage("/login");
        http
            .authorizeRequests()
                .antMatchers("/index1").permitAll();
        http
            .authorizeRequests()
                .antMatchers("/user").hasRole("USER")
                .and()
            .logout();

        http
            .authorizeRequests()
                .antMatchers("/adpage").hasRole("ADMIN");
        http
            .exceptionHandling().accessDeniedPage("/403");
        http
            .logout().permitAll();
    }
}
Run Code Online (Sandbox Code Playgroud)

使用 Thyemleaf 链接:

<li><a th:href="@{/login?logout}">logout</a></li>
Run Code Online (Sandbox Code Playgroud)

Ahs*_*bal 5

尝试做这样的事情。

 <form th:action="@{/logout}" method="post">
     <input type="submit" value="Log out"/>
 </form>
Run Code Online (Sandbox Code Playgroud)

Spring 安全注销 URL 仅为 POST。您可以通过更改 Java 配置来支持非 POST 注销

protected void configure(HttpSecurity http) throws Exception {
  http
    // ...
    .logout()
       .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
Run Code Online (Sandbox Code Playgroud)

这样您就可以使用 GET 请求注销用户

<li><a th:href="@{/logout}">logout</a></li>
Run Code Online (Sandbox Code Playgroud)