注销不适用于Spring Boot和Spring Security

时间:2017-04-24 22:22:08

标签: spring spring-security thymeleaf logout

这是我使用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();
    }
}

使用Thyemleaf链接:

<li><a th:href="@{/login?logout}">logout</a></li>

2 个答案:

答案 0 :(得分:1)

尝试做这样的事情。

 <form th:action="@{/logout}" method="post">
     <input type="submit" value="Log out"/>
 </form>

Spring安全注销Url仅限POST。您可以通过更改Java配置

来支持非POST注销
protected void configure(HttpSecurity http) throws Exception {
  http
    // ...
    .logout()
       .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}

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

<li><a th:href="@{/logout}">logout</a></li>

答案 1 :(得分:-1)

请尝试以下方法:

    http
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?login_error=true")
            .loginProcessingUrl("/j_spring_security_check") //if needed
            .and()
                .authorizeRequests()
                .antMatchers("/index1").permitAll()
                .antMatchers("/user").hasRole("USER")
                .antMatchers("/adpage").hasRole("ADMIN")
            .and()
                .exceptionHandling().accessDeniedPage("/403")
            .and()
                .logout()
                .logoutSuccessUrl("/index") //or whatever page you want
                .logoutUrl("/logout") //thinking this is what you need
                .permitAll();

您的链接将是:

<li><a th:href="@{/logout}">logout</a></li>