经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 软件/图像 » Git » 查看文章
Spring Boot整合OAuth2实现GitHub第三方登录
来源:cnblogs  作者:JavaCoderPan  时间:2023/10/25 18:52:09  对本文有异议

Github OAuth 第三方登录示例

1、第三方登录原理

第三方登录的原理是借助OAuth授权来实现,首先用户先向客户端提供第三方网站的数据证明自己的身份获取授权码,然后客户端拿着授权码与授权服务器建立连接获得一个Access Token,之后客户端就可以通过Access Token来与资源服务器进行交互。

使用OAuth的好处是提供给用户一个特定的密钥,用户持有这个密钥可以访问应用中的任何信息,而不需要向网站提供用户名&密码,可以实现跨系统共享用户授权协议。

通过控制用户持有的密钥,可以很方便的控制用户可以访问的资源,以及控制密钥的过期时间。

以下是来自维基百科对于OAuth的介绍

开放授权(OAuth)是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用。

OAuth允许用户提供一个令牌,而不是用户名和密码来访问他们存放在特定服务提供者的数据。每一个令牌授权一个特定的网站(例如,视频编辑网站)在特定的时段(例如,接下来的2小时内)内访问特定的资源(例如仅仅是某一相册中的视频)。这样,OAuth让用户可以授权第三方网站访问他们存储在另外服务提供者的某些特定信息,而非所有内容。

OAuth是OpenID的一个补充,但是完全不同的服务。

交互流程如下:

2、GitHub实现第三方登录

首先需要在github中对应用进行登记,让Github知道谁在发送请求。

访问这个网址,填写登记表

提交成功之后,GitHub会返回Client ID & Client Secrets ,这是应用的身份识别码

创建一个SpringBoot工程,pom.xml文件内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.7.17</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>org.pp</groupId>
  12. <artifactId>springboot-oauth2-api</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springboot-oauth2-api</name>
  15. <description>springboot整合oauth2,实现GitHub第三方登录</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-web</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  27. </dependency>
  28. </dependencies>
  29. <build>
  30. <plugins>
  31. <plugin>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-maven-plugin</artifactId>
  34. <configuration>
  35. <excludes>
  36. <exclude>
  37. <groupId>org.projectlombok</groupId>
  38. <artifactId>lombok</artifactId>
  39. </exclude>
  40. </excludes>
  41. </configuration>
  42. </plugin>
  43. </plugins>
  44. </build>
  45. </project>

将ID和密钥添加到配置文件application.yml中:

  1. # 项目端口号
  2. server:
  3. port: 8080
  4. # GitHub认证相关参数
  5. github:
  6. client:
  7. id: xxx
  8. secret: xxx

创建一个实体类,用于映射授权成功产生的Token令牌:

  1. import com.fasterxml.jackson.annotation.JsonProperty;
  2. /**
  3. *
  4. * Token令牌 - 响应参数
  5. *
  6. * @author supanpan
  7. * @date 2023/10/25
  8. */
  9. public class AccessTokenResponse {
  10. @JsonProperty("access_token")
  11. private String accessToken;
  12. public String getAccessToken() {
  13. return accessToken;
  14. }
  15. public void setAccessToken(String accessToken) {
  16. this.accessToken = accessToken;
  17. }
  18. }

OAuthController如下:

  1. **
  2. * @author supanpan
  3. * @date 2023/10/25
  4. */
  5. @Controller
  6. public class OAuthController {
  7. @Value("${github.client.id}")
  8. private String clientId;
  9. @Value("${github.client.secret}")
  10. private String clientSecret;
  11. @GetMapping("/oauth/redirect")
  12. public String handleRedirect(@RequestParam("code") String requestToken, Model model) {
  13. // 使用RestTemplate来发送HTTP请求
  14. RestTemplate restTemplate = new RestTemplate();
  15. // 获取Token的Url
  16. String tokenUrl = "https://github.com/login/oauth/access_token" +
  17. "?client_id=" + clientId +
  18. "&client_secret=" + clientSecret +
  19. "&code=" + requestToken;
  20. // 使用restTemplate向GitHub发送请求,获取Token
  21. AccessTokenResponse tokenResponse = restTemplate.postForObject(tokenUrl, null, AccessTokenResponse.class);
  22. // 从响应体中获取Token数据
  23. String accessToken = tokenResponse.getAccessToken();
  24. // 携带Token向GitHub发送请求
  25. String apiUrl = "https://api.github.com/user";
  26. HttpHeaders headers = new HttpHeaders();
  27. headers.set("Authorization", "token " + accessToken);
  28. HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
  29. ResponseEntity<String> response = restTemplate.exchange(apiUrl, HttpMethod.GET, entity, String.class);
  30. model.addAttribute("userData", response.getBody());
  31. return "welcome";
  32. }
  33. }

