springboot集成oauth
时间: 2023-09-03 09:15:40 浏览: 43
2.0
OAuth2.0是一种基于授权协议的开放式标准,允许用户授权第三方应用访问他们的资源。在Spring Boot中,可以通过集成Spring Security来实现OAuth2.0授权。
以下是在Spring Boot中集成OAuth2.0的步骤:
1. 添加依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
```
2. 配置OAuth2.0客户端
在application.yml文件中添加以下配置:
```
spring:
security:
oauth2:
client:
registration:
google:
client-id: <google-client-id>
client-secret: <google-client-secret>
scope:
- email
- profile
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/v2/auth
token-uri: https://www.googleapis.com/oauth2/v4/token
user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
user-name-attribute: sub
```
这里以Google为例,配置了一个OAuth2.0客户端,包括客户端ID和客户端密钥,以及授权范围和提供商的授权、令牌和用户信息URI。
3. 配置Spring Security
在SecurityConfig类中添加以下配置:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login()
.loginPage("/login")
.defaultSuccessURL("/home")
.and()
.logout()
.logoutSuccessUrl("/login")
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("USER");
}
}
```
这里配置了一个简单的安全配置,允许所有用户访问主页,但要求已验证用户访问其他页面。此外,还配置了OAuth2.0登录、注销和CSRF保护。
4. 创建登录页面
在src/main/resources/templates目录下创建login.html文件,添加以下内容:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form th:action="@{/login/oauth2/google}" method="post">
<button type="submit">Sign in with Google</button>
</form>
</body>
</html>
```
这里创建了一个简单的登录页面,允许用户使用Google帐户登录。
5. 运行应用程序
运行Spring Boot应用程序,并访问http://localhost:8080/login,应该会看到一个Google登录按钮。单击该按钮,将被重定向到Google登录页面,完成登录后将返回主页。
这就是在Spring Boot中集成OAuth2.0的基本步骤。当然,在实际应用中,可能需要更复杂的配置和更严格的安全措施。