为了在Spring启动中实现OAuth安全性,您必须通过分别从AuthorizationServerConfigurerAdapter
和扩展它们来创建授权和资源服务器ResourceServerConfigurerAdapter
。
@Configuration
@EnableAuthorizationServer
public class AuthorizationApplication extends AuthorizationServerConfigurerAdapter{
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints
.userDetailsService(userDetailsService)
.authenticationManager(this.authenticationManager).tokenStore(tokenStore()).approvalStoreDisabled();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(mongoClientDetailsService);
/*inMemory()
.withClient(propertyResolver.getProperty(PROP_CLIENTID))
.scopes("read", "write")
.authorities("ROLE_CLIENT")
.authorizedGrantTypes("password", "refresh_token","client_credentials")
.secret(propertyResolver.getProperty(PROP_SECRET))
.accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 18000));*/
}
//Do others stuff
}
此服务器配置中应提及您要使用OAuth保护的所有网址。它启用了一个Spring Security过滤器,该过滤器使用传入的OAuth2令牌对请求进行身份验证。虽然大多数WebSecurityConfigurerAdapter
扩展类用于基本安全配置,例如添加过滤器,允许使用不安全的url或实现会话策略等。
@Configuration
@EnableResourceServer
public class App extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/api/**").and().authorizeRequests()
.antMatchers("/api/**").authenticated();
}
//Do others stuff
}