当前位置: 首页>后端>正文

JustAuth整合第三方登录组件

一、官网

JustAuth

整合平台:

  • QQ登录
  • 新浪微博登录
  • 百度登录
  • Gitee登录
  • Github登录
  • 开源中国登录
  • StackOverflow登录
  • Coding(腾讯云)登录
  • 程序员客栈登录
  • CSDN登录
  • Google登录
  • Facebook登录
  • 钉钉登录
  • 阿里云登录
  • 支付宝登录
  • 华为登录
  • 飞书登录
  • 微信开放平台登录
  • 企业微信扫码登录
  • 企业微信网页登录
  • 抖音登录
  • 京东登录

二、样例-微信开放平台登录

2.1 引入依赖
<dependency>
  <groupId>me.zhyd.oauth</groupId>
  <artifactId>JustAuth</artifactId>
  <version>${latest.version}</version>
</dependency>
2.2 创建Request
AuthRequest authRequest = new AuthWeChatRequest(AuthConfig.builder()
      .clientId("Client ID")
      .clientSecret("Client Secret")
      .redirectUri("https://www.zhyd.me/oauth/callback/wechat")
      .build());
2.3 生成授权地址

我们可以直接使用以下方式生成第三方平台的授权链接

String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());

这个链接我们可以直接后台重定向跳转,也可以返回到前端后,前端控制跳转。前端控制的好处就是,可以将第三方的授权页嵌入到iframe中,适配网站设计。

2.3 以上完整代码如下
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.request.AuthWeChatOpenRequest;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@RestController
@RequestMapping("/oauth")
public class RestAuthController {

    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public Object login(AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
        return authRequest.login(callback);
    }

    private AuthRequest getAuthRequest() {
        return new AuthWeChatOpenRequest(AuthConfig.builder()
                .clientId("Client ID")
                .clientSecret("Client Secret")
                .redirectUri("https://www.zhyd.me/oauth/callback/wechat")
                .build());
    }
}

三、集群环境问题

3.1 JustAuth默认使用Map做为缓存

JustAuth默认使用ConcurrentHashMap做为缓存,在单机环境下无问题,但在集群环境下(分布式多实例部署的应用)就会出现问题。

JustAuth部分源码

public class AuthWeChatOpenRequest extends AuthDefaultRequest {
    public AuthWeChatOpenRequest(AuthConfig config) {
        super(config, AuthDefaultSource.WECHAT_OPEN);
    }

    public AuthWeChatOpenRequest(AuthConfig config, AuthStateCache authStateCache) {
        super(config, AuthDefaultSource.WECHAT_OPEN, authStateCache);
    }

    .....
}



public class AuthDefaultCache implements AuthCache {

    /**
     * state cache
     */
    private static Map<String, CacheState> stateCache = new ConcurrentHashMap<>();
    private final ReentrantReadWriteLock cacheLock = new ReentrantReadWriteLock(true);
    private final Lock writeLock = cacheLock.writeLock();
    private final Lock readLock = cacheLock.readLock();

    public AuthDefaultCache() {
        if (AuthCacheConfig.schedulePrune) {
            this.schedulePrune(AuthCacheConfig.timeout);
        }
    }
  }
3.2 自定义使用Reids做缓存解决集群问题
3.2.1 实现AuthStateCache接口
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.cache.AuthCacheConfig;
import me.zhyd.oauth.cache.AuthStateCache;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 自定义AuthState Rds 缓存
 * @author zak
 **/
@Slf4j
@Component
public class AuthStateRedisCache implements AuthStateCache {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 存入缓存,默认3分钟
     *
     * @param key   缓存key
     * @param value 缓存内容
     */
    @Override
    public void cache(String key, String value) {
        log.info("RDS, 存入缓存,默认3分钟, key: {}, value: {}", key, value);
        stringRedisTemplate.opsForValue().set(key, value, AuthCacheConfig.timeout, TimeUnit.MILLISECONDS);
    }

    /**
     * 存入缓存
     *
     * @param key     缓存key
     * @param value   缓存内容
     * @param timeout 指定缓存过期时间(毫秒)
     */
    @Override
    public void cache(String key, String value, long timeout) {
        log.info("RDS, 存入缓存, key: {}, value: {}, timeout: {}", key, value, timeout);
        stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.MILLISECONDS);
    }

    /**
     * 获取缓存内容
     *
     * @param key 缓存key
     * @return 缓存内容
     */
    @Override
    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 是否存在key,如果对应key的value值已过期,也返回false
     *
     * @param key 缓存key
     * @return true:存在key,并且value没过期;false:key不存在或者已过期
     */
    @Override
    public boolean containsKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }
}
3.2.2 使用自定义缓存
    @Resource
    private AuthStateRedisCache stateRedisCache;

    AuthRequest authRequest = new AuthWeChatOpenRequest(AuthConfig.builder()
        .clientId(wechatAppId)
        .clientSecret(wechatAppSecret)
        .redirectUri(StrUtil.isNotBlank(redirectUri) redirectUri : wechatRedirectUri)
        .build(), stateRedisCache);

https://www.xamrdz.com/backend/3pa1941379.html

相关文章: