Yshop框架的小程序登录

2024-06-06 02:20
文章标签 程序 登录 框架 yshop

本文主要是介绍Yshop框架的小程序登录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1配置

根据请求头去判断,走小程序,还是Pc端。

#jwt
jwt:header: Authorization#小程序前缀 请求头mini-program-header: MiAuthorization# 令牌前缀token-start-with: Bearersecret: k09BQnaF# 必须使用最少88位的Base64对该令牌进行编码base64-secret: ZmQ0ZGI5NjQ0MDQwY2I4MjMxY2Y3ZmI3MjdhN2ZmMjNhODViOTg1ZGE0NTBjMGM4NDA5NzYxMjdjOWMwYWRmZTBlZjlhNGY3ZTg4Y2U3YTE1ODVkZDU5Y2Y3OGYwZWE1NzUzNWQ2YjFjZDc0NGMxZWU2MmQ3MjY1NzJmNTE0MzI=# 令牌过期时间 此处单位/毫秒 ,默认4小时,可在此网站生成 https://www.convertworld.com/zh-hans/time/milliseconds.htmltoken-validity-in-seconds: 14400000# 在线用户keyonline-key: online-token# 小程序在线用户mi-online-key: mi-online-token# 验证码code-key: code-key

2.登录

登录时,设置用户信息存储到redis中。

    /**** 根据账户,密码 登录* @param exUser* @return*/@Overridepublic R<Object> VxLogin(ExUser exUser) {// 查询数据库中的账号密码是否存在ExUser exUserA = exUserMapper.selectOne(new LambdaQueryWrapper<ExUser>().eq(StringUtils.isNotBlank(exUser.getUserUsername()), ExUser::getUserUsername, exUser.getUserUsername()).eq(StringUtils.isNotBlank(exUser.getUserPassword()), ExUser::getUserPassword, exUser.getUserPassword()).eq(Objects.nonNull(exUser.getUserStatus()), ExUser::getUserStatus, 1));if (Objects.isNull(exUserA)) {return R.error("该用户未存在");}// 生成tokenString token = tokenUtil.generateTokenA(exUserA);Map<String, Object> authInfo = new HashMap<String, Object>(2) {{put("token", properties.getTokenStartWith() + token);put("user", exUserA);}};RedisUtil.set(properties.getMiOnlineKey() + token, exUserA, properties.getTokenValidityInSeconds() / 1000);return R.success(authInfo);}

3.过滤器

获取请求头,判断是小程序接口还是Pc端接口。

/*** Copyright (C) 2018-2022* All rights reserved, Designed By www.yixiang.co*/
package co.yixiang.modules.security.security;import co.yixiang.domain.ExUser;
import co.yixiang.modules.security.config.SecurityProperties;
import co.yixiang.modules.security.service.OnlineUserService;
import co.yixiang.modules.user.vo.OnlineUser;
import co.yixiang.utils.SpringContextHolder;
import co.yixiang.utils.StringUtils;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.GenericFilterBean;import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;/*** @author /*/
@Slf4j
public class TokenFilter extends GenericFilterBean {@Autowiredprivate SecurityProperties securityProperties;private final TokenUtil tokenUtil;TokenFilter(TokenUtil tokenUtil) {this.tokenUtil = tokenUtil;}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException {HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;String requestRri = httpServletRequest.getRequestURI();OnlineUser onlineUser = null;ExUser exUser = null;String authToken = null;String authTokenA = null;try {SecurityProperties properties = SpringContextHolder.getBean(SecurityProperties.class);OnlineUserService onlineUserService = SpringContextHolder.getBean(OnlineUserService.class);String clientType = httpServletRequest.getHeader(properties.getHeader());String miniProgramClientType = httpServletRequest.getHeader(properties.getMiniProgramHeader());// 检查是否存在PC端或小程序端的请求头if (clientType == null && miniProgramClientType == null) {log.error("Both Client-Type and Mini-Program-Client-Type headers are missing.");filterChain.doFilter(httpServletRequest, servletResponse);return;}if (StringUtils.isNotBlank(clientType)) {// PC端authToken = tokenUtil.getToken(httpServletRequest);} else if (StringUtils.isNotBlank(miniProgramClientType)) {// 小程序authTokenA = tokenUtil.getTokenA(httpServletRequest);}if (authToken == null && authTokenA == null) {log.error("Both authToken and authTokenA are null.");filterChain.doFilter(httpServletRequest, servletResponse);return;}if (StringUtils.isNotBlank(authToken)) {onlineUser = onlineUserService.getOne(properties.getOnlineKey() + authToken);} else if (StringUtils.isNotBlank(authTokenA)) {exUser = onlineUserService.getOneA(properties.getMiOnlineKey() + authTokenA);
//                String userJson = RedisUtil.get("userA");
//                ExUser user = JSON.parseObject(userJson, ExUser.class);}} catch (ExpiredJwtException e) {log.error(e.getMessage());}// PcString username = StringUtils.isNotBlank(authToken) ? tokenUtil.getUsernameFromToken(authToken) : null;// 小程序String usernameA = StringUtils.isNotBlank(authTokenA) ? tokenUtil.getUsernameFromToken(authTokenA) : null;if (onlineUser != null && username != null && SecurityContextHolder.getContext().getAuthentication() == null && tokenUtil.validateToken(authToken)) {UserDetails userDetails = tokenUtil.getUserDetails(authToken);UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));SecurityContextHolder.getContext().setAuthentication(authentication);log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);}else if(exUser != null && usernameA != null && SecurityContextHolder.getContext().getAuthentication() == null && tokenUtil.validateTokenA(authTokenA)){UserDetails userDetailsA = tokenUtil.getUserDetailsA(authTokenA);UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetailsA, null, null);authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));SecurityContextHolder.getContext().setAuthentication(authenticationToken);}else {tokenUtil.removeToken(authToken);tokenUtil.removeToken(authTokenA);log.debug("no valid JWT token found, uri: {}", requestRri);}filterChain.doFilter(httpServletRequest, servletResponse);}
}

4. 工具类完善

/*** Copyright (C) 2018-2022* All rights reserved, Designed By www.yixiang.co*/
package co.yixiang.modules.security.security;import co.yixiang.domain.ExUser;
import co.yixiang.modules.security.config.SecurityProperties;
import co.yixiang.modules.security.service.OnlineUserService;
import co.yixiang.modules.user.vo.OnlineUser;
import co.yixiang.utils.SpringContextHolder;
import co.yixiang.utils.StringUtils;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.GenericFilterBean;import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;/*** @author /*/
@Slf4j
public class TokenFilter extends GenericFilterBean {@Autowiredprivate SecurityProperties securityProperties;private final TokenUtil tokenUtil;TokenFilter(TokenUtil tokenUtil) {this.tokenUtil = tokenUtil;}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException {HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;String requestRri = httpServletRequest.getRequestURI();OnlineUser onlineUser = null;ExUser exUser = null;String authToken = null;String authTokenA = null;try {SecurityProperties properties = SpringContextHolder.getBean(SecurityProperties.class);OnlineUserService onlineUserService = SpringContextHolder.getBean(OnlineUserService.class);String clientType = httpServletRequest.getHeader(properties.getHeader());String miniProgramClientType = httpServletRequest.getHeader(properties.getMiniProgramHeader());// 检查是否存在PC端或小程序端的请求头if (clientType == null && miniProgramClientType == null) {log.error("Both Client-Type and Mini-Program-Client-Type headers are missing.");filterChain.doFilter(httpServletRequest, servletResponse);return;}if (StringUtils.isNotBlank(clientType)) {// PC端authToken = tokenUtil.getToken(httpServletRequest);} else if (StringUtils.isNotBlank(miniProgramClientType)) {// 小程序authTokenA = tokenUtil.getTokenA(httpServletRequest);}if (authToken == null && authTokenA == null) {log.error("Both authToken and authTokenA are null.");filterChain.doFilter(httpServletRequest, servletResponse);return;}if (StringUtils.isNotBlank(authToken)) {onlineUser = onlineUserService.getOne(properties.getOnlineKey() + authToken);} else if (StringUtils.isNotBlank(authTokenA)) {exUser = onlineUserService.getOneA(properties.getMiOnlineKey() + authTokenA);
//                String userJson = RedisUtil.get("userA");
//                ExUser user = JSON.parseObject(userJson, ExUser.class);}} catch (ExpiredJwtException e) {log.error(e.getMessage());}// PcString username = StringUtils.isNotBlank(authToken) ? tokenUtil.getUsernameFromToken(authToken) : null;// 小程序String usernameA = StringUtils.isNotBlank(authTokenA) ? tokenUtil.getUsernameFromToken(authTokenA) : null;if (onlineUser != null && username != null && SecurityContextHolder.getContext().getAuthentication() == null && tokenUtil.validateToken(authToken)) {UserDetails userDetails = tokenUtil.getUserDetails(authToken);UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));SecurityContextHolder.getContext().setAuthentication(authentication);log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);}else if(exUser != null && usernameA != null && SecurityContextHolder.getContext().getAuthentication() == null && tokenUtil.validateTokenA(authTokenA)){UserDetails userDetailsA = tokenUtil.getUserDetailsA(authTokenA);UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetailsA, null, null);authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));SecurityContextHolder.getContext().setAuthentication(authenticationToken);}else {tokenUtil.removeToken(authToken);tokenUtil.removeToken(authTokenA);log.debug("no valid JWT token found, uri: {}", requestRri);}filterChain.doFilter(httpServletRequest, servletResponse);}
}

5. 获取当前用户数据的工具

判断该接口是否被类实现

/*** Copyright (C) 2018-2022* All rights reserved, Designed By www.yixiang.co*/
package co.yixiang.utils;import cn.hutool.json.JSONObject;
import co.yixiang.domain.ExUser;
import co.yixiang.exception.BadRequestException;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;/*** 获取当前登录的用户* @author Zheng Jie* @date 2019-01-17*/
public class SecurityUtils {public static UserDetails getUserDetails() {final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();if (authentication == null) {throw new BadRequestException(HttpStatus.UNAUTHORIZED, "当前登录状态过期");}if(authentication.getPrincipal() instanceof ExUser){return (UserDetails) authentication.getPrincipal();}if (authentication.getPrincipal() instanceof UserDetails) {UserDetails userDetails = (UserDetails) authentication.getPrincipal();UserDetailsService userDetailsService = SpringContextHolder.getBean(UserDetailsService.class);return userDetailsService.loadUserByUsername(userDetails.getUsername());}throw new BadRequestException(HttpStatus.UNAUTHORIZED, "找不到当前登录的信息");}/*** 获取系统用户名称* @return 系统用户名称*/public static String getUsername(){final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();if (authentication == null) {throw new BadRequestException(HttpStatus.UNAUTHORIZED, "当前登录状态过期");}UserDetails userDetails = (UserDetails) authentication.getPrincipal();return userDetails.getUsername();}/*** 获取系统用户id* @return 系统用户id*/public static Long getUserId(){Object obj = getUserDetails();JSONObject json = new JSONObject(obj);return json.get("id", Long.class);}
}

这篇关于Yshop框架的小程序登录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1034827

相关文章

springboot security验证码的登录实例

《springbootsecurity验证码的登录实例》:本文主要介绍springbootsecurity验证码的登录实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录前言代码示例引入依赖定义验证码生成器定义获取验证码及认证接口测试获取验证码登录总结前言在spring

Python Dash框架在数据可视化仪表板中的应用与实践记录

《PythonDash框架在数据可视化仪表板中的应用与实践记录》Python的PlotlyDash库提供了一种简便且强大的方式来构建和展示互动式数据仪表板,本篇文章将深入探讨如何使用Dash设计一... 目录python Dash框架在数据可视化仪表板中的应用与实践1. 什么是Plotly Dash?1.1

基于Flask框架添加多个AI模型的API并进行交互

《基于Flask框架添加多个AI模型的API并进行交互》:本文主要介绍如何基于Flask框架开发AI模型API管理系统,允许用户添加、删除不同AI模型的API密钥,感兴趣的可以了解下... 目录1. 概述2. 后端代码说明2.1 依赖库导入2.2 应用初始化2.3 API 存储字典2.4 路由函数2.5 应

Python GUI框架中的PyQt详解

《PythonGUI框架中的PyQt详解》PyQt是Python语言中最强大且广泛应用的GUI框架之一,基于Qt库的Python绑定实现,本文将深入解析PyQt的核心模块,并通过代码示例展示其应用场... 目录一、PyQt核心模块概览二、核心模块详解与示例1. QtCore - 核心基础模块2. QtWid

最新Spring Security实战教程之Spring Security安全框架指南

《最新SpringSecurity实战教程之SpringSecurity安全框架指南》SpringSecurity是Spring生态系统中的核心组件,提供认证、授权和防护机制,以保护应用免受各种安... 目录前言什么是Spring Security?同类框架对比Spring Security典型应用场景传统

最新Spring Security实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)

《最新SpringSecurity实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)》本章节介绍了如何通过SpringSecurity实现从配置自定义登录页面、表单登录处理逻辑的配置,并简单模拟... 目录前言改造准备开始登录页改造自定义用户名密码登陆成功失败跳转问题自定义登出前后端分离适配方案结语前言

如何用java对接微信小程序下单后的发货接口

《如何用java对接微信小程序下单后的发货接口》:本文主要介绍在微信小程序后台实现发货通知的步骤,包括获取Access_token、使用RestTemplate调用发货接口、处理AccessTok... 目录配置参数 调用代码获取Access_token调用发货的接口类注意点总结配置参数 首先需要获取Ac

Python结合Flask框架构建一个简易的远程控制系统

《Python结合Flask框架构建一个简易的远程控制系统》这篇文章主要为大家详细介绍了如何使用Python与Flask框架构建一个简易的远程控制系统,能够远程执行操作命令(如关机、重启、锁屏等),还... 目录1.概述2.功能使用系统命令执行实时屏幕监控3. BUG修复过程1. Authorization

基于Python开发PDF转Doc格式小程序

《基于Python开发PDF转Doc格式小程序》这篇文章主要为大家详细介绍了如何基于Python开发PDF转Doc格式小程序,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 用python实现PDF转Doc格式小程序以下是一个使用Python实现PDF转DOC格式的GUI程序,采用T

Oracle登录时忘记用户名或密码该如何解决

《Oracle登录时忘记用户名或密码该如何解决》:本文主要介绍如何在Oracle12c中忘记用户名和密码时找回或重置用户账户信息,文中通过代码介绍的非常详细,对同样遇到这个问题的同学具有一定的参... 目录一、忘记账户:二、忘记密码:三、详细情况情况 1:1.1. 登录到数据库1.2. 查看当前用户信息1.