SpringBoot启动器

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. @SpringBootApplication
  4. public class SpringbootOauth2ApiApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(SpringbootOauth2ApiApplication.class, args);
  7. }
  8. }

还需要编写两个html页面,index.html和welcome.html

index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <title>OAuth2 Demo</title>
  7. <meta name="viewport" content="width=device-width, initial-scale=1">
  8. </head>
  9. <body>
  10. <a id="login">Login with GitHub</a>
  11. <script>
  12. const client_id = 'xxxx';
  13. const authorize_uri = 'https://github.com/login/oauth/authorize';
  14. const redirect_uri = 'http://localhost:8080/oauth/redirect';
  15. const link = document.getElementById('login');
  16. link.href = `${authorize_uri}?client_id=${client_id}&redirect_uri=${redirect_uri}`;
  17. </script>
  18. </body>
  19. </html>

welcome.html

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Hello</title>
  8. </head>
  9. <body>
  10. <h1>Welcome</h1>
  11. <div th:text="${userData}"></div>
  12. </body>
  13. </html>

启动项目,浏览器访问localhost:8080,会跳转到index页面,点击链接会跳转到GitHub应用授权页面

点击跳转到GitHub授权之后,GitHub会询问示例代码正在请求数据,您是否同意授权。

用户同意授权, GitHub 就会跳转到redirect_uri指定的跳转网址,并且带上授权码,跳转回来的 URL 就是下面的样子

  1. // code参数就是授权码
  2. http://localhost:8080/oauth/redirect?code:4ea423f2ec1e04c6376a

如下是服务的响应数据:

  1. access token: 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
  2. {
  3. login: 'AtwoodPa',
  4. id: 110728122,
  5. node_id: 'U_kgDOBpmTug',
  6. avatar_url: 'https://avatars.githubusercontent.com/u/110728122?v=4',
  7. gravatar_id: '',
  8. url: 'https://api.github.com/users/AtwoodPa',
  9. html_url: 'https://github.com/AtwoodPa',
  10. followers_url: 'https://api.github.com/users/AtwoodPa/followers',
  11. following_url: 'https://api.github.com/users/AtwoodPa/following{/other_user}',
  12. gists_url: 'https://api.github.com/users/AtwoodPa/gists{/gist_id}',
  13. starred_url: 'https://api.github.com/users/AtwoodPa/starred{/owner}{/repo}',
  14. subscriptions_url: 'https://api.github.com/users/AtwoodPa/subscriptions',
  15. organizations_url: 'https://api.github.com/users/AtwoodPa/orgs',
  16. repos_url: 'https://api.github.com/users/AtwoodPa/repos',
  17. events_url: 'https://api.github.com/users/AtwoodPa/events{/privacy}',
  18. received_events_url: 'https://api.github.com/users/AtwoodPa/received_events',
  19. type: 'User',
  20. site_admin: false,
  21. name: null,
  22. company: null,
  23. blog: '',
  24. location: null,
  25. email: null,
  26. hireable: null,
  27. bio: null,
  28. twitter_username: null,
  29. public_repos: 6,
  30. public_gists: 0,
  31. followers: 0,
  32. following: 3,
  33. created_at: '2022-08-06T13:02:16Z',
  34. updated_at: '2023-09-03T00:15:55Z'
  35. }
  36. authorization code: 4ea423f2ec1e04c6376a

成功执行上述流程,最终展示示例的welcome页面

到这里,Spring Boot整合GitHub实现第三方登录的实现就结束了,以此类推其他厂商的第三方登录实现流程也大概是这样。

原文链接:https://www.cnblogs.com/atwood-pan/p/17787904.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号