0

我正在尝试为基于角色的资源授权。如果我喜欢在Spring中Oauth2 @EnableResourceServer如何添加基于角色的请求匹配器

@Configuration 
@EnableResourceServer 
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { 

    @Override 
    public void configure(HttpSecurity http) throws Exception { 
     http 
       .requestMatcher(new OrRequestMatcher(
         new AntPathRequestMatcher("/hello"), 
         new AntPathRequestMatcher("/user") 
       )) 
       .authorizeRequests() 
       .anyRequest().access("#oauth2.hasScope('read')"); 
    } 

    @Override 
    public void configure(ResourceServerSecurityConfigurer resources) 
      throws Exception { 
     resources.resourceId("openid"); 
    } 

} 

如果我使用下面的方法,它将不适用于测试资源。

@Override 
    public void configure(HttpSecurity http) throws Exception { 
     // @formatter:off 
     http 
       .requestMatcher(new OrRequestMatcher(
         new AntPathRequestMatcher("/hello"), 
         new AntPathRequestMatcher("/user") 
       )) 
       .authorizeRequests() 
       .antMatchers("/test").hasRole("ADMIN") 
       .anyRequest().access("#oauth2.hasScope('read')"); 
    } 

它完全忽略了基于令牌的授权。我怎样才能实现这个?我得到的另一个问题是,如果我删除requestMatcher块,Oauth客户端无法获得授权码,在提交用户凭证登录表单后,它会重新加载登录页面。但与前面的代码块,它工作正常。我在这里做错了什么?

这里是我的安全配置类

@Configuration 
@EnableWebSecurity 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
       .authorizeRequests() 
       .antMatchers("/css/**").permitAll() 
       .antMatchers("/js/**").permitAll() 
       .antMatchers("/img/**").permitAll() 
       .anyRequest().authenticated() 
       .and() 
       .formLogin().loginPage("/login").permitAll() 
       .defaultSuccessUrl("/hello") 
       .and() 
       .logout() 
       .logoutUrl("/logout") 
       .logoutSuccessUrl("/login?logout"); 
    } 
} 

回答

0

当您使用的角色在春天,你必须使用前缀角色(例如ROLE_ADMIN),使其与默认设置工作。

+0

不,它不会工作,如果我这样做,我得到'java.lang.IllegalArgumentException:角色不应该以'ROLE_'开始,因为它会自动插入。有'ROLE_ADMIN'' –

相关问题