将OAuth2配置到springboot请给示例代码
时间: 2024-04-07 11:31:42 浏览: 17
好的,以下是一个简单的示例代码,可以将OAuth2配置到Spring Boot应用程序中:
首先,需要在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
```
然后,在Spring Boot应用程序的配置文件中添加以下配置:
```yaml
server:
port: 8080
spring:
security:
oauth2:
client:
registration:
google:
client-id: <your-client-id>
client-secret: <your-client-secret>
scope:
- email
- profile
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/auth
token-uri: https://accounts.google.com/o/oauth2/token
user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
user-name-attribute: sub
```
在上面的配置中,我们添加了一个名为“google”的OAuth2客户端,并设置了客户端ID和客户端密钥。我们还指定了要请求的Scope(email和profile)以及提供程序的授权URI,令牌URI和用户信息URI。
最后,在我们的Spring Boot应用程序中添加一个OAuth2保护资源:
```java
@RestController
public class HelloWorldController {
@GetMapping("/")
@PreAuthorize("hasAuthority('ROLE_USER')")
public String helloWorld() {
return "Hello World!";
}
}
```
在上面的代码中,我们使用@PreAuthorize注释来确保只有具有ROLE_USER权限的用户才能访问我们的保护资源。
希望这个示例能够帮助你将OAuth2配置到Spring Boot应用程序中。