前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >认证授权:JustAuth 简介及实践

认证授权:JustAuth 简介及实践

作者头像
Freedom123
发布2024-03-29 16:13:56
1710
发布2024-03-29 16:13:56
举报
文章被收录于专栏:DevOpsDevOps

JustAuth简介

JustAuth,如你所见,它仅仅是一个第三方授权登录工具类库,它可以让我们脱离繁琐的第三方登录 SDK,让登录变得So easy!

JustAuth 集成了诸如:Github、Gitee、支付宝、新浪微博、微信、Google、Facebook、Twitter、StackOverflow等国内外数十家第三方平台。更多请参考已集成的平台

一、特点

  1. :已集成十多家第三方平台(国内外常用的基本都已包含),仍然还在持续扩展中(开发计划)!
  2. :API就是奔着最简单去设计的(见后面快速开始),尽量让您用起来没有障碍感!

二、核心能力

  • 集成国内外数十家第三方平台,实现快速接入。参考文档
  • 自定义 State 缓存,支持各种分布式缓存组件。参考文档
  • 自定义 OAuth 平台,更容易适配自有的 OAuth 服务。参考文档
  • 自定义 Http 实现,选择权完全交给开发者,不会单独依赖某一具体实现。参考文档
  • 自定义 Scope,支持更完善的授权体系。参考文档
  • 更多…参考文档

三、justauth-spring-boot-starter

pring Boot 集成 JustAuth 的最佳实践~ JustAuth 脚手架

地址:https://github.com/justauth/justauth-spring-boot-starter

justauth-spring-boot-starter-demo: 此 demo 主要演示 Spring Boot 如何使用 justauth-spring-boot-starter 集成 JustAuth

地址:https://github.com/justauth/justauth-spring-boot-starter-demo

四、环境准备

本地环境测验使用 gitee 第三方应用进行测验的:

https://gitee.com/oauth/applications/

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Dw57GcYF-1687850166192)(C:\Users\86186\AppData\Roaming\Typora\typora-user-images\image-20230412143441487.png)]

1.创建本地应用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CERB49oW-1687850166196)(C:\Users\86186\AppData\Roaming\Typora\typora-user-images\image-20230412143541548.png)]

2.设置应用主页,回调地址

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-c9m9qkVR-1687850166201)(C:\Users\86186\AppData\Roaming\Typora\typora-user-images\image-20230412143638715.png)]

此处我使用的回到地址是: http://localhost:8443/oauth/gitee/callback,你需要根据自身情况进行填写。

需要把Client IDClient Secret回调地址记录下来,方便后面使用。

五、快速开始

此 demo 主要演示 Spring Boot 如何使用 justauth-spring-boot-starter 集成 JustAuth

1. 基础配置
  • 引用依赖
代码语言:javascript
复制
<dependency>
  <groupId>com.xkcoding</groupId>
  <artifactId>justauth-spring-boot-starter</artifactId>
  <version>1.3.2</version>
</dependency>
  • 添加配置,在 application.yml 中添加配置配置信息
代码语言:javascript
复制
justauth:
  enabled: true
  type:
    QQ:
      client-id: 10**********6
      client-secret: 1f7d08**********5b7**********29e
      redirect-uri: http://oauth.xkcoding.com/demo/oauth/qq/callback
  cache:
    type: default
  • 然后就开始玩耍吧~
