JA Plus 开发者文档 JA Plus 开发者文档
首页
📖 白皮书 (opens new window)
  • 名词解释
  • 快速开始

    • 使用jap-simple
    • 使用jap-social
    • 使用jap-oauth2
    • 使用jap-oidc
    • 使用jap-sso
    • 使用jap-mfa
    • 使用jap-http-api
    • 使用jap-ldap
    • 错误代码
  • IDS

    • 简介
    • 快速开始
    • 自定义scope
    • 自定义登录页面
    • 自定义确认授权页面
    • 自定义缓存
    • 自定义Token加密密钥
    • 使用PKCE模式
    • 自动授权
    • 错误代码
  • starter

    • jap-spring-boot-starter
    • jap-simple-spring-boot-starter
    • jap-social-spring-boot-starter
    • jap-oauth2-spring-boot-starter
    • jap-oidc-spring-boot-starter
  • jap-ids的demo
  • 前后端分离架构中使用JAP
  • SpringBoot中使用JAP
  • 问题反馈
  • 项目问题
  • 异常问题
  • 功能问题
  • 数据看板🔥
  • 贡献指南
  • 行为准则
  • 用户权益
  • 贡献者们
  • 社区配套 (opens new window)
  • 教程
  • 投稿
  • 资讯
  • 关于
  • 友情链接
  • 捐赠列表
  • 其他开源
  • 更新记录
收藏
GitHub (opens new window)

FuJie Team

以开源的形式赋能开发者. Just auth into any app.
首页
📖 白皮书 (opens new window)
  • 名词解释
  • 快速开始

    • 使用jap-simple
    • 使用jap-social
    • 使用jap-oauth2
    • 使用jap-oidc
    • 使用jap-sso
    • 使用jap-mfa
    • 使用jap-http-api
    • 使用jap-ldap
    • 错误代码
  • IDS

    • 简介
    • 快速开始
    • 自定义scope
    • 自定义登录页面
    • 自定义确认授权页面
    • 自定义缓存
    • 自定义Token加密密钥
    • 使用PKCE模式
    • 自动授权
    • 错误代码
  • starter

    • jap-spring-boot-starter
    • jap-simple-spring-boot-starter
    • jap-social-spring-boot-starter
    • jap-oauth2-spring-boot-starter
    • jap-oidc-spring-boot-starter
  • jap-ids的demo
  • 前后端分离架构中使用JAP
  • SpringBoot中使用JAP
  • 问题反馈
  • 项目问题
  • 异常问题
  • 功能问题
  • 数据看板🔥
  • 贡献指南
  • 行为准则
  • 用户权益
  • 贡献者们
  • 社区配套 (opens new window)
  • 教程
  • 投稿
  • 资讯
  • 关于
  • 友情链接
  • 捐赠列表
  • 其他开源
  • 更新记录
收藏
GitHub (opens new window)
  • 使用指南
  • 名词解释
  • 快速开始

    • 使用jap-simple
    • 使用jap-social
    • 使用jap-oauth2
      • 添加依赖
      • 实现 JapUserService 接口
      • 多种不同的授权方式
        • 授权码模式
        • 隐式授权模式
        • 密码授权模式
      • 测试登录
      • jap-oauth2 和 jap-social 有什么区别?
      • OAuthConfig 配置项
      • 官方推荐
    • 使用jap-oidc
    • 使用jap-sso
    • 使用jap-mfa
    • 使用jap-http-api
    • 使用jap-ldap
    • JAP 错误代码
  • IDS

  • starter

  • 指南
  • 快速开始
FuJie Team
2021-09-20

使用jap-oauth2

提示

jap-oauth2 是为了方便快速的集成所有支持标准 OAuth 2.0 协议的平台而添加的增强包。

# 添加依赖

<dependency>
    <groupId>com.fujieid</groupId>
    <artifactId>jap-oauth2</artifactId>
    <version>{latest-version}</version>
</dependency>

<!--
jap 已经使用 simple-json 解耦 json 类库,开发者只需要选择适合的依赖引入即可,支持依赖:
    - jackson
    - fastjson
    - gson
    - hutool-json
关于 simple-json 更多使用方式参考:https://github.com/xkcoding/simple-json
-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
</dependency>

<!--
jap 已经使用 simple-http 解耦 http 类库,开发者只需要选择适合的依赖引入即可,支持依赖:
    - java 11 HttpClient
    - OkHttp3
    - apache HttpClient
    - hutool-http
关于 simple-http 更多使用方式参考:https://github.com/xkcoding/simple-http
-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-http</artifactId>
    <version>5.2.5</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

# 实现 JapUserService 接口

JapUserService 是 JAP 调用(操作)开发者业务系统中用户的接口,jap-oauth2 需要实现 getByPlatformAndUid 和 createAndGetSocialUser 方法。

public class JapOauth2UserServiceImpl implements JapUserService {

    /**
     * 根据第三方平台标识(platform)和第三方平台的用户 uid 查询数据库
     *
     * @param platform 第三方平台标识
     * @param uid      第三方平台的用户 uid
     * @return JapUser
     */
    @Override
    public JapUser getByPlatformAndUid(String platform, String uid) {
        return null;
    }

    /**
     * 创建并获取第三方用户,相当于第三方登录成功后,将授权关系保存到数据库
     * (开发者业务系统中 oauth2 user -> sys user 的绑定关系)
     *
     * @param platform 第三方平台标识
     * @param userInfo 第三方返回的用户信息
     * @param tokenInfo token 信息,可以强制转换为 com.fujieid.jap.oauth2.token.AccessToken
     * @return JapUser
     */
    @Override
    public JapUser createAndGetOauth2User(String platform, Map<String, Object> userInfo, Object tokenInfo) {
        // FIXME 业务端可以对 tokenInfo 进行保存或其他操作
        AccessToken accessToken = (AccessToken) tokenInfo;
        System.out.println(JsonUtil.toJsonString(accessToken));
        // FIXME 注意:此处仅作演示用,不同的 oauth 平台用户id都不一样,
        // 此处需要开发者自己分析第三方平台的用户信息,提取出用户的唯一ID
        String uid = (String) userInfo.get("userId");
        // 查询绑定关系,确定当前用户是否已经登录过业务系统
        JapUser japUser = this.getByPlatformAndUid(platform, uid);
        if (null == japUser) {
            // 保存用户
            japUser = createJapUser();
            japUser.setAdditional(userInfo);
            userDatas.add(japUser);
        }
        return japUser;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

特别注意

上面示例代码仅作演示,具体业务逻辑需要开发者自己实现

# 多种不同的授权方式

# 授权码模式

# 创建 OAuth 应用

需要开发者自己去对应的平台创建 OAuth 应用,开发者还可以参考 Gitee 登录 - 申请应用 (opens new window) 这篇文章。

本例以 JAI (opens new window) 平台为例,创建一个 OAuth 应用,创建完成后的应用如下:

# 实现 controller


1

注意

部分平台的 getUserInfo和getAccessToken接口的请求方式为 GET 请求,针对这种情况,处理方法参考:第三方平台获取 token 和 userinfo 的请求方式为 GET

# 隐式授权模式

# 创建 OAuth 应用

# 实现 controller

import cn.hutool.core.util.URLUtil;
import com.fujieid.jap.core.JapUserService;
import com.fujieid.jap.core.config.JapConfig;
import com.fujieid.jap.core.result.JapResponse;
import com.fujieid.jap.http.jakarta.JakartaRequestAdapter;
import com.fujieid.jap.http.jakarta.JakartaResponseAdapter;
import com.fujieid.jap.oauth2.OAuthConfig;
import com.fujieid.jap.oauth2.Oauth2GrantType;
import com.fujieid.jap.oauth2.Oauth2ResponseType;
import com.fujieid.jap.oauth2.Oauth2Strategy;
import me.zhyd.oauth.utils.UuidUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/oauth2")
public class Oauth2Controller {

    @Resource(name = "oauth2")
    private JapUserService japUserService;

    @RequestMapping("/login/jai")
    public ModelAndView renderAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Oauth2Strategy oauth2Strategy = new Oauth2Strategy(japUserService, new JapConfig());
        OAuthConfig config = new OAuthConfig();
        config.setPlatform("jai")
                .setState(UuidUtils.getUUID())
                .setClientId("xx")
                .setClientSecret("xx")
                .setCallbackUrl("http://sso.jap.com:8443/oauth2/login/jai")
                .setAuthorizationUrl("xx")
                .setTokenUrl("xx")
                .setUserinfoUrl("xx")
                .setScopes(new String[]{"read", "write"})
                .setResponseType(Oauth2ResponseType.CODE)
                .setGrantType(Oauth2GrantType.AUTHORIZATION_CODE);
        JapResponse japResponse = oauth2Strategy.authenticate(config, new JakartaRequestAdapter(request), new JakartaResponseAdapter(response));
        if (!japResponse.isSuccess()) {
            return new ModelAndView(new RedirectView("/?error=" + URLUtil.encode(japResponse.getMessage())));
        }
        if (japResponse.isRedirectUrl()) {
            return new ModelAndView(new RedirectView((String) japResponse.getData()));
        } else {
            // 登录成功,需要对用户数据进行处理
            // ...
            System.out.println(japResponse.getData());
            return new ModelAndView(new RedirectView("/"));
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

# 密码授权模式

# 创建 OAuth 应用

# 实现 controller

import cn.hutool.core.util.URLUtil;
import com.fujieid.jap.core.JapUserService;
import com.fujieid.jap.core.result.JapResponse;
import com.fujieid.jap.demo.config.JapConfigContext;
import com.fujieid.jap.oauth2.OAuthConfig;
import com.fujieid.jap.oauth2.Oauth2GrantType;
import com.fujieid.jap.oauth2.Oauth2ResponseType;
import com.fujieid.jap.oauth2.Oauth2Strategy;
import me.zhyd.oauth.utils.UuidUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 需要依赖 jap-oauth2 模块
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0.0
 * @date 2021/1/12 14:07
 * @since 1.0.0
 */
@RestController
@RequestMapping("/oauth2")
public class Oauth2Controller {

    @Resource(name = "oauth2")
    private JapUserService japUserService;

    @RequestMapping("/login/password/jai")
    public ModelAndView renderAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Oauth2Strategy oauth2Strategy = new Oauth2Strategy(japUserService, new JapConfig());
        OAuthConfig config = new OAuthConfig();
        config.setPlatform("jai")
                .setState(UuidUtils.getUUID())
                .setClientId("xxx")
                .setClientSecret("xxx")
                .setCallbackUrl("http://sso.jap.com:8443/oauth2/login/password/jai")
                // 密码模式,不需要授权端链接
//                .setAuthorizationUrl("https://xxx.com/oauth/authorize")
                .setTokenUrl("https://xxx.com/oauth/token")
                .setUserinfoUrl("https://xxx.com/api/userinfo")
                .setScopes(new String[]{"read", "write"})
                // GrantType 设为 password
                .setGrantType(Oauth2GrantType.password)
                // 指定账号密码
                .setUsername("xxx")
                .setPassword("xxx");
        JapResponse japResponse = oauth2Strategy.authenticate(config, new JakartaRequestAdapter(request), new JakartaResponseAdapter(response));
        if (!japResponse.isSuccess()) {
            return new ModelAndView(new RedirectView("/?error=" + URLUtil.encode(japResponse.getMessage())));
        }
        if (japResponse.isRedirectUrl()) {
            return new ModelAndView(new RedirectView((String) japResponse.getData()));
        } else {
            System.out.println(japResponse.getData());
            return new ModelAndView(new RedirectView("/"));
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

# 测试登录

启动测试项目后访问分别访问:

  • 授权码模式:http://127.0.0.1:8443/social/login/jai
  • 隐式授权模式:http://127.0.0.1:8443/social/implicit/jai
  • 密码模式:http://127.0.0.1:8443/social/password/jai

登录账号

登录成功

提示

注意此处登录的时候没有显示授权页面,是因为我们在创建应用的时候勾选了自动批准。对于其他平台可能没有此项配置,实际要以第三方平台支持的配置为主。

注意

response data 的格式为:

{
  "additional" : {},
  "userId" : "1",
  "username" : "jap"
}
1
2
3
4
5

其中 additional 节点第三方平台的用户信息。

# jap-oauth2 和 jap-social 有什么区别?

  • 其实本质上没有区别,jap-social 是基于 JustAuth (opens new window) 实现的,所以也就支持了 JustAuth (opens new window) 中自定义第三方 OAuth 平台的功能。
  • jap-oauth2 能适配的平台,jap-social 一样可以适配,只不过,传递的参数不同而已。敲黑板
  • 但是,jap-social 能适配的平台,jap-oauth2 不一定可以适配,原因如下。敲黑板
  • 这两个模块唯一的最大区别在于,jap-oauth2 仅支持标准的 OAuth 2.0 协议,类似于 支付宝、Stack Overflow Key、Coding 这种做了定制化的平台,jap-oauth2无法做到适配。(ps.好在JustAuth (opens new window)已经完成了这部分工作。)
  • 更多内容请查看 常见问题 - 项目问题

# OAuthConfig 配置项

参数名 参数类型 必填 解释
platform String √ OAuth 平台名称
clientId String √ clientId
clientSecret String √ clientSecret
callbackUrl String √ 服务提供商获得授权后将用户重定向到的URL
authorizationUrl String √ 用于获取授权许可的 URL
tokenUrl String √ 用于获取访问令牌的 URL
refreshTokenUrl String x 用于刷新 access_token 的 URL
revokeTokenUrl String x 用于撤销 access_token 的 URL
userinfoUrl String √ 用于获取用户信息的 URL
responseType Oauth2ResponseType √ 授权码模式必须为 code,隐式授权时必须为 token
grantType Oauth2GrantType x 授权类型。可选值:AUTHORIZATION_CODE,PASSWORD,CLIENT_CREDENTIALS,REFRESH_TOKEN
scopes String[] x OAuth平台支持的授权范围
state String x 客户端用于维护请求和回调之间的状态的不透明值。授权服务器在将用户代理重定向回客户端时包含此值
verifyState String x 当 verifyState 为 true 时,会检查授权请求中的 state 是否与回调请求中的 state 一致
enablePkce Boolean x 是否启用 PKCE 模式。
codeChallengeMethod PkceCodeChallengeMethod x 启用 pkce 增强协议后,授权请求中发送的 code_verifier 派生的challenge code的生成方式默认为S256
codeVerifierTimeout long x pkce 模式下 code_verifier 的过期时间,单位毫秒,默认3分钟
username String x 密码模式中的用户名
password String x 密码模式中的密码
userInfoEndpointMethodType Oauth2EndpointMethodType x 第三方获取 userInfo 的请求方法,默认为 POST
accessTokenEndpointMethodType Oauth2EndpointMethodType x 第三方获取 accessToken 的请求方法,默认为 POST
refreshTokenEndpointMethodType Oauth2EndpointMethodType x 第三方刷新 accessToken 的请求方法,默认为 POST
revokeTokenEndpointMethodType Oauth2EndpointMethodType x 第三方撤销 accessToken 的请求方法,默认为 POST

# 官方推荐

  • 普通示例项目:jap-demo (opens new window)
  • 前后端分离项目示例:jap-demo-vue (opens new window)
编辑 (opens new window)
#jap-oauth2#oauth2
Last Updated: 2021/10/09, 22:47:39
使用jap-social
使用jap-oidc

← 使用jap-social 使用jap-oidc→

最近更新
01
经验总结:关于为 JAP 开发不同语言的 Demo 的总结
11-02
02
jap-spring-boot-starter 使用帮助
10-28
03
使用jap-ldap
10-25
更多文章>
Theme by Vdoing | Copyright © 2021-2022

友情链接:UniAdmin | 江如意的博客

Copyright © 2021-2040 FUJIE. All rights reserved. 北京符节科技有限公司版权所有 | 京ICP备2020044519号-4
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式