软件编程
位置:首页>> 软件编程>> java编程>> springboot+jwt+springSecurity微信小程序授权登录问题

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

作者:尽力漂亮  发布时间:2022-10-13 03:36:22 

标签:springboot,jwt,springSecurity,微信小程序,登录

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

微信小程序授权登录问题

思路

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

参考文章

https://www.jb51.net/article/204704.htm

总的来说的

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

springSecurity的原来的登录过滤器UsernamePasswordAuthenticationFilter

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

采用账户+密码的形式

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

说明我微信小程序这里很有可能不适用要升级,因为微信小程序采用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));
}
}

来源:https://blog.csdn.net/weixin_44106334/article/details/110920815

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com