1
0
mirror of synced 2025-12-12 00:48:04 +08:00

47 Commits
1.0.0 ... 1.3.0

Author SHA1 Message Date
Yangkai.Shen
2de415c7ba 📝 更新 README.md 2019-11-04 16:26:13 +08:00
Yangkai.Shen
c670d9d10a 🔖 发布 1.3.0 2019-11-04 16:20:31 +08:00
Yangkai.Shen
dea73c1c6e 📝 添加 CHANGELOG 2019-11-04 16:20:14 +08:00
Yangkai.Shen
64a389aac4 支持 推特 2019-11-04 16:19:47 +08:00
Yangkai.Shen
e07cb8970b ⬆️ 升级 JustAuth 版本:1.13.0,支持 推特 2019-11-04 16:19:10 +08:00
Yangkai.Shen
1a690f5dd1 📝 添加 CHANGELOG 2019-11-04 16:12:35 +08:00
Yangkai.Shen
2029083f26 📝 添加 CHANGELOG 2019-11-04 16:11:54 +08:00
Yangkai.Shen
c00a127011 📝 更新 README.md 2019-11-04 16:08:34 +08:00
Yangkai.Shen
6b99039b98 🔧 修改 group id 2019-10-31 17:14:14 +08:00
Yangkai.Shen
0b00363336 📝 更新 README.md 2019-10-12 17:37:23 +08:00
Yangkai.Shen
70e9fc0af9 🔖 发布 1.2.1 2019-10-12 17:30:04 +08:00
Yangkai.Shen
2e723b2c51 📝 添加 CHANGELOG 2019-10-12 17:29:57 +08:00
Yangkai.Shen
011ad64fea 🚑 紧急修复Oauth列表空指针BUG 2019-10-12 17:28:37 +08:00
Yangkai.Shen
585edda9fa 🔖 发布 1.2.0 2019-10-09 16:17:38 +08:00
Yangkai.Shen
ddf066002b 📝 更新 README.md 2019-10-09 16:17:23 +08:00
Yangkai.Shen
479ce1abb0 📝 添加 CHANGELOG 2019-10-09 16:12:46 +08:00
Yangkai.Shen
a2ce42c0f3 🚚 移动文件 2019-10-09 15:46:26 +08:00
Yangkai.Shen
8eceb0f1cd 自定义扩展第三方平台 2019-10-09 15:29:18 +08:00
Yangkai.Shen
71e3a09565 ⬆️ 升级 Spring Boot 版本:2.1.8.RELEASE 2019-10-09 10:29:11 +08:00
Yangkai.Shen
4dbb9b2bb5 ⬆️ 升级 JustAuth 版本:1.12.0,支持 美团饿了么自定义扩展第三方平台 2019-10-09 10:28:04 +08:00
Yangkai.Shen
794c316859 🔧 更新私服地址 2019-09-18 10:38:12 +08:00
Yangkai.Shen
abd87213c1 📝 更新 README.md 2019-09-04 19:40:06 +08:00
Yangkai.Shen
e3d7054171 📝 更新 README.md 2019-09-04 19:34:47 +08:00
Yangkai.Shen
4a9187af34 📝 添加 CHANGELOG 2019-09-04 19:34:38 +08:00
Yangkai.Shen
30de3ea9bc 📝 更新 README.md 2019-09-04 18:58:21 +08:00
Yangkai.Shen
a6cefde0e5 📝 添加 CHANGELOG 2019-09-04 18:58:10 +08:00
Yangkai.Shen
4de27beb76 🔖 发布 1.1.0 2019-09-04 18:57:59 +08:00
Yangkai.Shen
741a322798 ⬆️ 升级 JustAuth 版本:1.11.0,支持 GitLab酷家乐 2019-09-04 18:57:04 +08:00
Yangkai.Shen
f702e70705 📝 更新 README.md 2019-09-02 17:56:31 +08:00
Yangkai.Shen
a42c80f22d 📝 更新 README.md 2019-08-31 13:24:52 +08:00
Yangkai.Shen
5c406fe4e1 Merge branch 'master' into dev 2019-08-31 13:19:00 +08:00
Yangkai.Shen
cf6ef0de49 📝 更新 README.md 2019-08-31 13:15:24 +08:00
Yangkai.Shen
59da8a1c61 📝 添加 CHANGELOG 2019-08-31 13:15:24 +08:00
Yangkai.Shen
9dbe77b703 📝 补充注释 2019-08-31 13:15:24 +08:00
Yangkai.Shen
1a890c4497 🎨 优化自动装配 2019-08-31 13:15:24 +08:00
Yangkai.Shen
263930ed34 自定义prefix和超时时间 2019-08-31 13:15:24 +08:00
Yangkai.Shen
e03aa81f33 集成 redis 缓存配置,用户可以通过配置使用缓存,不需要自行实现 2019-08-31 13:15:24 +08:00
Yangkai.Shen
5a82dd0792 📝 更新 README.md 2019-08-31 13:12:19 +08:00
Yangkai.Shen
fa88e58055 📝 添加 CHANGELOG 2019-08-31 13:12:06 +08:00
Yangkai.Shen
c0ca2979a7 📝 补充注释 2019-08-31 12:38:42 +08:00
Yangkai.Shen
12369820e5 🎨 优化自动装配 2019-08-31 12:34:34 +08:00
Yangkai.Shen
3f5989c917 自定义prefix和超时时间 2019-08-31 11:35:38 +08:00
Yangkai.Shen
30e7f01a78 集成 redis 缓存配置,用户可以通过配置使用缓存,不需要自行实现 2019-08-31 11:04:25 +08:00
Yangkai.Shen
219f390284 📦 添加 github 打包地址 2019-08-21 09:59:58 +08:00
Yangkai.Shen
2f6946c6b1 ⬆️ 升级 JustAuth 版本:1.10.1,AuthUser添加构造函数,支持反序列化 2019-08-19 09:21:25 +08:00
Yangkai.Shen
1a4d50bbb7 📝 添加 CHANGELOG 2019-08-09 16:22:51 +08:00
Yangkai.Shen
395e390f50 📝 更新 README.md 2019-08-09 16:20:37 +08:00
12 changed files with 923 additions and 163 deletions

