我试图通过使用@PreAuthorize
批注保护控制器方法来增强OAuth2提供程序的安全性。我还添加了@EnableGlobalMethodSecurity
,因此@PreAuthorize
可与oauth一起使用。
这是我当前的设置:
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableResourceServer
@RestController
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@RequestMapping("/")
public String home() {
return "Hello World";
}
@PreAuthorize("#oauth2.clientHasRole('ROLE_CUSTOM')")
@RequestMapping("/a")
public String a() {
return "foo";
}
@PreAuthorize("#oauth2.clientHasRole('ROLE_TRUSTED_CLIENT')")
@RequestMapping("/b")
public String b() {
return "bar";
}
// So that @PreAuthorize notations would work
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public static class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
@Configuration
@EnableWebSecurity
public static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
}
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore());
}
@Bean
public ApprovalStore approvalStore() throws Exception {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore());
return store;
}
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// @formatter:off
clients.inMemory()
.withClient("my-trusted-client")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")
.resourceIds("oauth2-resource")
.accessTokenValiditySeconds(60)
.and()
.withClient("my-client-with-registered-redirect")
.authorizedGrantTypes("authorization_code")
.authorities("ROLE_CLIENT")
.scopes("read", "trust")
.resourceIds("oauth2-resource")
.redirectUris("http://anywhere?key=value")
.and()
.withClient("my-client-with-secret")
.authorizedGrantTypes("client_credentials", "password")
.authorities("ROLE_CLIENT","ROLE_CUSTOM")
.scopes("read")
.resourceIds("oauth2-resource")
.secret("secret");
// @formatter:on
}
}
}
当我删除
@PreAuthorize
表示法时,它会起作用,但是当我添加它们时,编译器会抛出大量缺少的自动连接异常注入,而且我无法真正查明或找出导致真正问题的原因。Here's my output
很抱歉,我目前无法提供任何其他输出或研究结果,有点卡住了。
最佳答案
尝试从其余配置中提取@RestController
类。
除了“全能”配置类难以维护之外,Spring可能在配置方法安全性以及在同一类中使用方法安全性方面存在问题。
关于java - Spring Oauth2提供者PreAuthorize无法注入(inject)自动连线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39103842/