JustAuth实现GitHub登录

11 篇文章 0 订阅

GitHub创建第三方应用

具体步骤查看博客:GitHub创建第三方应用

copy以下三个信息:Client ID、Client Secret和Authorization callback URL

application.yml配置

server:
  port: 80
  servlet:
    context-path: /
  tomcat:
    uri-encoding: utf-8

spring:
  session:
    store-type: none

引入依赖

<dependency>
	<groupId>me.zhyd.oauth</groupId>
	<artifactId>JustAuth</artifactId>
	<version>1.16.1</version>
</dependency>

创建Request

AuthRequest authRequest = new AuthGithubRequest(AuthConfig.builder()
                .clientId("Client ID")
                .clientSecret("Client Secret")
                .redirectUri("应用回调地址")
                .build());

生成授权地址

String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());

完整代码

IndexController
package com.ledao.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author LeDao
 * @company
 * @create 2021-07-28 0:05
 */
@RestController
public class IndexController {

    @RequestMapping("/")
    public String root() {
        return "<h2 style='text-align: center'><a href='/oauth/login/github'>github登录</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='/oauth/login/gitee'>gitee登录</a></span>";
    }

    @RequestMapping("/home")
    public String home() {
        return "<h1>主页</h1>";
    }
}
JustAuthController

Client ID、Client Secret和Authorization callback URL更换为自己的,下面代码中的是错误的

package com.ledao.controller;

import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthGithubRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LeDao
 * @company
 * @create 2021-07-28 0:12
 */
@RestController
@RequestMapping("/oauth")
public class JustAuthController {

    /**
     * 重定向
     *
     * @param type
     * @param response
     * @throws IOException
     */
    @RequestMapping("/login/{type}")
    public void login(@PathVariable String type, HttpServletResponse response) throws IOException {
        //创建request
        AuthRequest authRequest = getAuthRequest(type);
        //重定向到授权链接
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    /**
     * 登录后回调
     *
     * @param type
     * @param callback
     * @return
     */
    @RequestMapping("/callback/{type}")
    public AuthResponse callback(@PathVariable String type, AuthCallback callback) {
        //创建request
        AuthRequest authRequest = getAuthRequest(type);
        //登录(获取用户信息)
        AuthResponse authResponse = authRequest.login(callback);
        return authResponse;
    }

    /**
     * 授权平台创建响应的request
     *
     * @param type
     * @return
     */
    private AuthRequest getAuthRequest(String type) {
        AuthRequest authRequest = null;
        switch (type) {
            //github平台
            case "github":
                authRequest = new AuthGithubRequest(AuthConfig.builder()
                        .clientId("803de7712b9908181")
                        .clientSecret("e863222b3de13fe5ca91224e4651c0316e")
                        .redirectUri("http://localhost:80/oauth/callback/github")
                        .build());
                break;
            //gitee平台
            case "gitee":
                authRequest = new AuthGiteeRequest(AuthConfig.builder()
                        .clientId("e7c5c4c0cadb936b728b5d87af2ae1f2958c0a2cb24af4daa6f29a5f7")
                        .clientSecret("823a0fd650add2468a8e31ac684b7c614b1783331c73b32bb29040")
                        .redirectUri("http://localhost:80/oauth/callback/gitee")
                        .build());
                break;
            default:
                break;
        }
        return authRequest;
    }
}

结果

浏览器地址栏输入:http://localhost

img

GitHub登录返回的结果

img

Gitee登录返回的结果

img

PS.

代码中包含了Gitee登录

GitHub完整代码地址:https://github.com/a6678696/JustAuthDemo

更多第三方登录教程查看:https://justauth.wiki/

如果需要获取返回的用户信息,callback方法返回的数据类型修改为AuthResponse,完整代码如下:(可直接覆盖上面代码)

/**
 * 登录后回调
 *
 * @param type
 * @param callback
 * @return
 */
@RequestMapping("/callback/{type}")
public AuthResponse<AuthUser> callback(@PathVariable String type, AuthCallback callback) {
	//创建request
	AuthRequest authRequest = getAuthRequest(type);
	//登录(获取用户信息)
	AuthResponse<AuthUser> authResponse = authRequest.login(callback);

	//打印授权回传代码(2000 表示成功,可以用来判断用户登录是否成功)
	System.out.println("状态码:" + authResponse.getCode());

	//打印用户的昵称、ID、头像
	System.out.println("用户的uuid:" + authResponse.getData().getUuid());
	System.out.println("用户的昵称:" + authResponse.getData().getNickname());
	System.out.println("用户的头像:" + authResponse.getData().getAvatar());

	//打印用户的Token中的access_token
	System.out.println("access_token:" + authResponse.getData().getToken().getAccessToken());
	return authResponse;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值