View File

@@ -1,7 +1,38 @@
## 版本更新记录
### 【1.3.0】2019-11-04
- 修改 `groupId``com.xkcoding.justauth`
- 升级 `JustAuth` 版本1.13.0,支持 `推特`
### 【1.2.1】2019-10-12
- 紧急修复Oauth列表空指针BUG
### 【1.2.0】2019-10-09
- 升级 `JustAuth` 版本1.12.0,支持 `饿了么``美团`
- 新增配置项,支持`自定义第三方平台扩展`
- 规范包结构
### 【1.1.0】2019-09-04
- 升级 `JustAuth` 版本1.11.0,支持 `GitLab``酷家乐`
- 添加内置的 Redis 缓存策略,通过配置项可配,不需要额外实现
- 支持 Redis 缓存自定义缓存前缀、自定义缓存过期时间
### *【1.0.2-SNAPSHOT】2019-08-31*
- 添加内置的 Redis 缓存策略,通过配置项可配,不需要额外实现
- 支持 Redis 缓存自定义缓存前缀、自定义缓存过期时间
### 【1.0.1】2019-08-19
- 升级 `JustAuth` 版本1.10.1AuthUser添加构造函数支持反序列化
### 【1.0.0】2019-08-08
- 升级 `JustAuth` 版本到 1.10.0,支持 `华为登录``企业微信登录``自定义State缓存`
- 升级 `JustAuth` 版本1.10.0,支持 `华为登录``企业微信登录``自定义State缓存`
### 【0.0.2】2019-08-01

510
README.md
View File

