springboot项目justAuth扩展第二个小程序

发布于:2025-08-07 ⋅ 阅读:(26) ⋅ 点赞:(0)

1. 首先用的是bootstart

<dependency>
  <groupId>com.youkol.support</groupId>
  <artifactId>justauth-spring-boot-starter</artifactId>
  <version>${justauth-spring-boot.version}</version>
</dependency>

2. 自定义request(枚举类配置方式),继承AuthDefaultRequest 

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthDefaultRequest;
import me.zhyd.oauth.utils.HttpUtils;
import me.zhyd.oauth.utils.UrlBuilder;


public class AuthWechatMiniBrokerRequest extends AuthDefaultRequest {

    public AuthWechatMiniBrokerRequest(AuthConfig config, AuthSource source) {
        super(config, ExtendSource.WECHAT_MINI_PROGRAM_BROKER);
    }

    public AuthWechatMiniBrokerRequest(AuthConfig config, AuthStateCache authStateCache) {
        super(config, ExtendSource.WECHAT_MINI_PROGRAM_BROKER, authStateCache);
    }
    @Override
    public AuthToken getAccessToken(AuthCallback authCallback) {
        // 参见 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html 文档
        // 使用 code 获取对应的 openId、unionId 等字段
        String response = new HttpUtils(config.getHttpConfig()).get(accessTokenUrl(authCallback.getCode())).getBody();
        JSCode2SessionResponse accessTokenObject = JSONObject.parseObject(response, JSCode2SessionResponse.class);
        assert accessTokenObject != null;
        checkResponse(accessTokenObject);
        // 拼装结果
        return AuthToken.builder()
                .openId(accessTokenObject.getOpenid())
                .unionId(accessTokenObject.getUnionId())
                .accessToken(accessTokenObject.getSessionKey())
                .build();
    }

    @Override
    public AuthUser getUserInfo(AuthToken authToken) {
        // 参见 https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html 文档
        // 如果需要用户信息,需要在小程序调用函数后传给后端
        return AuthUser.builder()
                .username("")
                .nickname("")
                .avatar("")
                .uuid(authToken.getOpenId())
                .token(authToken)
                .source(source.toString())
                .build();
    }

    /**
     * 检查响应内容是否正确
     *
     * @param response 请求响应内容
     */
    private void checkResponse(JSCode2SessionResponse response) {
        if (response.getErrorCode() != 0) {
            throw new AuthException(response.getErrorCode(), response.getErrorMsg());
        }
    }

    @Override
    protected String accessTokenUrl(String code) {
        return UrlBuilder.fromBaseUrl(source.accessToken())
                .queryParam("appid", config.getClientId())
                .queryParam("secret", config.getClientSecret())
                .queryParam("js_code", code)
                .queryParam("grant_type", "authorization_code")
                .build();
    }

    @Data
    @SuppressWarnings("SpellCheckingInspection")
    private static class JSCode2SessionResponse {

        @JSONField(name = "errcode")
        private int errorCode;
        @JSONField(name = "errmsg")
        private String errorMsg;
        @JSONField(name = "session_key")
        private String sessionKey;
        private String openid;
        @JSONField(name = "unionid")
        private String unionId;

    }
}

3. 自定义AuthSource(枚举类配置方式),继承AuthSource


import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.request.AuthDefaultRequest;

public enum ExtendSource implements AuthSource {
    WECHAT_MINI_PROGRAM_BROKER {
        @Override
        public String authorize() {
            // 参见 https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html 文档
            throw new UnsupportedOperationException("不支持获取授权 url,请使用小程序内置函数 wx.login() 登录获取 code");
        }

        @Override
        public String accessToken() {
            // 参见 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html 文档
            // 获取 openid, unionId , session_key 等字段
            return "https://api.weixin.qq.com/sns/jscode2session";
        }

        @Override
        public String userInfo() {
            // 参见 https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html 文档
            throw new UnsupportedOperationException("不支持获取用户信息 url,请使用小程序内置函数 wx.getUserProfile() 获取用户信息");
        }

        @Override
        public Class<? extends AuthDefaultRequest> getTargetClass() {
            return AuthWechatMiniBrokerRequest.class;
        }
    }
}

4. yml配置

justauth:
  enabled: true
  type:
    WECHAT_MINI_PROGRAM: # 微信小程序
      client-id: ${wx.miniapp.appid}
      client-secret: ${wx.miniapp.secret}
      ignore-check-redirect-uri: true
      ignore-check-state: true # 微信小程序,不会使用到 state,所以不进行校验
  extend:
    enum-class: com.demo.module.system.framework.justauth.extend.ExtendSource
    config:
      WECHAT_MINI_PROGRAM_BROKER:
        request-class: com.demo.module.system.framework.justauth.extend.AuthWechatMiniBrokerRequest
        client-id: wxea86b728b1e5ca8h
        client-secret: c69e4d7b65b48h9150235e8de55b246c
        ignore-check-redirect-uri: true
        ignore-check-state: true # 微信小程序,不会使用到 state,所以不进行校验
  cache:
    type: REDIS
    prefix: 'social_auth_state:' # 缓存前缀,目前只对 Redis 缓存生效,默认 JUSTAUTH::STATE::
    timeout: 24h # 超时时长,目前只对 Redis 缓存生效,默认 3 分钟

配置就是上面的配置,具体使用参看官网文档:

justauth-spring-boot-starter: Spring boot starter for JustAuth (Spring Boot 集成 JustAuth)

JustAuth


网站公告

今日签到

点亮在社区的每一天
去签到