zer*_*gen 9 spring-security oauth-2.0 spring-security-oauth2 spring-cloud
我想开发两个独立的服务,一个用于业务,一个用于使用Spring OAuth 2进行用户身份验证
我们称之为商业服务和OAuth服务.
现在,如果请求未经过身份验证,我希望将Business-Service委托给OAuth-Service.客户端应用程序(Android应用程序)不应该事先知道OAuth-Service,它应该只由Business-Service委托给它,并且302 HTTP重定向用于非认证请求.确切地说,我希望我的API登录页面提供指向http://businessservice.com/login的链接,当我的客户端应用程序决定关注此链接时,它会被重定向到OAuth-Service.
如果我使用@ EnableOAuth2Resource注释Business-Service ,那么当我在没有访问令牌的情况下卷曲它时,它的所有资源都会受到保护,返回401.到现在为止还挺好.如果我提供这样的访问令牌:
curl -v http://localhost:8667/resource/ -H "Authorization: Bearer $TOKEN"
Run Code Online (Sandbox Code Playgroud)
我可以访问该资源.还好.
但是,如果我使用@ EnableOAuth2Sso注释业务服务以启用重定向到OAuth服务,则会失去使用访问令牌访问资源的功能(与上面相同的卷曲),它只返回302到登录页面http: //本地主机:8667 /登录
如果我同时使用两个注释,@ EnableOAuth2Resource似乎总是"赢",因为身份验证有效,但调用http:// localhost:8667/login返回404.
那么创建一个委托给auth服务器进行非认证调用的资源服务器的正确方法是什么?
经过几个小时的尝试后,我现在找到了解决方案。
业务服务器(资源服务器)现在如下所示:
@SpringBootApplication
@EnableOAuth2Sso
@EnableOAuth2Resource
public class BusinessService {
public static void main(final String[] args) {
final ConfigurableApplicationContext context = SpringApplication.run(BusinessService.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
有两种配置,一种用于 SSO:
@Configuration
public class OAuth2SsoConfiguration extends OAuth2SsoConfigurerAdapter {
@Override
public void match(final RequestMatchers matchers) {
matchers.antMatchers("/");
}
@Override
public void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
}
}
Run Code Online (Sandbox Code Playgroud)
以及一个资源:
@Configuration
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(final HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/resource/**").and().authorizeRequests().anyRequest().authenticated().antMatchers("/").permitAll();
}
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
curl -v http://localhost:8667/
Run Code Online (Sandbox Code Playgroud)
回报
HTTP/1.1 200 OK
{"links":[{"rel":"login","href":"http://localhost:8667/login"}]}
Run Code Online (Sandbox Code Playgroud)
curl -v http://localhost:8667/resource/
Run Code Online (Sandbox Code Playgroud)
回报
HTTP/1.1 401 Unauthorized
{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}
Run Code Online (Sandbox Code Playgroud)
curl -v http://localhost:8667/login
Run Code Online (Sandbox Code Playgroud)
回报
HTTP/1.1 302 Found
Location: http://localhost:8666/user/oauth/authorize?client_id=clientId&redirect_uri=http%3A%2F%2Flocalhost%3A8667%2Flogin&response_type=code&state=YmmNO9
Run Code Online (Sandbox Code Playgroud)
因此,我的业务服务受到保护,资源服务器为所有业务资源返回 401。服务的根适用于所有客户端,因此他们可以发现登录关系,如果他们遵循此关系,他们将被重定向到授权服务器
| 归档时间: |
|
| 查看次数: |
5756 次 |
| 最近记录: |