@@ -4,25 +4,31 @@
>
> JustAuth 脚手架
![Maven Central](https://img.shields.io/maven-central/v/com.xkcoding/justauth-spring-boot-starter.svg?color=brightgreen&label=Maven%20Central)
![Travis (.com)](https://img.shields.io/travis/com/xkcoding/justauth-spring-boot-starter.svg?label=Build%20Status)
![GitHub](https://img.shields.io/github/license/xkcoding/justauth-spring-boot-starter.svg)
![Maven Central](https://img.shields.io/maven-central/v/com.xkcoding.justauth/justauth-spring-boot-starter.svg?color=brightgreen&label=Maven%20Central)![Travis (.com)](https://img.shields.io/travis/com/xkcoding/justauth-spring-boot-starter.svg?label=Build%20Status)![GitHub](https://img.shields.io/github/license/xkcoding/justauth-spring-boot-starter.svg)
## Demo
## 1. Demo
懒得看文档的可以直接看demo
https://github.com/xkcoding/justauth-spring-boot-starter-demo
## 快速开始
完整版 demohttps://github.com/xkcoding/spring-boot-demo/tree/master/spring-boot-demo-social
## 2. 更新日志
[CHANGELOG](./CHANGELOG.md)
## 3. 快速开始
### 3.1. 基础配置
- 引用依赖
```xml
<dependency>
<groupId>com.xkcoding</groupId>
<groupId>com.xkcoding.justauth</groupId>
<artifactId>justauth-spring-boot-starter</artifactId>
<version>1.0.0</version>
<version>1.3.0</version>
</dependency>
```
@@ -36,6 +42,8 @@ justauth:
client-id: 10**********6
client-secret: 1f7d08**********5b7**********29e
redirect-uri: http://oauth.xkcoding.com/demo/oauth/qq/callback
cache:
type: default
```
- 然后就开始玩耍吧~
@@ -55,161 +63,397 @@ public class TestController {
@GetMapping("/login/{type}")
public void login(@PathVariable String type, HttpServletResponse response) throws IOException {
AuthRequest authRequest = factory.get(getAuthSource(type));
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(getAuthSource(type));
AuthRequest authRequest = factory.get(type);
AuthResponse response = authRequest.login(callback);
log.info("【response】= {}", JSONUtil.toJsonStr(response));
return response;
}
private AuthSource getAuthSource(String type) {
if (StrUtil.isNotBlank(type)) {
return AuthSource.valueOf(type.toUpperCase());
} else {
throw new RuntimeException("不支持的类型");
}
```
### 3.2. 缓存配置
> starter 内置了2种缓存实现一种是上面的默认实现另一种是基于 Redis 的缓存实现。
>
> 当然了,你也可以自定义实现你自己的缓存。
#### 3.2.1. 默认缓存实现
在配置文件配置如下内容即可
```yaml
justauth:
cache:
type: default
```
#### 3.2.2. Redis 缓存实现
1.添加 Redis 相关依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 对象池使用redis时必须引入 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
```
2.配置文件配置如下内容即可
```yaml
justauth:
cache:
type: redis
# 缓存前缀目前只对redis缓存生效默认 JUSTAUTH::STATE::
prefix: ''
# 超时时长目前只对redis缓存生效默认3分钟
timeout: 1h
spring:
redis:
host: localhost
# 连接超时时间记得添加单位Duration
timeout: 10000ms
# Redis默认情况下有16个分片这里配置具体使用的分片
# database: 0
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制) 默认 8
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-wait: -1ms
# 连接池中的最大空闲连接 默认 8
max-idle: 8
# 连接池中的最小空闲连接 默认 0
min-idle: 0
```
#### 3.2.3. 自定义缓存实现
1.配置文件配置如下内容
```yaml
justauth:
cache:
type: custom
```
2.自定义缓存实现 `AuthStateCache` 接口
```java
/**
* <p>
* 自定义缓存实现
* </p>
*
* @author yangkai.shen
* @date Created in 2019/8/31 12:53
*/
public class MyAuthStateCache implements AuthStateCache {
/**
* 存入缓存
*
* @param key 缓存key
* @param value 缓存内容
*/
@Override
public void cache(String key, String value) {
// TODO: 自定义存入缓存
}
/**
* 存入缓存
*
* @param key 缓存key
* @param value 缓存内容
* @param timeout 指定缓存过期时间(毫秒)
*/
@Override
public void cache(String key, String value, long timeout) {
// TODO: 自定义存入缓存
}
/**
* 获取缓存内容
*
* @param key 缓存key
* @return 缓存内容
*/
@Override
public String get(String key) {
// TODO: 自定义获取缓存内容
return null;
}
/**
* 是否存在key如果对应key的value值已过期也返回false
*
* @param key 缓存key
* @return true存在key并且value没过期falsekey不存在或者已过期
*/
@Override
public boolean containsKey(String key) {
// TODO: 自定义判断key是否存在
return false;
}
}
```
3.自动装配 `JustAuthConfig`
```java
/**
* <p>
* 自定义缓存装配
* </p>
*
* @author yangkai.shen
* @date Created in 2019/8/31 12:29
*/
@Configuration
public class AuthStateConfiguration {
@Bean
public AuthStateCache authStateCache() {
return new MyAuthStateCache();
}
}
```
### 3.3. 自定义第三方平台配置
1.创建自定义的平台枚举类
```java
/**
* <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;
}
}
}
```
- 如果需要自定义 State 的缓存(此处举例 Redis其余缓存同理)
2.创建自定义的请求处理
> 1. 自定义缓存实现 `AuthStateCache` 接口
> 2. 将自定义缓存加入 Spring 容器
```java
/**
* <p>
* 测试用自定义扩展的第三方request
* </p>
*
* @author yangkai.shen
* @date Created in 2019/10/9 14:19
*/
public class ExtendTestRequest extends AuthDefaultRequest {
1.添加Redis依赖
public ExtendTestRequest(AuthConfig config) {
super(config, ExtendSource.TEST);
}
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 对象池使用redis时必须引入 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
```
public ExtendTestRequest(AuthConfig config, AuthStateCache authStateCache) {
super(config, ExtendSource.TEST, authStateCache);
}
2.自定义缓存 `RedisStateCache`
/**
* 获取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();
}
```java
/**
* <p>
* Redis作为JustAuth的State的缓存
* </p>
*
* @author yangkai.shen
* @date Created in 2019-08-02 15:10
*/
@RequiredArgsConstructor
public class RedisStateCache implements AuthStateCache {
private final RedisTemplate<String, String> redisTemplate;
private static final long DEF_TIMEOUT = 3 * 60 * 1000;
/**
* 存入缓存
*
* @param key 缓存key
* @param value 缓存内容
*/
@Override
public void cache(String key, String value) {
this.cache(key, value, DEF_TIMEOUT);
}
/**
* 存入缓存
*
* @param key 缓存key
* @param value 缓存内容
* @param timeout 指定缓存过期时间(毫秒)
*/
@Override
public void cache(String key, String value, long timeout) {
redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.MILLISECONDS);
}
/**
* 获取缓存内容
*
* @param key 缓存key
* @return 缓存内容
*/
@Override
public String get(String key) {
return redisTemplate.opsForValue().get(key);
}
/**
* 是否存在key如果对应key的value值已过期也返回false
*
* @param key 缓存key
* @return true存在key并且value没过期falsekey不存在或者已过期
*/
@Override
public boolean containsKey(String key) {
Long expire = redisTemplate.getExpire(key, TimeUnit.MILLISECONDS);
if (expire == null) {
expire = 0L;
}
return expire > 0;
}
}
```
/**
* 使用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();
}
3.自动装配 `JustAuthConfig`
/**
* 撤销授权
*
* @param authToken 登录成功后返回的Token信息
* @return AuthResponse
*/
@Override
public AuthResponse revoke(AuthToken authToken) {
return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).msg(AuthResponseStatus.SUCCESS.getMsg()).build();
}
```java
/**
* <p>
* JustAuth配置类
* </p>
*
* @author yangkai.shen
* @date Created in 2019-08-02 15:08
*/
@Configuration
public class JustAuthConfig {
/**
* 默认情况下的模板只能支持RedisTemplate<String, String>,也就是只能存入字符串,因此支持序列化
*/
@Bean
public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
public AuthStateCache authStateCache(RedisTemplate<String,String> redisCacheTemplate) {
return new RedisStateCache(redisCacheTemplate);
}
}
```
/**
* 刷新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.在配置文件配置相关信息
`justauth` 配置列表
```yaml
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
```
| 属性名 | 类型 | 默认值 | 可选项 | 描述 |
| ------------------ | ------------------------------------------------------------ | ------ | ---------- | ----------------- |
| `justauth.enabled` | `boolean` | true | true/false | 是否启用 JustAuth |
| `justauth.type` | `java.util.Map<me.zhyd.oauth.config.AuthSource,me.zhyd.oauth.config.AuthConfig>` | 无 | | JustAuth 配置 |
## 4. 附录
`justauth.type` 配置列表
### 4.1. 基础配置
#### 4.1.1. `justauth` 配置列表
| 属性名 | 类型 | 默认值 | 可选项 | 描述 |
| ------------------ | ------------------------------------------------------------ | ------ | ---------- | ---------------------- |
| `justauth.enabled` | `boolean` | true | true/false | 是否启用 JustAuth |
| `justauth.type` | `java.util.Map<me.zhyd.oauth.config.AuthSource,me.zhyd.oauth.config.AuthConfig>` | 无 | | JustAuth 配置 |
| `justauth.cache` | `com.xkcoding.justauth.autoconfigure.CacheProperties` | | | JustAuth缓存配置 |
| `justauth.extend` | `com.xkcoding.justauth.autoconfigure.ExtendProperties` | 无 | | JustAuth第三方平台配置 |
##### 4.1.1.1. `justauth.type` 配置列表
| 属性名 | 描述 |
| --------------------------- | ------------------------------------------------------------ |
| `justauth.type.keys` | `justauth.type``Map` 格式的key 的取值请参考 [`AuthSource`](https://github.com/zhangyd-c/JustAuth/blob/master/src/main/java/me/zhyd/oauth/config/AuthSource.java) |
| `justauth.type.keys.values` | `justauth.type``Map` 格式的value 的取值请参考 [`AuthConfig`](https://github.com/zhangyd-c/JustAuth/blob/master/src/main/java/me/zhyd/oauth/config/AuthConfig.java) |
##### 4.1.1.2.`justauth.cache` 配置列表
| 属性名 | 类型 | 默认值 | 可选项 | 描述 |
| ------------------------ | ------------------------------------------------------------ | ----------------- | -------------------- | ------------------------------------------------------------ |
| `justauth.cache.type` | `com.xkcoding.justauth.autoconfigure.CacheProperties.CacheType` | default | default/redis/custom | 缓存类型default使用JustAuth默认的缓存实现redis使用默认的redis缓存实现custom用户自定义缓存实现 |
| `justauth.cache.prefix` | `java.lang.String` | JUSTAUTH::STATE:: | | 缓存前缀目前只对redis缓存生效默认 `JUSTAUTH::STATE::` |
| `justauth.cache.timeout` | `java.time.Duration` | 3分钟 | | 超时时长目前只对redis缓存生效默认`3分钟` |
##### 4.1.1.3.`justauth.extend` 配置列表
| 属性名 | 类型 | 默认值 | 可选项 | 描述 |
| ---------------------------- | -------------------------------------------- | ------ | ------ | ------------ |
| `justauth.extend.enum-class` | `Class<? extends AuthSource>` | 无 | | 枚举类全路径 |
| `justauth.extend.config` | `java.util.Map<String, ExtendRequestConfig>` | 无 | | 对应配置信息 |
###### 4.1.1.3.1.`justauth.extend.config` 配置列表
| 属性名 | 类型 | 默认值 | 可选项 | 描述 |
| ------------------------------- | ------------------------------------------------------------ | ------ | ------ | ------------------------------------------------------------ |
| `justauth.extend.config.keys` | `java.lang.String` | 无 | | key 必须在 `justauth.extend.enum-class` 配置的枚举类中声明 |
| `justauth.extend.config.values` | `com.xkcoding.justauth.autoconfigure.ExtendProperties.ExtendRequestConfig` | 无 | | value 就是 `AuthConfig` 的子类,增加了一个 `request-class` 属性配置请求的全类名,具体参考类[`ExtendProperties.ExtendRequestConfig`](https://github.com/justauth/justauth-spring-boot-starter/blob/master/src/main/java/com/xkcoding/justauth/autoconfigure/ExtendProperties.java#L49-L54) |
### 4.2. SNAPSHOT版本
![https://img.shields.io/badge/snapshots-1.3.0--SNAPSHOT-green](https://img.shields.io/badge/snapshots-1.3.0--SNAPSHOT-green)如果需要体验快照版本,可以在你的 `pom.xml`进行如下配置:
```xml
<repositories>
<!--阿里云私服-->
<repository>
<id>aliyun</id>
<name>aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</repository>
<!--中央仓库-->
<repository>
<id>oss</id>
<name>oss</name>
<url>http://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
```

56
pom.xml
View File

@@ -21,9 +21,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xkcoding</groupId>
<groupId>com.xkcoding.justauth</groupId>
<artifactId>justauth-spring-boot-starter</artifactId>
<version>1.0.0</version>
<version>1.3.0</version>
<name>justauth-spring-boot-starter</name>
<url>https://github.com/xkcoding/justauth-spring-boot-starter</url>
@@ -65,9 +65,9 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!--SpringBoot版本-->
<spring-boot.version>2.1.6.RELEASE</spring-boot.version>
<spring-boot.version>2.1.8.RELEASE</spring-boot.version>
<!--JustAuth版本-->
<justauth.version>1.10.0</justauth.version>
<justauth.version>1.13.0</justauth.version>
</properties>
<dependencies>
@@ -76,6 +76,17 @@
<artifactId>JustAuth</artifactId>
<version>${justauth.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<scope>provided</scope>
</dependency>
<!-- 对象池使用redis时必须引入 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
@@ -249,18 +260,47 @@
<distributionManagement>
<!-- 发布版私服仓库 -->
<repository>
<id>releases</id>
<name>Nexus Release Repository</name>
<id>xkcoding-nexus</id>
<name>xkcoding Nexus Release Repository</name>
<url>https://nexus.xkcoding.com/repository/maven-releases/</url>
</repository>
<!-- 快照版私服仓库 -->
<snapshotRepository>
<id>snapshots</id>
<name>Nexus Snapshot Repository</name>
<id>xkcoding-nexus</id>
<name>xkcoding Nexus Snapshot Repository</name>
<url>https://nexus.xkcoding.com/repository/maven-snapshots/</url>
</snapshotRepository>
</distributionManagement>
</profile>
<profile>
<id>github</id>
<build>
<plugins>
<!-- GPG -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<distributionManagement>
<!-- 发布到GitHub仓库 -->
<repository>
<id>github-xkcoding</id>
<name>xkcoding</name>
<url>https://maven.pkg.github.com/xkcoding/justauth-spring-boot-starter</url>
</repository>
</distributionManagement>
</profile>
</profiles>
</project>

View File

@@ -17,16 +17,26 @@
package com.xkcoding.justauth;
import com.xkcoding.justauth.properties.JustAuthProperties;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.xkcoding.justauth.autoconfigure.ExtendProperties;
import com.xkcoding.justauth.autoconfigure.JustAuthProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthDefaultSource;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.enums.AuthResponseStatus;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.request.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
@@ -37,6 +47,7 @@ import java.util.stream.Collectors;
* @author yangkai.shen
* @date Created in 2019-07-22 14:21
*/
@Slf4j
@RequiredArgsConstructor
public class AuthRequestFactory {
private final JustAuthProperties properties;
@@ -47,8 +58,22 @@ public class AuthRequestFactory {
*
* @return Oauth列表
*/
@SuppressWarnings("unchecked")
public List<String> oauthList() {
return properties.getType().keySet().stream().map(Enum::name).collect(Collectors.toList());
// 默认列表
List<String> defaultList = properties.getType().keySet().stream().map(Enum::name).collect(Collectors.toList());
// 扩展列表
List<String> extendList = new ArrayList<>();
ExtendProperties extend = properties.getExtend();
if (null != extend) {
Class enumClass = extend.getEnumClass();
List<String> names = EnumUtil.getNames(enumClass);
// 扩展列表
extendList = extend.getConfig().keySet().stream().filter(x -> names.contains(x.toUpperCase())).map(String::toUpperCase).collect(Collectors.toList());
}
// 合并
return (List<String>) CollUtil.addAll(defaultList, extendList);
}
/**
@@ -57,9 +82,85 @@ public class AuthRequestFactory {
* @param source {@link AuthSource}
* @return {@link AuthRequest}
*/
public AuthRequest get(AuthSource source) {
AuthConfig config = properties.getType().get(source);
switch (source) {
public AuthRequest get(String source) {
if (StrUtil.isBlank(source)) {
throw new AuthException(AuthResponseStatus.NO_AUTH_SOURCE);
}
// 获取 JustAuth 中已存在的
AuthRequest authRequest = getDefaultRequest(source);
// 如果获取不到则尝试取自定义的
if (authRequest == null) {
authRequest = getExtendRequest(properties.getExtend().getEnumClass(), source);
}
if (authRequest == null) {
throw new AuthException(AuthResponseStatus.UNSUPPORTED);
}
return authRequest;
}
/**
* 获取自定义的 request
*
* @param clazz 枚举类 {@link AuthSource}
* @param source {@link AuthSource}
* @return {@link AuthRequest}
*/
@SuppressWarnings("unchecked")
private AuthRequest getExtendRequest(Class clazz, String source) {
try {
EnumUtil.fromString(clazz, source.toUpperCase());
} catch (IllegalArgumentException e) {
// 无自定义匹配
return null;
}
Map<String, ExtendProperties.ExtendRequestConfig> extendConfig = properties.getExtend().getConfig();
// key 转大写
Map<String, ExtendProperties.ExtendRequestConfig> upperConfig = new HashMap<>(6);
extendConfig.forEach((k, v) -> upperConfig.put(k.toUpperCase(), v));
ExtendProperties.ExtendRequestConfig extendRequestConfig = upperConfig.get(source.toUpperCase());
if (extendRequestConfig != null) {
Class<? extends AuthRequest> requestClass = extendRequestConfig.getRequestClass();
if (requestClass != null) {
// 反射获取 Request 对象,所以必须实现 2 个参数的构造方法
return ReflectUtil.newInstance(requestClass, (AuthConfig) extendRequestConfig, authStateCache);
}
}
return null;
}
/**
* 获取默认的 Request
*
* @param source {@link AuthSource}
* @return {@link AuthRequest}
*/
private AuthRequest getDefaultRequest(String source) {
AuthDefaultSource authDefaultSource;
try {
authDefaultSource = EnumUtil.fromString(AuthDefaultSource.class, source.toUpperCase());
} catch (IllegalArgumentException e) {
// 无自定义匹配
return null;
}
AuthConfig config = properties.getType().get(authDefaultSource);
// 找不到对应关系,直接返回空
if (config == null) {
return null;
}
switch (authDefaultSource) {
case GITHUB:
return new AuthGithubRequest(config, authStateCache);
case WEIBO:
@@ -112,8 +213,18 @@ public class AuthRequestFactory {
return new AuthHuaweiRequest(config, authStateCache);
case WECHAT_ENTERPRISE:
return new AuthWeChatEnterpriseRequest(config, authStateCache);
case GITLAB:
return new AuthGitlabRequest(config, authStateCache);
case KUJIALE:
return new AuthKujialeRequest(config, authStateCache);
case ELEME:
return new AuthElemeRequest(config, authStateCache);
case MEITUAN:
return new AuthMeituanRequest(config, authStateCache);
case TWITTER:
return new AuthTwitterRequest(config, authStateCache);
default:
throw new AuthException(AuthResponseStatus.UNSUPPORTED);
return null;
}
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (c) 2019-2029, xkcoding & Yangkai.Shen & 沈扬凯 (237497819@qq.com & xkcoding.com).
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.xkcoding.justauth.autoconfigure;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.time.Duration;
/**
* <p>
* 缓存配置类
* </p>
*
* @author yangkai.shen
* @date Created in 2019/8/31 10:18
*/
@Getter
@Setter
public class CacheProperties {
/**
* 缓存类型
*/
private CacheType type = CacheType.DEFAULT;
/**
* 缓存前缀目前只对redis缓存生效默认 JUSTAUTH::STATE::
*/
private String prefix = "JUSTAUTH::STATE::";
/**
* 超时时长目前只对redis缓存生效默认3分钟
*/
private Duration timeout = Duration.ofMinutes(3);
/**
* 缓存类型
*/
@Getter
@ToString
public enum CacheType {
/**
* 使用JustAuth内置的缓存
*/
DEFAULT,
/**
* 使用Redis缓存
*/
REDIS,
/**
* 自定义缓存
*/
CUSTOM;
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (c) 2019-2029, xkcoding & Yangkai.Shen & 沈扬凯 (237497819@qq.com & xkcoding.com).
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.xkcoding.justauth.autoconfigure;
import lombok.Getter;
import lombok.Setter;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.request.AuthRequest;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* 扩展配置
* </p>
*
* @author yangkai.shen
* @date Created in 2019/10/9 11:21
*/
@Getter
@Setter
public class ExtendProperties {
/**
* 枚举类全路径
*/
private Class<? extends AuthSource> enumClass;
private Map<String, ExtendRequestConfig> config = new HashMap<>();
@Getter
@Setter
public static class ExtendRequestConfig extends AuthConfig{
/**
* 请求对应全路径
*/
private Class<? extends AuthRequest> requestClass;
}
}

View File

@@ -15,16 +15,16 @@
*
*/
package com.xkcoding.justauth;
package com.xkcoding.justauth.autoconfigure;
import com.xkcoding.justauth.properties.JustAuthProperties;
import me.zhyd.oauth.cache.AuthDefaultStateCache;
import com.xkcoding.justauth.AuthRequestFactory;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.cache.AuthStateCache;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* <p>
@@ -34,6 +34,7 @@ import org.springframework.context.annotation.Configuration;
* @author yangkai.shen
* @date Created in 2019-07-22 10:52
*/
@Slf4j
@Configuration
@EnableConfigurationProperties(JustAuthProperties.class)
public class JustAuthAutoConfiguration {
@@ -44,10 +45,10 @@ public class JustAuthAutoConfiguration {
return new AuthRequestFactory(properties, authStateCache);
}
@Bean
@ConditionalOnMissingBean
public AuthStateCache authStateCache() {
return AuthDefaultStateCache.INSTANCE;
@Configuration
@Import({JustAuthStateCacheConfiguration.Default.class, JustAuthStateCacheConfiguration.Redis.class, JustAuthStateCacheConfiguration.Custom.class})
protected static class AuthStateCacheAutoConfiguration {
}
}

View File

@@ -15,13 +15,14 @@
*
*/
package com.xkcoding.justauth.properties;
package com.xkcoding.justauth.autoconfigure;
import lombok.Getter;
import lombok.Setter;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.config.AuthDefaultSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import java.util.HashMap;
import java.util.Map;
@@ -44,8 +45,20 @@ public class JustAuthProperties {
private boolean enabled;
/**
* JustAuth 配置
* JustAuth 默认配置
*/
private Map<AuthSource, AuthConfig> type = new HashMap<>();
private Map<AuthDefaultSource, AuthConfig> type = new HashMap<>();
/**
* JustAuth 自定义配置
*/
@NestedConfigurationProperty
private ExtendProperties extend;
/**
* 缓存配置类
*/
@NestedConfigurationProperty
private CacheProperties cache = new CacheProperties();
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright (c) 2019-2029, xkcoding & Yangkai.Shen & 沈扬凯 (237497819@qq.com & xkcoding.com).
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.xkcoding.justauth.autoconfigure;
import com.xkcoding.justauth.support.cache.RedisStateCache;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.cache.AuthDefaultStateCache;
import me.zhyd.oauth.cache.AuthStateCache;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* <p>
* JustAuth 缓存装配类,{@link JustAuthAutoConfiguration.AuthStateCacheAutoConfiguration}
* </p>
*
* @author yangkai.shen
* @date Created in 2019/8/31 12:00
*/
@Slf4j
abstract class JustAuthStateCacheConfiguration {
/**
* Redis 缓存
*/
@ConditionalOnClass(RedisTemplate.class)
@ConditionalOnMissingBean(AuthStateCache.class)
@AutoConfigureBefore(RedisAutoConfiguration.class)
@ConditionalOnProperty(name = "justauth.cache.type", havingValue = "redis", matchIfMissing = true)
static class Redis {
static {
log.debug("JustAuth 使用 Redis 缓存存储 state 数据");
}
@Bean
public RedisTemplate<String, String> justAuthRedisCacheTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
public AuthStateCache authStateCache(RedisTemplate<String, String> justAuthRedisCacheTemplate, JustAuthProperties justAuthProperties) {
return new RedisStateCache(justAuthRedisCacheTemplate, justAuthProperties.getCache());
}
}
/**
* 默认缓存
*/
@ConditionalOnMissingBean(AuthStateCache.class)
@ConditionalOnProperty(name = "justauth.cache.type", havingValue = "default", matchIfMissing = true)
static class Default {
static {
log.debug("JustAuth 使用 默认缓存存储 state 数据");
}
@Bean
public AuthStateCache authStateCache() {
return AuthDefaultStateCache.INSTANCE;
}
}
/**
* 默认缓存
*/
@ConditionalOnProperty(name = "justauth.cache.type", havingValue = "custom")
static class Custom {
static {
log.debug("JustAuth 使用 自定义缓存存储 state 数据");
}
@Bean
@ConditionalOnMissingBean(AuthStateCache.class)
public AuthStateCache authStateCache() {
log.error("请自行实现 me.zhyd.oauth.cache.AuthStateCache");
throw new RuntimeException();
}
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright (c) 2019-2029, xkcoding & Yangkai.Shen & 沈扬凯 (237497819@qq.com & xkcoding.com).
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.xkcoding.justauth.support.cache;
import com.xkcoding.justauth.autoconfigure.CacheProperties;
import lombok.RequiredArgsConstructor;
import me.zhyd.oauth.cache.AuthStateCache;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit;
/**
* <p>
* Redis作为JustAuth的State的缓存
* </p>
*
* @author yangkai.shen
* @date Created in 2019-08-02 15:10
*/
@RequiredArgsConstructor
public class RedisStateCache implements AuthStateCache {
private final RedisTemplate<String, String> redisTemplate;
private final CacheProperties cacheProperties;
/**
* 存入缓存
*
* @param key 缓存key
* @param value 缓存内容
*/
@Override
public void cache(String key, String value) {
this.cache(key, value, cacheProperties.getTimeout().toMillis());
}
/**
* 存入缓存
*
* @param key 缓存key
* @param value 缓存内容
* @param timeout 指定缓存过期时间(毫秒)
*/
@Override
public void cache(String key, String value, long timeout) {
redisTemplate.opsForValue().set(cacheProperties.getPrefix() + key, value, timeout, TimeUnit.MILLISECONDS);
}
/**
* 获取缓存内容
*
* @param key 缓存key
* @return 缓存内容
*/
@Override
public String get(String key) {
return redisTemplate.opsForValue().get(cacheProperties.getPrefix() + key);
}
/**
* 是否存在key如果对应key的value值已过期也返回false
*
* @param key 缓存key
* @return true存在key并且value没过期falsekey不存在或者已过期
*/
@Override
public boolean containsKey(String key) {
Long expire = redisTemplate.getExpire(cacheProperties.getPrefix() + key, TimeUnit.MILLISECONDS);
if (expire == null) {
expire = 0L;
}
return expire > 0;
}
}

View File

@@ -4,7 +4,7 @@
"name": "justauth.type",
"type": "java.util.Map<me.zhyd.oauth.config.AuthSource,me.zhyd.oauth.config.AuthConfig>",
"description": "JustAuth 配置.",
"sourceType": "com.xkcoding.justauth.properties.JustAuthProperties"
"sourceType": "com.xkcoding.justauth.autoconfigure.JustAuthProperties"
}
],
"hints": [
@@ -129,4 +129,4 @@
]
}
]
}
}

View File

@@ -1 +1,2 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.xkcoding.justauth.JustAuthAutoConfiguration
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.xkcoding.justauth.autoconfigure.JustAuthAutoConfiguration