微信小程序登录流程

微信小程序登录流程时序

在这里插入图片描述

jwt令牌配置

sky:
  wechat:
    appid: wx8780a37323517afa
    secret: f01ec214a64dec164faa9d2003c6f27f

生成jwt令牌

User user=userService.wxlogin(userLoginDTO);
//为微信用户生成jwt令牌
Map<String,Object>claims=new HashMap<>();
claims.put(JwtClaimsConstant.USER_ID,user.getId());
String token= JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);
UserLoginVO userLoginVO=new UserLoginVO().builder()
        .id(user.getId())
        .openid(user.getOpenid())
        .token(token)
        .build();
return Result.success(userLoginVO);

使用微信接口服务,获取当前微信用户的openId

/**
 * 用户登录
 * @param userLoginDTO
 * @return
 */
@Override
public User wxlogin(UserLoginDTO userLoginDTO) {
    //调用微信接口服务,获得当前用户的openid
    Map<String,String>map=new HashMap<>();
    map.put("appid",weChatProperties.getAppid());
    map.put("secret",weChatProperties.getSecret());
    map.put("js_code",userLoginDTO.getCode());
    map.put("grant_type","authorization_code" );
            String json=HttpClientUtil.doGet(welogin,map);
    JSONObject jsonObject = JSON.parseObject(json);
    String openid = jsonObject.getString("openid");
    //判断openid是否为空,为空代表登录失败,抛出异常
    if (openid==null){
    throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
    }
    //判断当前用户是否为新用户
    User user = userMapper.gerByOpenid(openid);
    //是新用户自动注册
    if(user==null){
       user=  User.builder()
                .openid(openid)
                .createTime(LocalDateTime.now())
                .build();
        userMapper.insert(user);
    }
    //返回用户对象
    return user;
}

创建拦截器并注册

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法,直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            BaseContext.setCurrentId(userId);
            log.info("当前用户id:", userId);
            //3、通过,放行
            return true;
        } catch (Exception ex) {
            //4、不通过,响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}

/**
 * 注册自定义拦截器
 *
 * @param registry
 */
protected void addInterceptors(InterceptorRegistry registry) {
    log.info("开始注册自定义拦截器...");
    registry.addInterceptor(jwtTokenAdminInterceptor)
            .addPathPatterns("/admin/**")
            .excludePathPatterns("/admin/employee/login");
    registry.addInterceptor(jwtTokenUserInterceptor)
            .addPathPatterns("/user/**")
            .excludePathPatterns("/user/user/login")
            .excludePathPatterns("/user/shop/status");
}
  • 12
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值