java实现oauth2.0 客户端
时间: 2023-10-04 14:10:17 浏览: 59
在 Java 中实现 OAuth2 客户端通常需要使用 OAuth2 客户端库,以下是使用 Spring Security OAuth2 客户端的示例代码:
1. 添加依赖
在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
```
2. 配置授权服务器信息
在 application.yml 或 application.properties 文件中添加授权服务器信息:
```yaml
spring:
security:
oauth2:
client:
registration:
my-client:
client-id: my-client-id
client-secret: my-client-secret
authorization-grant-type: authorization_code
redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'
scope: user
client-name: My Client
provider:
my-provider:
authorization-uri: https://example.com/oauth2/authorize
token-uri: https://example.com/oauth2/token
user-info-uri: https://example.com/oauth2/userinfo
user-name-attribute: sub
```
其中,`my-client` 和 `my-provider` 是自定义的标识符,用于区分不同的客户端和提供商。`client-id` 和 `client-secret` 是从授权服务器获取的客户端 ID 和密钥。`authorization-grant-type` 指定授权类型,这里是授权码模式。`redirect-uri` 是回调 URL,用于接收授权码。`scope` 是请求的权限范围,这里是请求用户信息。`authorization-uri` 是授权服务器的授权页面 URL,`token-uri` 是获取访问令牌的 URL,`user-info-uri` 是获取用户信息的 URL,`user-name-attribute` 是用户标识符在用户信息中的属性名。
3. 创建登录页面
在 Thymeleaf 模板中创建登录页面:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login Page</title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<h2>Login with OAuth2</h2>
<a th:href="@{/oauth2/authorization/my-provider}">Login with My Provider</a>
</body>
</html>
```
其中,`/oauth2/authorization/my-provider` 是登录链接,`my-provider` 是之前配置的提供商标识符。
4. 创建回调页面
在 Thymeleaf 模板中创建回调页面:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>OAuth2 Callback Page</title>
</head>
<body>
<script>
function closeWindow() {
window.opener.location.reload();
window.close();
}
closeWindow();
</script>
</body>
</html>
```
其中,使用 JavaScript 关闭弹出窗口并刷新父窗口。
5. 创建安全配置
创建一个继承 `WebSecurityConfigurerAdapter` 的安全配置类:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/login**", "/webjars/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.loginPage("/")
.defaultSuccessURL("/home")
.failureUrl("/?error=true")
.and()
.logout()
.logoutSuccessUrl("/")
.permitAll();
}
}
```
其中,`configure()` 方法配置了请求授权规则和 OAuth2 登录的相关参数,`.antMatchers()` 指定了不需要认证的 URL,`.oauth2Login()` 配置了 OAuth2 登录的参数,`.loginPage()` 指定了登录页面 URL,`.defaultSuccessURL()` 指定了登录成功后的默认 URL,`.failureUrl()` 指定了登录失败后的 URL,`.logout()` 配置了注销登录的参数。
6. 创建控制器
创建一个控制器处理回调请求和获取用户信息:
```java
@Controller
public class OAuth2Controller {
@GetMapping("/home")
public String home(Model model, OAuth2AuthenticationToken authentication) {
OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(authentication.getAuthorizedClientRegistrationId(), authentication.getName());
model.addAttribute("userName", client.getPrincipalName());
return "home";
}
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/logout")
public String logout() {
return "logout";
}
@Autowired
private OAuth2AuthorizedClientService authorizedClientService;
@GetMapping("/login/oauth2/code/{registrationId}")
public String callback(@PathVariable String registrationId, OAuth2AuthenticationToken authentication) {
OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(registrationId, authentication.getName());
return "redirect:/home";
}
}
```
其中,`home()` 方法获取用户信息并返回到 home.html 模板,`login()` 方法返回到登录页面,`logout()` 方法返回到注销页面,`callback()` 方法处理回调请求并获取 OAuth2 客户端。
这就是使用 Spring Security OAuth2 客户端实现 OAuth2 客户端的基本流程。