如何在Spring Boot安全性中配置站点授权?

时间:2019-05-12 03:59:24

标签: spring-boot spring-security

我在Spring Boot安全性上有一些授权问题。首先在application.properties中,键入如下的角色查询,

# MySQL Queries for AuthenticationManagerBuilder
spring.queries.users-query = SELECT username, password, role FROM blog_user WHERE username=?
spring.queries.roles-query = SELECT username, role FROM blog_user WHERE username=?

我进行了Spring Boot安全配置

@Configuration
@EnableWebSecurity
public class BlogWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Value("${spring.queries.users-query}")
    private String usersQuery;

    @Value("${spring.queries.roles-query}")
    private String rolesQuery;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // TODO Auto-generated method stub
        auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        http.csrf().disable()
            .authorizeRequests()
                .antMatchers("/" ,"/home*", "/js/**", "/css/**", "/icon/**", "/users/login", "/users/register").permitAll()
                .antMatchers("/users", "/posts/create", "posts/view", "/tags/create").hasAnyRole("USER") // only .permitAll() method makes it work.
                .anyRequest().authenticated()
                .and() 
            .formLogin()
                .loginPage("/users/login").defaultSuccessUrl("/")
                .usernameParameter("username").passwordParameter("password")
                .and()
            .logout()
                .invalidateHttpSession(true)
                .clearAuthentication(true)
                .logoutSuccessUrl("/").and()
            .exceptionHandling().accessDeniedPage("/error/403");
    }

     @Bean 
     public PasswordEncoder passwordEncoder() {
         return new BCryptPasswordEncoder();
     }
}

.hasAnyRole("USER")行效果不好。网站“ /用户”,“ /帖子/创建”,“帖子/视图”,“ /标签/创建”会引发404错误。我的意思是我的“ USER”角色代码有一些问题。当我将角色方法.hasAnyRole("USER")更改为.permitAll()方法时,它就起作用了。如何在系统中输入正确的授权角色代码?

1 个答案:

答案 0 :(得分:1)

Blog_user表中的role值应以ROLE_作为前缀(即,应为ROLE_USER)。

Spring Security 4在检查hasRole()时总是添加ROLE_前缀。 有关更多信息,请参见Spring security 3 to 4 migration guide