springboot整合Oauth2
时间: 2023-05-15 08:06:10 浏览: 79
可以使用 Spring Security OAuth2 来实现 Spring Boot 和 OAuth2 的整合。具体步骤如下:
1. 添加 Spring Security OAuth2 依赖
在 pom.xml 文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
```
2. 配置 OAuth2 客户端
在 application.yml 文件中添加以下配置:
```
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
```
3. 配置 Spring Security
在 SecurityConfig 类中添加以下配置:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login**", "/error**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login();
}
}
```
4. 创建控制器
创建一个控制器来处理 OAuth2 登录成功后的回调:
```
@Controller
public class OAuth2Controller {
@GetMapping("/oauth2/callback")
public String callback() {
return "redirect:/";
}
}
```
5. 运行应用程序
现在,您可以运行应用程序并访问 http://localhost:8080/login,然后选择 Google 登录。如果您已经登录了 Google 帐户,则应用程序将自动登录并重定向到 http://localhost:8080/。