Github 第三方授权登陆

1.在Github上创建一个OAuth App

在Github上按照官方文档【Creating an OAuth App】进行操作
右上角–Settings–Developer settings–OAuth Apps–New OAuth App
主要是填写:
在这里插入图片描述
创建成功之后会得到授权用户数目和授权需要用到的参数【client id和client secret】:
在这里插入图片描述

2.授权登陆【Authorizing OAuth Apps官方文档

主要流程分析:

  1. 获取code
  2. 通过code获取access_token
  3. 通过access_token获取github上的用户信息

根据官方文档具体分析流程:
在这里插入图片描述
https://github.com/login/oauth/authorize发送get请求【带上client_id,redirect_uri等参数】,这时会跳转到GitHub授权登陆页面,授权之后,会返回一个url,这个url里带有下一步要用到code参数
在这里插入图片描述
授权后GitHub会重定向返回之前在平台上配置好的站点,携带有code和上一步中state参数。如下:

http://localhost:8887/callback?code=984de57e4a966fd6d7be&state=1

然后我们就要用code去获得access_token,用如下post方法:

https://github.com/login/oauth/access_token

上图中的5个参数1、2、4都在步骤一中,state是在上一步发送get请求的时候自己设置的,code是上一步的返回

在这里插入图片描述
上一步的请求会返回access_token,只需要向https://api.github.com/user?access_token=xxx发送GET请求,就能获得用户信息

上面几个步骤的url参考:

https://github.com/login/oauth/authorize?client_id=××××&redirect_uri=××××&scope=××××&state=1"
https://github.com/login/oauth/access_token?client_id=××××&client_secret=××××&code=××××&redirect_uri=××××&state=××××
https://api.github.com/user?access_token=××××

3.代码实现

跳转到授权登陆页面,授权登陆后会返回code

<a href="https://github.com/login/oauth/authorize?client_id=d7451ffbdd3f5482cfcb&redirect_uri=http://localhost:8887/callback&scope=user&state=1">登陆</a>

用code交换access_token

public String getAccessToken(AccessTokenDTO accessTokenDTO){
   
         MediaType mediaType = MediaType.get("application/json; charset=utf-8");
         OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON.toJSONString(
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值