Spring Boot2.0 Oauth2 服务器和客户端配置及理
在Spring Boot 2.0中,OAuth2的配置和理解可以简化为以下几个步骤:
- 引入依赖:确保你的
pom.xml
或build.gradle
文件中包含了Spring Security和Spring Security OAuth2的依赖。
<!-- For Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
</dependency>
- 配置OAuth2服务器:在你的
application.properties
或application.yml
文件中配置OAuth2服务器的基本信息,例如客户端详情、授权模式、token存储等。
# application.yml配置示例
spring:
security:
oauth2:
client:
registration:
my-client:
client-id: client-id
client-secret: client-secret
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
scope: openid, profile, email
provider:
my-client:
authorization-uri: https://your-auth-server/auth
token-uri: https://your-auth-server/token
user-info-uri: https://your-auth-server/userinfo
user-name-attribute: sub
- 配置OAuth2客户端:如果你需要作为OAuth2客户端访问受保护的资源,你需要配置客户端信息,并确保有适当的授权头在API调用中。
@Configuration
@EnableOAuth2Client
public class OAuth2ClientConfig {
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
DefaultOAuth2AuthorizedClientManager manager = new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
return manager;
}
}
- 使用OAuth2客户端:在你的服务中,你可以使用
OAuth2AuthorizedClientManager
获取授权客户端来调用受保护的资源。
@RestController
public class MyController {
@Autowired
private OAuth2AuthorizedClientManager authorizedClientManager;
@GetMapping("/api/resource")
public String getResource(OAuth2AuthenticationToken token) {
OA
评论已关闭