怎么在springboot中使用jwt与springSecurity实现一个微信小程序授权登录功能

发布时间:2021-01-25 15:35:43 作者:Leah
来源:亿速云 阅读:350

怎么在springboot中使用jwt与springSecurity实现一个微信小程序授权登录功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

通过自定义的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));
 }
}

看完上述内容,你们掌握怎么在springboot中使用jwt与springSecurity实现一个微信小程序授权登录功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. 微信小程序后端实现授权登录
  2. 微信小程序如何实现授权登录

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot jwt springsecurity

上一篇:如何使用redis分布式锁解决高并发时的线程安全问题

下一篇:怎么在Spring Boot 2中利用Spring security 与JWT登录微信小程序

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》