在配置您的 auh 服务器时::
在ClientDetailsServiceConfigurer 中为资源服务器创建一个新的clientDetails。将用于配置RemoteTokenService。
在资源服务器中配置 Spring Security OAuth2:
创建一个使用@EnableWebSecurity、@Configuration 注释并扩展WebSecurityConfigurerAdapter 的类。
@Configuration
@EnableWebSecurity
protected static class ResourceConfiguration extends WebSecurityConfigurerAdapter {
// methods
}
创建一个带有@Bean 注解的方法,该方法将返回TokenService 的实例,该实例将用于创建AuthenticationManager。
在这个方法中创建一个RemoteTokenService的实例并设置clientId、client_secret、checkTokenEndpointUrl和DefaultAccessTokenConverterWithClientRoles(这个类是我们在验证accessToken时获取client_authority的实现在 OAuth2 服务器中。)
@Bean
public ResourceServerTokenServices tokenService() {
RemoteTokenServices tokenServices = new RemoteTokenServices();
tokenServices.setClientId("resource_id");
tokenServices.setClientSecret("resource_secret");
tokenServices.setCheckTokenEndpointUrl("http://<server-url>: <port>/oauth/check_token");
return tokenServices;
}
覆盖authenticationManagerBean() 方法并使用@Bean 对其进行注释,并返回一个OAuth2AuthenticationManager 的实例并注入TokenService。
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
OAuth2AuthenticationManager authenticationManager = new OAuth2AuthenticationManager();
authenticationManager.setTokenServices(tokenService());
return authenticationManager;
}
创建一个用@EnableResourceServer、@Configuration注解的类并扩展ResourceServerConfigurerAdapter。
@Configuration
@EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
// Mehotds
}
覆盖超类的配置方法来配置资源服务器。
不同的配置器来配置资源服务器。
ResourceServerSecurityConfigurer:配置Resource_id。
HttpSecurity:这将配置安全过滤器,告诉它用户需要对受保护的 URL (API) 进行身份验证。
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("resource_id");
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/**").authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// @formatter:on
}
.antMatcher("/**").authenticated() 这一行将保护资源服务器的每个 api url。
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 不会创建会话。
PS:: 如果有什么不对的,请告诉我。