Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Spring Boot 使用 justauth-spring-boot-starter 快速集成 JustAuth

NotificationsYou must be signed in to change notification settings

justauth/justauth-spring-boot-starter-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 

Repository files navigation

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

快速开始

1. 基础配置

  • 引用依赖
<dependency>  <groupId>com.xkcoding</groupId>  <artifactId>justauth-spring-boot-starter</artifactId>  <version>1.3.2</version></dependency>
  • 添加配置,在application.yml 中添加配置配置信息
justauth:enabled:truetype:QQ:client-id:10**********6client-secret:1f7d08**********5b7**********29eredirect-uri:http://oauth.xkcoding.com/demo/oauth/qq/callbackcache:type:default
  • 然后就开始玩耍吧~
@Slf4j@RestController@RequestMapping("/oauth")@RequiredArgsConstructor(onConstructor_ =@Autowired)publicclassTestController {privatefinalAuthRequestFactoryfactory;@GetMappingpublicList<String>list() {returnfactory.oauthList();    }@GetMapping("/login/{type}")publicvoidlogin(@PathVariableStringtype,HttpServletResponseresponse)throwsIOException {AuthRequestauthRequest =factory.get(type);response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));    }@RequestMapping("/{type}/callback")publicAuthResponselogin(@PathVariableStringtype,AuthCallbackcallback) {AuthRequestauthRequest =factory.get(type);AuthResponseresponse =authRequest.login(callback);log.info("【response】= {}",JSONUtil.toJsonStr(response));returnresponse;    }}

2. 缓存配置

starter 内置了2种缓存实现,一种是上面的默认实现,另一种是基于 Redis 的缓存实现。

当然了,你也可以自定义实现你自己的缓存。

2.1. 默认缓存实现

在配置文件配置如下内容即可

justauth:cache:type:default

2.2. Redis 缓存实现

1.添加 Redis 相关依赖

<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.配置文件配置如下内容即可

justauth:cache:type:redis# 缓存前缀,目前只对redis缓存生效,默认 JUSTAUTH::STATE::prefix:''# 超时时长,目前只对redis缓存生效,默认3分钟timeout:1hspring:redis:host:localhost# 连接超时时间(记得添加单位,Duration)timeout:10000ms# Redis默认情况下有16个分片,这里配置具体使用的分片# database: 0lettuce:pool:# 连接池最大连接数(使用负值表示没有限制) 默认 8max-active:8# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1max-wait:-1ms# 连接池中的最大空闲连接 默认 8max-idle:8# 连接池中的最小空闲连接 默认 0min-idle:0

2.3. 自定义缓存实现

1.配置文件配置如下内容

justauth:cache:type:custom

2.自定义缓存实现AuthStateCache 接口

