Github第三方登录实现获取用户信息(小白笔记)

Github第三方登录实现获取用户信息

接上一版:https://blog.csdn.net/qq_43516238/article/details/105884926

看这版前先看上一版

步骤一:

前端按钮点击方法

这边有所改变:回调地址去掉了login,因为实际项目中/login容易被拦截器拦截

login() {
      const authorize_uri = 'https://github.com/login/oauth/authorize'
      const client_id = '029605ac4b8d64a69874'
      const redirect_url = 'http://localhost:8080/oauth2/code/github'
      // alert('click')
      window.location.href = `${authorize_uri}?client_id=${client_id}&redirect_url=${redirect_url}`
    }
步骤二:

后端AuthController接口类

package com.soft1851.music.admin.controller;
import com.alibaba.fastjson.JSONObject;
import com.soft1851.music.admin.annotation.ControllerWebLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping(value = "/oauth2/code/github") 
@Slf4j
public class AuthController {

    @GetMapping()
    @ControllerWebLog
    public void getUser(@RequestParam("code") String code) {  //这边code必须要加
        String token = "";
        String user = "";
        try {
            //创建一个HttpClient对象
            HttpClient client = HttpClients.createDefault();
            //创建一个Post对象
            HttpPost post = new HttpPost("https://github.com/login/oauth/access_token");
            //创建一个entity模拟一个表单
            List<NameValuePair> list = new ArrayList<>();
            list.add(new BasicNameValuePair("client_id", "02**********74"));
            list.add(new BasicNameValuePair("client_secret", "7744***********5b0a4"));
            list.add(new BasicNameValuePair("code", code));
            //包装成一个entity对象
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
            //设置请求内容
            post.setEntity(urlEncodedFormEntity);
            post.addHeader("accept", "application/json");
            post.addHeader("user-agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Mobile Safari/537.36");
            //执行请求内容
            HttpResponse httpResponse = client.execute(post);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            log.info(String.valueOf(statusCode));
            HttpEntity contentEntity = httpResponse.getEntity();
            String content = EntityUtils.toString(contentEntity);
            log.info(content);
            token = JSONObject.parseObject(content).getString("access_token");
            log.info("token>>>>>>>>>>>>>>>>" + token);

            //取user
            RequestConfig requestConfig = RequestConfig.custom()
                    .setExpectContinueEnabled(true)
                    .setSocketTimeout(10000)
                    .setConnectTimeout(10000)
                    .setConnectionRequestTimeout(10000)
                    .build();
            HttpGet get = new HttpGet("https://api.github.com/user?access_token=" + token);
            get.setConfig(requestConfig);
            get.setHeader("Authorization", "token " + token);
            get.setHeader("user-agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Mobile Safari/537.36");

            httpResponse = client.execute(get);
            contentEntity = httpResponse.getEntity();
            user = EntityUtils.toString(contentEntity);
            log.info("user>>>>>>>>>>>>" + user);
            EntityUtils.consume(contentEntity);
            //重定向跳回客户端
            ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            assert sra != null;
            HttpServletResponse response = sra.getResponse();
            response.sendRedirect("http://localhost:8081/#/auth?user=" + user);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 这个接口其实也就是你的回调地址
  • code参数必须要加,要接住过来的参数
  • 最后的response.sendRedirect("http://localhost:8081/#/auth?user=" + user);这个地址是为了重定向到你前端的界面,因此你前端需要有/auth这个路由
  • 那么如何获取路由中的user参数呢?
步骤三

在你前端页面的created()中按如下方法获取

created() {
    console.log('回调')
    let user = this.$route.query.user
    if (user) {
      console.log(user)
      this.user = JSON.parse(user)
      localStorage.setItem('token', this.user.id)
      localStorage.setItem('user', JSON.stringify(user))
      this.$store.commit('setUser', JSON.stringify(user))
    }
    window.location.href = 'http://localhost:8081/#/dashboard'
  },
  • 可以将user存储到本地存储中,方便后面的数据获取,当然如果你只是想展示相关信息就不用了
  • 最后的window.location.href = 'http://localhost:8081/#/dashboard'是为了当你数据存储过后跳到首页,因此这个页面其实是不显示的,只是一个中间过渡的作用

最终效果如下(我只拿了用户名和头像)

谢谢!!!留言交流

OkHttp是一个流行的开源的HTTP客户端,它可以用于发送和接收HTTP请求。要实现GitHub第三方登录,我们可以使用OkHttp向GitHub的认证服务器发送请求,并获取授权码或访问令牌。 下面是一个用OkHttp实现GitHub第三方登录的简单的步骤: 1. 首先,我们需要在GitHub开发者平台注册一个应用程序,获得Client ID和Client Secret。这些凭证将用于向GitHub认证服务器证明我们的应用程序的身份。 2. 在应用程序中,创建一个OkHttpClient实例并实例化一个Request对象。Request对象应该包含登录请求的URL、请求方法(一般是GET或POST)、请求头(包括Accept和User-Agent等)以及需要的参数(如Client ID、Client Secret和一些其他参数)。 3. 调用OkHttpClient的newCall方法并传入Request对象来创建Call对象。 4. 调用Call对象的execute方法来发送请求并获取响应。得到的响应是一个Response对象。 5. 从Response对象中获取响应的内容,可能是JSON格式的数据。如果响应中包含授权码或访问令牌,我们可以将其用于后续的访问。 6. 进行登录验证和其他操作。根据响应内容和需要,可以使用OkHttp继续发送请求并处理响应。 需要注意的是,此处的步骤是简化的,并且可能因GitHub的认证流程而有所不同。在实际的应用程序中,还需要处理认证过程中的错误、重试机制、OAuth协议的授权流程等相关问题。 总结来说,使用OkHttp实现GitHub第三方登录需要创建OkHttpClient和Request对象,发送请求并获取响应,然后根据需要处理响应,获取授权码或访问令牌。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老子裤子马

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值