您好,登录后才能下订单哦!
怎么在springboot中使用jwt与springSecurity实现一个微信小程序授权登录功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
通过自定义的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));
}
}看完上述内容,你们掌握怎么在springboot中使用jwt与springSecurity实现一个微信小程序授权登录功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。