经过几个小时的尝试后,我现在找到了解决方案。
业务服务器(资源服务器)现在如下所示:
@SpringBootApplication
@EnableOAuth2Sso
@EnableOAuth2Resource
public class BusinessService {
public static void main(final String[] args) {
final ConfigurableApplicationContext context = SpringApplication.run(BusinessService.class, args);
}
}
有两种配置,一种用于 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();
}
}
以及一个资源:
@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();
}
}
结果如下:
curl -v http://localhost:8667/
returns
HTTP/1.1 200 OK
{"links":[{"rel":"login","href":"http://localhost:8667/login"}]}
curl -v http://localhost:8667/resource/
returns
HTTP/1.1 401 Unauthorized
{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}
curl -v http://localhost:8667/login
returns
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
因此,我的业务服务受到保护,资源服务器为所有业务资源返回 401。服务的根适用于所有客户端,因此他们可以发现登录关系,如果他们遵循此关系,他们将被重定向到授权服务器