首页 > 解决方案 > Spring Security 并没有像我想象的那样做

问题描述

我试图让它只有管理员可以查看/数据。邮递员允许用户和管理员访问它。想知道我做错了什么。

@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("admin").password("{noop}pw").roles("ADMIN").and()
            .withUser("user").password("{noop}pw").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .authorizeRequests()
            .antMatchers("**/data*").hasRole("ADMIN")
            .and().httpBasic();
        httpSecurity.csrf().disable();
    }
}

管理员应该能够访问数据/data而用户不应该。

标签: springsecurity

解决方案


尝试将 antMatchers 中的 URL 更改为从斜杠开始,然后重试。

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
        .authorizeRequests()
        .antMatchers("/**/data").hasRole("ADMIN")
        .and().httpBasic();
    httpSecurity.csrf().disable();
}

推荐阅读