前言
相关授权服务器搭建请参照:Spring Cloud oAuth2(一)搭建授权服务器以及访问
这里仅对学习Spring Cloud oAuth2过程中遇到的问题和相关过程做一个总结。
服务搭建
Spring Cloud版本Greenwich.SR2,Spring Boot版本2.1.10.RELEASE。
- 资源服务器pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 部分重要的yml配置:
security:
oauth2:
resource:
user-info-uri: http://localhost:9002/auth/user/current
client:
client-id: kevin
client-secret: kevin12345
access-token-uri: http://localhost:9002/auth/oauth/token
grant-type: password,refresh_token
scope: all
user-info-uri: 获取当前用户的token地址 client-id: 与授权服务器配置的对应(多个端自己注意) client-secret: 与授权服务器配置的对应(多个端自己注意) access-token-uri: 授权令牌地址 grant-type: 与授权服务器配置的对应(多个端自己注意) scope: 与授权服务器配置的对应(多个端自己注意)
- 配置资源服务器Resource Server
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/user/register").permitAll()
.anyRequest().authenticated();
}
}
- 配置OAuth2 Client
@Configuration
@EnableOAuth2Client
@EnableConfigurationProperties
public class OAuth2ClientConfig {
//访问各种受保护资源的客户端配置
@Bean
@ConfigurationProperties(prefix = "security.oauth2.client")
public ClientCredentialsResourceDetails clientCredentialsResourceDetails()
{
return new ClientCredentialsResourceDetails();
}
//拦截请求并且注入一个新的请求头,也是请求的存储库
@Bean
public RequestInterceptor OAuth2FeignRequestInterceptor()
{
return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(),clientCredentialsResourceDetails());
}
//使oauth2授权支持rest类型的请求
@Bean
public OAuth2RestTemplate ClientCredentialsRestTemplate()
{
return new OAuth2RestTemplate(clientCredentialsResourceDetails());
}
}
- 添加一个测试controller:
@RestController
public class ResourceController {
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/resource/test")
public String test()
{
return "hello,admin!";
}
}
资源服务器和客户端配置完成!
测试
1.post请求http://localhost:9002/auth/oauth/token?grant_type=password&password=12345&username=kevin&client_id=kevin&client_secret=kevin12345获取token:
2.添加Authorization中参数,请求地址localhost:9003/resource/test: