how-to-use.md 7.7 KB
Newer Older
智布道's avatar
智布道 已提交
1
在前面有介绍到,JustAuth的特点之一就是**简**,极简主义,不给使用者造成不必要的障碍。
智布道's avatar
智布道 已提交
2

智布道's avatar
智布道 已提交
3 4
既然牛皮吹下了, 那么如何才能用JustAuth实现第三方登录呢?

智布道's avatar
智布道 已提交
5 6
## 使用步骤

智布道's avatar
智布道 已提交
7
使用JustAuth总共分三步(**这三步也适合于JustAuth支持的任何一个平台**):
智布道's avatar
智布道 已提交
8 9

1. 申请注册第三方平台的开发者账号
智布道's avatar
智布道 已提交
10
2. 创建第三方平台的应用,获取配置信息(`accessKey`, `secretKey`, `redirectUri`)
智布道's avatar
智布道 已提交
11 12
3. 使用该工具实现授权登陆

智布道's avatar
智布道 已提交
13
## 使用方式
智布道's avatar
智布道 已提交
14 15 16 17 18 19

- 引入依赖
```xml
<dependency>
    <groupId>me.zhyd.oauth</groupId>
    <artifactId>JustAuth</artifactId>
智布道's avatar
智布道 已提交
20
    <version>${latest.version}</version>
智布道's avatar
智布道 已提交
21 22
</dependency>
```
智布道's avatar
智布道 已提交
23

智布道's avatar
智布道 已提交
24
获取最新版本:[JustAuth](https://search.maven.org/search?q=g:me.zhyd.oauth%20AND%20a:JustAuth)
智布道's avatar
智布道 已提交
25

智布道's avatar
智布道 已提交
26 27 28 29 30 31 32 33 34
- 调用api
```java
// 创建授权request
AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
        .clientId("clientId")
        .clientSecret("clientSecret")
        .redirectUri("redirectUri")
        .build());
// 生成授权页面
智布道's avatar
智布道 已提交
35
authRequest.authorize("state");
智布道's avatar
智布道 已提交
36 37 38
// 授权登录后会返回code(auth_code(仅限支付宝))、state,1.8.0版本后,可以用AuthCallback类作为回调接口的参数
// 注:JustAuth默认保存state的时效为3分钟,3分钟内未使用则会自动清除过期的state
authRequest.login(callback);
智布道's avatar
智布道 已提交
39 40
```

智布道's avatar
智布道 已提交
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 66 67 68 69 70 71 72 73 74

注意,JustAuth从[v1.14.0](https://gitee.com/yadong.zhang/JustAuth/releases/v1.14.0)开始默认集成了的[simple-http](https://github.com/xkcoding/simple-http)作为HTTP通用接口(更新说明见[JustAuth 1.14.0版本正式发布!完美解耦HTTP工具](https://mp.weixin.qq.com/s?__biz=MzA3NDk3OTIwMg==&mid=2450633197&idx=1&sn=11e625b307db62b2f1c4e82f7744b2a2&chksm=88929300bfe51a16562b45592a264482ae2c74c6dbfa4a3aa9611ad4fea4a9be5b1f0545527d&token=1093833287&lang=zh_CN#rd)),鉴于一般项目中都已经集成了HTTP工具,比如OkHttp3、apache HttpClient、hutool-http,因此为了减少不必要的依赖,从[v1.14.0](https://gitee.com/yadong.zhang/JustAuth/releases/v1.14.0)开始JustAuth将不会默认集成hutool-http,如果开发者的项目是全新的或者项目内没有集成HTTP实现工具,请自行添加对应的HTTP实现类,备选依赖如下:

- hutool-http

  ```xml
  <dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-http</artifactId>
      <version>5.2.5</version>
  </dependency>
  ```

- httpclient

  ```xml
  <dependency>
  	<groupId>org.apache.httpcomponents</groupId>
    	<artifactId>httpclient</artifactId>
    	<version>4.5.12</version>
  </dependency>
  ```

- okhttp

  ```xml
  <dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.4.1</version>
  </dependency>
  ```


智布道's avatar
智布道 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87
## API分解

**JustAuth**的核心就是一个个的`request`,每个平台都对应一个具体的`request`类,所以在使用之前,需要就具体的授权平台创建响应的`request`

```java
// 创建授权request
AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
        .clientId("clientId")
        .clientSecret("clientSecret")
        .redirectUri("redirectUri")
        .build());
```

88
所有可用的`Request`列表请参考:[已集成的平台](https://justauth.wiki/#/README?id=已集成的平台)
智布道's avatar
智布道 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

### 获取授权链接

```java
String authorizeUrl = authRequest.authorize("state");
```
获取到`authorizeUrl`后,可以手动实现redirect到`authorizeUrl`

**伪代码**

```java
/**
 * 
 * @param source 第三方授权平台,以本例为参考,该值为gitee(因为上面声明的AuthGiteeRequest)
 */
@RequestMapping("/render/{source}")
public void renderAuth(@PathVariable("source") String source, HttpServletResponse response) throws IOException {
    AuthRequest authRequest = getAuthRequest(source);
    String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
    response.sendRedirect(authorizeUrl);
}
```

注:`state`建议必传!`state``OAuth`的流程中的主要作用就是保证请求完整性,防止**CSRF**风险,此处传的`state`将在回调时传回

### 登录(获取用户信息)

```java
AuthResponse response = authRequest.login(callback);
```

授权登录后会返回code(auth_code(仅限支付宝)、authorization_code(仅限华为))、state,1.8.0版本后,用`AuthCallback`类作为回调接口的入参

**伪代码**

```java
/**
 * 
 * @param source 第三方授权平台,以本例为参考,该值为gitee(因为上面声明的AuthGiteeRequest)
 */
@RequestMapping("/callback/{source}")
public Object login(@PathVariable("source") String source, AuthCallback callback) {
    AuthRequest authRequest = getAuthRequest(source);
    AuthResponse response = authRequest.login(callback);
    return response;
}
```

**注:第三方平台中配置的授权回调地址,以本文为例,在创建授权应用时的回调地址应为:`[host]/callback/gitee`**

### 刷新token

注:`refresh`功能,并不是每个平台都支持

```java
AuthResponse response = authRequest.refresh(AuthToken.builder().refreshToken(token).build());
```

**伪代码**

```java
/**
 * 
 * @param source 第三方授权平台,以本例为参考,该值为gitee(因为上面声明的AuthGiteeRequest)
 * @param token  login成功后返回的refreshToken
 */
@RequestMapping("/refresh/{source}")
public Object refreshAuth(@PathVariable("source") String source, String token){
    AuthRequest authRequest = getAuthRequest(source);
    return authRequest.refresh(AuthToken.builder().refreshToken(token).build());
}
```

### 取消授权

注:`revoke`功能,并不是每个平台都支持

```java
AuthResponse response = authRequest.revoke(AuthToken.builder().accessToken(token).build());
```

**伪代码**

```java
/**
 * 
 * @param source 第三方授权平台,以本例为参考,该值为gitee(因为上面声明的AuthGiteeRequest)
 * @param token  login成功后返回的accessToken
 */
@RequestMapping("/revoke/{source}/{token}")
public Object revokeAuth(@PathVariable("source") String source, @PathVariable("token") String token) throws IOException {
    AuthRequest authRequest = getAuthRequest(source);
    return authRequest.revoke(AuthToken.builder().accessToken(token).build());
}
183 184 185 186 187 188 189 190
```

## 参考文章

- [实现Gitee授权登录](http://t.cn/ExDKxQs)
- [实现Github授权登录](http://t.cn/EJ0Fxqo)
- [Spring Boot 快速集成第三方登录功能](http://t.cn/AiWWx5kH) : QQ、Github、微信、谷歌、微软、小米、企业微信
- [集成企业微信](https://mp.weixin.qq.com/s?__biz=MzA3NDk3OTIwMg==&mid=2450633170&idx=2&sn=456b70742a86948a193c691f3e47b72e&chksm=8892933fbfe51a29c1da386a2252d4bf91bfbd14e1ac0b99b783763a0d12e2e4b2d7c4369933&token=482455242&lang=zh_CN#rd)
191 192 193 194 195 196 197 198 199

## 配套项目

- [JustAuth-demo](https://github.com/justauth/JustAuth-demo):普通版springboot项目demo
- [jFinal版](https://github.com/xkcoding/jfinal-justauth-demo): Jfinal集成JustAuth的demo by [xkcoding](https://github.com/xkcoding)
- [ActFramework版](https://github.com/xkcoding/act-justauth-demo): ActFramework 集成 JustAuth 的 demo by [xkcoding](https://github.com/xkcoding)
- [Nutzboot版](https://github.com/EggsBlue/nutzboot-justauth-demo): NutzBoot集成JustAuth的demo  by [蛋蛋](https://github.com/EggsBlue)
- [Blade版](https://github.com/justauth/blade-justauth-demo): Blade集成JustAuth的demo

智布道's avatar
智布道 已提交
200
## SpringBoot插件
201
- [justauth-spring-boot-starter](https://github.com/xkcoding/justauth-spring-boot-starter): Spring Boot 集成 JustAuth 的最佳实践 by [xkcoding](https://github.com/xkcoding)
智布道's avatar
智布道 已提交
202
- [justauth-spring-security-starter](https://github.com/justauth/justauth-spring-security-starter): JustAuth整合Spring security的 starter依赖 by [luoqiz](https://github.com/luoqiz)