springboot+jwt+springSecurity微信小程序授权登录 springboot+jwt+springSecurity微信小程序授权登录问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

springboot+jwt+springSecurity微信小程序授权登录 springboot+jwt+springSecurity微信小程序授权登录问题

尽力漂亮   2021-01-27 我要评论

场景重现:1.微信小程序向后台发送请求 ——而后台web采用的springSecuriry没有token生成,就会拦截请求,,所以小编记录下这个问题

微信小程序授权登录问题

思路

参考网上一大堆资料 核心关键字: 自定义授权+鉴权 (说的通俗就是解决办法就是改造springSecurity的过滤器)

参考文章

https:

总的来说的

通过自定义的WxAppletAuthenticationFilter替换默认的UsernamePasswordAuthenticationFilter,在UsernamePasswordAuthenticationFilter中可任意定制自己的登录方式。

springSecurity的原来的登录过滤器UsernamePasswordAuthenticationFilter

在这里插入图片描述

采用账户+密码的形式

在这里插入图片描述

说明我微信小程序这里很有可能不适用要升级,因为微信小程序采用openid的形式登录,而没有password

用户认证

需要结合JWT来实现用户认证,第一步登录成功后如何颁发token。

关键点

使用cn.hutool.http请求第三方数据

 <dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>4.5.16</version>
 </dependency>

说明:请求第三方数据时,需要授权。

第三方(微信小程序)会给到appid和secret,请求携带appid和secret获取一个token和expires,又了token就又了操作第三方数据的权限。

每次操作第三方数据时就需要携带token。

package com.shbykj.springboot.wx.security.handler;

import cn.hutool.http.ContentType;
import com.alibaba.fastjson.JSON;
import com.shbykj.springboot.wx.enums.ConstantEnum;
import com.shbykj.springboot.wx.security.WxAppletAuthenticationToken;
import com.shbykj.springboot.wx.util.JwtTokenUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户认证通过的处理handler
 */
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

 @Autowired
 private JwtTokenUtils jwtTokenUtils;

 @Override
 public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
 // 使用jwt管理,所以封装用户信息生成jwt响应给前端
 String token = jwtTokenUtils.generateToken(((WxAppletAuthenticationToken)authentication).getOpenid());
 Map<String, Object> result = new HashMap<>();
 result.put(ConstantEnum.AUTHORIZATION.getValue(), token);
 httpServletResponse.setContentType(ContentType.JSON.toString());
 httpServletResponse.getWriter().write(JSON.toJSONString(result));
 }
}

总结

发现微信小程序和后台使用一个项目的话,会有 不能使用多个WebSecurityConfig这个错误,暂时只想到这里了

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们