【问题标题】:Allow access to url pattern only for a specific role in spring security仅允许对 Spring Security 中的特定角色访问 url 模式
【发布时间】:2018-07-24 22:36:41
【问题描述】:

我正在尝试仅允许具有“管理员”角色的用户访问以下端点:

../adminconfig/*(那些在 url 中有 'adminconfig' 的)

这是我的配置:

@SpringBootApplication
@EnableWebSecurity
@RestController
public class BootApplication extends WebSecurityConfigurerAdapter {


    public static void main(String[] args) {
        SpringApplication.run(BootApplication.class, args);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("{noop}1").roles("USER").and()
                .withUser("admin").password("{noop}1").roles("ADMIN");
    }

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

        http
                .authorizeRequests()

                .anyRequest().authenticated()
                .antMatchers("/adminconfig/**").hasRole("ADMIN")
                .and()
                .formLogin().and()
                .httpBasic();
    }

}

但我仍然可以使用任何其他用户访问它们,例如使用“USER”角色。我做错了什么?

【问题讨论】:

标签: spring spring-security


【解决方案1】:

找到了解决办法。我不得不将 antMatchers().. 移到 .anyRequest().authenticated() 上方:

            .antMatchers("/adminconfig/**").hasRole("ADMIN")
            .anyRequest().authenticated()

【讨论】:

    猜你喜欢
    • 2014-05-29
    • 2014-10-22
    • 2018-10-03
    • 2015-02-21
    • 1970-01-01
    • 2011-01-07
    • 2015-10-09
    • 2020-09-07
    • 1970-01-01
    相关资源
    最近更新 更多