ver*_*tti 12 spring spring-security oauth-2.0
我已经在另一个项目中运行了OAuth2授权服务器.现在我需要使用OAuth2来保护几个简单的spring-boot rest-servers.但是我发现Spring文档在分离授权和资源服务器时确实非常有限.
我还发现了几个问题,答案是"只要它们共享相同的tokenStore数据源,它们就可以是不同的盒子".这真的可以吗?这怎么可能对微服务有用?每个休息服务都需要实现它自己的OAuth授权服务器,这似乎是一件非常奇怪的事情.
那么如何为引用远程oauth授权服务器的spring-boot rest-endpoints设置Oauth2.0安全性(可能甚至不用Spring编写)?
这个名为RemoteTokenServices的东西似乎很有希望,但根本没有记录.
Pra*_*hah 14
配置你的auh服务器::
ClientDetailsServiceConfigurer为资源服务器创建一个新的clientDetails .这将用于配置RemoteTokenService.
在资源服务器中配置Spring Security OAuth2:
创建一个带注释的类@EnableWebSecurity,@Configuration并进行扩展WebSecurityConfigurerAdapter.
@Configuration
@EnableWebSecurity
protected static class ResourceConfiguration extends WebSecurityConfigurerAdapter {
// methods
}
Run Code Online (Sandbox Code Playgroud)
使用@Bean注释创建一个方法,该方法将返回TokenService将用于创建的实例AuthenticationManager.
在这个方法中创建一个实例RemoteTokenService并设置clientId,client_secret,checkTokenEndpointUrl和DefaultAccessTokenConverterWithClientRoles(这个类是我们在OAuth2服务器中验证accessToken时获取client_authority的实现.)
@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;
}
Run Code Online (Sandbox Code Playgroud)
替代authenticationManagerBean()方法及标注它@Bean,并返回的实例OAuth2AuthenticationManager与TokenService注射.
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
OAuth2AuthenticationManager authenticationManager = new OAuth2AuthenticationManager();
authenticationManager.setTokenServices(tokenService());
return authenticationManager;
}
Run Code Online (Sandbox Code Playgroud)
创建一个用@EnableResourceServer,注释@Configuration和扩展的类 ResourceServerConfigurerAdapter.
@Configuration
@EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
// Mehotds
}
Run Code Online (Sandbox Code Playgroud)
覆盖配置方法构成超类以配置资源服务器.不同的配置器配置资源服务器.
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
}
Run Code Online (Sandbox Code Playgroud)
.antMatcher("/**").authenticated()这一行将保护资源服务器的每个api url.
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 不会创建会话.
PS ::如果有什么不对的话请告诉我.
| 归档时间: |
|
| 查看次数: |
7889 次 |
| 最近记录: |