Spring security-端点仅用于管理员

问题描述 投票:0回答:1

我想使角色“ Administrator”的“用户”可通过端点“ / admin / **”访问,很遗憾,目前没有人可以访问此API。我做错了

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/login/").permitAll()
                .antMatchers("/api/books/*").authenticated()
                .antMatchers("/api/admin/**").hasAuthority("Administrator")
                .and()
                .addFilter(new JwtFilter(authenticationManager()))
                .csrf().disable();

    }
}
spring-boot api security
1个回答
0
投票

虽然使用hasAuthority()方法,但您需要添加前缀ROLE_,如下所示。另外,请确保将前缀为ROLE_的角色存储在数据库中。

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/login/").permitAll()
            .antMatchers("/api/admin/**").hasAuthority("ROLE_Administrator")
            .antMatchers("/api/books/*").authenticated()
            .and()
            .addFilter(new JwtFilter(authenticationManager()));

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.