/** * <p> * 自定义缓存实现 * </p> * * @author yangkai.shen * @date Created in 2019/8/31 12:53 */publicclassMyAuthStateCacheimplementsAuthStateCache {/**     * 存入缓存     *     * @param key   缓存key     * @param value 缓存内容     */@Overridepublicvoidcache(Stringkey,Stringvalue) {// TODO: 自定义存入缓存    }/**     * 存入缓存     *     * @param key     缓存key     * @param value   缓存内容     * @param timeout 指定缓存过期时间(毫秒)     */@Overridepublicvoidcache(Stringkey,Stringvalue,longtimeout) {// TODO: 自定义存入缓存    }/**     * 获取缓存内容     *     * @param key 缓存key     * @return 缓存内容     */@OverridepublicStringget(Stringkey) {// TODO: 自定义获取缓存内容returnnull;    }/**     * 是否存在key,如果对应key的value值已过期,也返回false     *     * @param key 缓存key     * @return true:存在key,并且value没过期;false:key不存在或者已过期     */@OverridepublicbooleancontainsKey(Stringkey) {// TODO: 自定义判断key是否存在returnfalse;    }}

3.自动装配JustAuthConfig

/** * <p> * 自定义缓存装配 * </p> * * @author yangkai.shen * @date Created in 2019/8/31 12:29 */@ConfigurationpublicclassAuthStateConfiguration {@BeanpublicAuthStateCacheauthStateCache() {returnnewMyAuthStateCache();    }}

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

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

/** * <p> * 扩展的自定义 source * </p> * * @author yangkai.shen * @date Created in 2019/10/9 14:14 */publicenumExtendSourceimplementsAuthSource {/**     * 测试     */TEST {/**         * 授权的api         *         * @return url         */@OverridepublicStringauthorize() {return"http://authorize";        }/**         * 获取accessToken的api         *         * @return url         */@OverridepublicStringaccessToken() {return"http://accessToken";        }/**         * 获取用户信息的api         *         * @return url         */@OverridepublicStringuserInfo() {returnnull;        }/**         * 取消授权的api         *         * @return url         */@OverridepublicStringrevoke() {returnnull;        }/**         * 刷新授权的api         *         * @return url         */@OverridepublicStringrefresh() {returnnull;        }    }}

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

/** * <p> * 测试用自定义扩展的第三方request * </p> * * @author yangkai.shen * @date Created in 2019/10/9 14:19 */publicclassExtendTestRequestextendsAuthDefaultRequest {publicExtendTestRequest(AuthConfigconfig) {super(config,ExtendSource.TEST);    }publicExtendTestRequest(AuthConfigconfig,AuthStateCacheauthStateCache) {super(config,ExtendSource.TEST,authStateCache);    }/**     * 获取access token     *     * @param authCallback 授权成功后的回调参数     * @return token     * @see AuthDefaultRequest#authorize()     * @see AuthDefaultRequest#authorize(String)     */@OverrideprotectedAuthTokengetAccessToken(AuthCallbackauthCallback) {returnAuthToken.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)     */@OverrideprotectedAuthUsergetUserInfo(AuthTokenauthToken) {returnAuthUser.builder().username("test").nickname("test").gender(AuthUserGender.MALE).token(authToken).source(this.source.toString()).build();    }/**     * 撤销授权     *     * @param authToken 登录成功后返回的Token信息     * @return AuthResponse     */@OverridepublicAuthResponserevoke(AuthTokenauthToken) {returnAuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).msg(AuthResponseStatus.SUCCESS.getMsg()).build();    }/**     * 刷新access token (续期)     *     * @param authToken 登录成功后返回的Token信息     * @return AuthResponse     */@OverridepublicAuthResponserefresh(AuthTokenauthToken) {returnAuthResponse.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:enabled:trueextend:enum-class:com.xkcoding.justauthspringbootstarterdemo.extend.ExtendSourceconfig:TEST:request-class:com.xkcoding.justauthspringbootstarterdemo.extend.ExtendTestRequestclient-id:xxxxxxclient-secret:xxxxxxxxredirect-uri:http://oauth.xkcoding.com/demo/oauth/test/callback

附录

1. 基础配置

justauth 配置列表

属性名类型默认值可选项描述
justauth.enabledbooleantruetrue/false是否启用 JustAuth
justauth.typejava.util.Map<me.zhyd.oauth.config.AuthSource,me.zhyd.oauth.config.AuthConfig>JustAuth 配置
justauth.cachecom.xkcoding.justauth.properties.CachePropertiesJustAuth缓存配置

justauth.type 配置列表

属性名描述
justauth.type.keysjustauth.typeMap 格式的,key 的取值请参考AuthSource
justauth.type.keys.valuesjustauth.typeMap 格式的,value 的取值请参考AuthConfig

justauth.cache 配置列表

属性名类型默认值可选项描述
justauth.cache.typecom.xkcoding.justauth.properties.CacheProperties.CacheTypedefaultdefault/redis/custom缓存类型,default使用JustAuth默认的缓存实现,redis使用默认的redis缓存实现,custom用户自定义缓存实现
justauth.cache.prefixstringJUSTAUTH::STATE::缓存前缀,目前只对redis缓存生效,默认 JUSTAUTH::STATE::
justauth.cache.timeoutjava.time.Duration3分钟超时时长,目前只对redis缓存生效,默认3分钟

justauth.extend 配置列表

属性名类型默认值可选项描述
justauth.extend.enum-classClass<? extends AuthSource>枚举类全路径
justauth.extend.configjava.util.Map<String, ExtendRequestConfig>对应配置信息

justauth.extend.config 配置列表

属性名类型默认值可选项描述
justauth.extend.config.keysjava.lang.Stringkey 必须在justauth.extend.enum-class 配置的枚举类中声明
justauth.extend.config.valuescom.xkcoding.justauth.autoconfigure.ExtendProperties.ExtendRequestConfigvalue 就是AuthConfig 的子类,增加了一个request-class 属性配置请求的全类名,具体参考类ExtendProperties.ExtendRequestConfig

2. SNAPSHOT版本

https://img.shields.io/badge/snapshots-1.4.0--SNAPSHOT-green如果需要体验快照版本,可以在你的pom.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>

About

Spring Boot 使用 justauth-spring-boot-starter 快速集成 JustAuth

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors2

  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp