我已配置以下应用程序
@SpringBootApplication
@EnableResourceServer
@RestController
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@RequestMapping("/home")
public String home() {
return "Hello World";
}
@RequestMapping("/reg/a")
public String reg() {
return "REGISTERED";
}
@RequestMapping(value = "/", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public String create(@RequestBody MultiValueMap<String, String> map) {
return "OK";
}
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("my-client-with-secret")
.authorizedGrantTypes("client_credentials", "password")
.authorities("ROLE_CLIENT")
.scopes("read")
.resourceIds("oauth2-resource")
.secret("secret");
}
}}
和
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class OAuth2WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean(name="authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManager();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
String password = "pass";
String user = "user";
auth.inMemoryAuthentication()
.withUser(user).password(password).roles("USER")
.and().withUser("admin").password("admin").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers().antMatchers("/reg/**")
.and()
.authorizeRequests()
.antMatchers("/reg/**").access("hasRole('ADMIN')");
}
}
我可以使用下面的url使用user / pass
生成访问令牌以后
http://localhost:8080/reg/a?access_token=bd280b8e-b0b0-47a7-96d9-b4f3bfa60692
永远不会根据角色阻止/抛出授权错误,我尝试了不同的方式,如下所示,但没有任何效果
hasAccess(“#oauth2.hasRole('ADMIN')”),hasAuthority('ADMIIN'), hasRole( 'ADMIIN')
非常感谢任何帮助,提前谢谢。