Spring Boot安全性登录验证失败

Spring boot security login verify failed

我想在用户发送localhost:8080/submit请求时验证其身份,因此我在SecurityConfig类中添加了以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/submit").access("hasRole('WORKER')")
            .antMatchers("/**").permitAll()
            .and()
            .formLogin()
            .loginPage("/login")
            .and()
            .logout()
            .logoutSuccessUrl("/")
            .and()
            .rememberMe()
            .tokenValiditySeconds(4838400)
            .key("workerKey");
}

我希望当我在地址字段中输入localhost:8080/submit时,页面可以重定向到localhost:8080/login。我的工人实体的角色为" WORKER ":

1
2
3
4
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return Arrays.asList(new SimpleGrantedAuthority("WORKER"));
}

当我输入" localhost:8080 / submit "时,我可以注册一个帐户并重定向到登录页面。但是,当我输入正确的用户名和密码时,它会响应我一个错误页面,而不是提交页面:

There was an unexpected error (type=Forbidden, status=403).
Forbidden

我的提交页面只是一个" welcome "单词页面。我的映射是

1
2
3
4
5
6
7
8
9
@RequestMapping(value ="/login", method = RequestMethod.GET)
public String showLogin() {
    return"login";
}

@RequestMapping(value ="/submit", method = RequestMethod.GET)
public String showSubmit() {
    return"submit";
}

当我再次输入localhost:8080/submit时,它这次没有重定向到登录页面。而是直接将其重定向到错误页面并显示相同的错误。那是什么禁止我重定向到提交页面?


我自己发现了问题。我需要将Worker类中的角色" WORKER"更改为" ROLE_WORKER"。像这样

1
2
3
4
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return Arrays.asList(new SimpleGrantedAuthority("ROLE_WORKER"));
}

似乎我无法在Worker类中将角色" ROLE_WORKER"简化为" WORKER",但可以在SecurityConfig类中对其进行简化。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().anyRequest().fullyAuthenticated()

                .antMatchers("/submit").hasRole("WORKER").and().formLogin().permitAll().and().logout().permitAll();

    }

    @Bean
    public UserDetailsService userDetailsService() {
        // ensure the passwords are encoded properly
        @SuppressWarnings("deprecation")
        UserBuilder users = User.withDefaultPasswordEncoder();
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(users.username("me").password("me").roles("WORKER").build());
        return manager;
    }

}

您可以使用自定义login page进行更多自定义。