代码语言:javascript
复制
@Slf4j
@RestController
@RequestMapping("/oauth")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TestController {
    private final AuthRequestFactory factory;

    @GetMapping
    public List<String> list() {
        return factory.oauthList();
    }

    @GetMapping("/login/{type}")
    public void login(@PathVariable String type, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = factory.get(type);
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/{type}/callback")
    public AuthResponse login(@PathVariable String type, AuthCallback callback) {
        AuthRequest authRequest = factory.get(type);
        AuthResponse response = authRequest.login(callback);
        log.info("【response】= {}", JSONUtil.toJsonStr(response));
        return response;
    }

}
2. 缓存配置

starter 内置了2种缓存实现,一种是上面的默认实现,另一种是基于 Redis 的缓存实现。当然了,你也可以自定义实现你自己的缓存。

再次或略,有兴趣的朋友可以自行研究。

3. 自定义第三方平台配置

1.创建自定义的平台枚举类

代码语言:javascript
复制
/**
 * <p>
 * 扩展的自定义 source
 * </p>
 *
 * @author yangkai.shen
 * @date Created in 2019/10/9 14:14
 */
public enum ExtendSource implements AuthSource {

    /**
     * 测试
     */
    TEST {
        /**
         * 授权的api
         *
         * @return url
         */
        @Override
        public String authorize() {
            return "http://authorize";
        }

        /**
         * 获取accessToken的api
         *
         * @return url
         */
        @Override
        public String accessToken() {
            return "http://accessToken";
        }

        /**
         * 获取用户信息的api
         *
         * @return url
         */
        @Override
        public String userInfo() {
            return null;
        }

        /**
         * 取消授权的api
         *
         * @return url
         */
        @Override
        public String revoke() {
            return null;
        }

        /**
         * 刷新授权的api
         *
         * @return url
         */
        @Override
        public String refresh() {
            return null;
        }
    }
}

2.创建自定义的请求处理

代码语言:javascript
复制
/**
 * <p>
 * 测试用自定义扩展的第三方request
 * </p>
 *
 * @author yangkai.shen
 * @date Created in 2019/10/9 14:19
 */
public class ExtendTestRequest extends AuthDefaultRequest {

    public ExtendTestRequest(AuthConfig config) {
        super(config, ExtendSource.TEST);
    }

    public ExtendTestRequest(AuthConfig config, AuthStateCache authStateCache) {
        super(config, ExtendSource.TEST, authStateCache);
    }

    /**
     * 获取access token
     *
     * @param authCallback 授权成功后的回调参数
     * @return token
     * @see AuthDefaultRequest#authorize()
     * @see AuthDefaultRequest#authorize(String)
     */
    @Override
    protected AuthToken getAccessToken(AuthCallback authCallback) {
        return AuthToken.builder().openId("openId").expireIn(1000).idToken("idToken").scope("scope").refreshToken("refreshToken").accessToken("accessToken").code("code").build();
    }

    /**
     * 使用token换取用户信息
     *
     * @param authToken token信息
     * @return 用户信息
     * @see AuthDefaultRequest#getAccessToken(AuthCallback)
     */
    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        return AuthUser.builder().username("test").nickname("test").gender(AuthUserGender.MALE).token(authToken).source(this.source.toString()).build();
    }

    /**
     * 撤销授权
     *
     * @param authToken 登录成功后返回的Token信息
     * @return AuthResponse
     */
    @Override
    public AuthResponse revoke(AuthToken authToken) {
        return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).msg(AuthResponseStatus.SUCCESS.getMsg()).build();
    }

    /**
     * 刷新access token (续期)
     *
     * @param authToken 登录成功后返回的Token信息
     * @return AuthResponse
     */
    @Override
    public AuthResponse refresh(AuthToken authToken) {
        return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(AuthToken.builder().openId("openId").expireIn(1000).idToken("idToken").scope("scope").refreshToken("refreshToken").accessToken("accessToken").code("code").build()).build();
    }
}

3.在配置文件配置相关信息

代码语言:javascript
复制
justauth:
  enabled: true
  extend:
    enum-class: com.xkcoding.justauthspringbootstarterdemo.extend.ExtendSource
    config:
      TEST:
        request-class: com.xkcoding.justauthspringbootstarterdemo.extend.ExtendTestRequest
        client-id: xxxxxx
        client-secret: xxxxxxxx
        redirect-uri: http://oauth.xkcoding.com/demo/oauth/test/callback

本地项目路径:C:\Users\86186\Desktop\justauth-spring-boot-starter-demo

其他

参考:https://github.com/justauth/JustAuth

https://gitcode.net/justauth/JustAuth

https://github.com/justauth/justauth-spring-boot-starter

https://github.com/justauth/justauth-spring-boot-starter-demo

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-03-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • JustAuth简介
  • 一、特点
  • 二、核心能力
  • 三、justauth-spring-boot-starter
  • 四、环境准备
    • 1.创建本地应用
      • 2.设置应用主页,回调地址
      • 五、快速开始
        • 1. 基础配置
          • 2. 缓存配置
            • 3. 自定义第三方平台配置
            • 其他
            相关产品与服务
            云数据库 Redis
            腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档