概述
实现微信小程序登录功能
- 技术栈&工具
- 登录流程
- 流程图
- ==具体流程请参考微信小程序官方文档:== [微信小程序官方API](https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html).
- 代码实现
- 一.pom文件配置可能会用到的一些依赖(dependencies)
- 笔者这里只是列出需要哪些依赖,具体的依赖版本大家可以去Maven中央仓库自行查询:[Maven中央仓库](https://mvnrepository.com/).
- 二.部分yml文件配置(application.yml)
- 三.工具类(Utils)
- 1. Http请求工具类(HttpClientUtil)
- 2. 微信工具类(WechatUtil)
- 2. Token生成与解析工具类(JwtUtil)
- 2. 生成分布式自增id工具类(IdWorker)
- 2.时间戳生成类(DateTimeTransferUtil)
- 四.实体类(pojo)
- 用户(User)
- 五.Controller层(UserController)
- 六.Service层(UserServiceImpl)
- 七.Dao层(UserDao)
- 八.Token拦截器及其配置类(TokenInterceptor&InterceptorConfig)
- 九.全局异常处理类(GlobalException&BasicException)
- 整体的框架:
- 到这里登录的代码就结束了,这里显示的是后端代码,笔者也是第一次开发小程序后台,对微信小程序不太熟悉,如果有什么问题请指正!
技术栈&工具
- SpringBoot
- MyBatis
- Junit
- Mysql连接驱动以及数据库连接池(我这里用的是druid)
- lombok
- jwt
- fastjson
- http请求工具
- base64加密解密
- shiro依赖和缓存
登录流程
- 根据流程图的说明,首先是微信小程序的前端调用wx.login()接口获取到code值,然后前端使用wx.request()或者前端自己封装的请求,来调用后台自己写的登录接口(login),后台接收到前端传来的code值、用户非敏感信息:rawData,签名:signature(还可以获取其他更多的数据,具体看需求);
- 后台调用微信接口服务里面的jscode2session接口,官方文档有说明,详情可看官方文档,这个jscode2session接口会返回session_key和openid等值,一般是这两个值,unionid看满足条件返回
- 后端在接收到这两个值后,进行签名校验,需要用到前端传的signature
- 通过openid在数据库中查询该用户,若返回结果是空,则是新用户,如果返回结果不为空,则是老用户
- 调用IdWorker生成唯一skey,用于维护微信小程序用户与服务端的会话
- 将生成的skey和openid封装进token生成令牌传入前端
流程图
具体流程请参考微信小程序官方文档: 微信小程序官方API.
代码实现
一.pom文件配置可能会用到的一些依赖(dependencies)
笔者这里只是列出需要哪些依赖,具体的依赖版本大家可以去Maven中央仓库自行查询:Maven中央仓库.
<dependencies>
<!--SpringBoot起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 安全验证相关 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- Spring测试相关 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<!-- mysql连接驱动以及数据库连接池 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.spring.boot.version}</version>
</dependency>
<!-- PageHelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- 日志及lombok -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<optional>true</optional>
</dependency>
<!-- SpringConfiguration相关 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- 验证码所需工具 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- jwt相关 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- http请求工具包依赖 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
<!--base64加密解密-->
<!--shiro依赖和缓存-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
二.部分yml文件配置(application.yml)
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
username: 数据库账号
password: 数据库密码
url: jdbc:mysql://localhost:3306/wechat_applet?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
mybatis:
mapper-locations: classpath:mapping/*Dao.xml
type-aliases-package: com.tom.entity.pojo
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
jwt:
config:
key: SecretKey #服务端加密所使用的密文(自拟)
ttl: 21600000 #毫秒
三.工具类(Utils)
1. Http请求工具类(HttpClientUtil)
package com.tom.utils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author BeiChen
* @version 1.0
* @date 2021/4/7 13:03
*/
public class HttpClientUtil {
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
}
2. 微信工具类(WechatUtil)
package com.tom.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.codec.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author BeiChen
* @version 1.0
* @date 2021/4/7 12:59
*/
public class WechatUtil {
public static JSONObject getSessionKeyOrOpenId(String code) {
String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
Map<String, String> requestUrlParam = new HashMap<>();
// https://mp.weixin.qq.com/wxopen/devprofile?action=get_profile&token=164113089&lang=zh_CN
//小程序appId
requestUrlParam.put("appid", "自己的小程序appId");
//小程序secret
requestUrlParam.put("secret", "自己的小程序secret");
//小程序端返回的code
requestUrlParam.put("js_code", code);
//默认参数
requestUrlParam.put("grant_type", "authorization_code");
//发送post请求读取调用微信接口获取openid用户唯一标识
JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(requestUrl, requestUrlParam));
return jsonObject;
}
public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
// 被加密的数据
byte[] dataByte = Base64.decode(encryptedData);
// 加密秘钥
byte[] keyByte = Base64.decode(sessionKey);
// 偏移量
byte[] ivByte = Base64.decode(iv);
try {
// 如果密钥不足16位,那么就补足. 这个if 中的内容很重要
int base = 16;
if (keyByte.length % base != 0) {
int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
keyByte = temp;
}
// 初始化
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte));
// 初始化
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length > 0) {
String result = new String(resultByte, "UTF-8");
return JSON.parseObject(result);
}
} catch (Exception e) {
}
return null;
}
}
2. Token生成与解析工具类(JwtUtil)
package com.tom.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @Author Alfalfa99
* @Date 2020/9/13 15:54
* @Version 1.0
* JWT生成以及校验工具类
*/
@ConfigurationProperties("jwt.config")
@Component
public class JwtUtil {
private String key;
private long ttl;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public long getTtl() {
return ttl;
}
public void setTtl(long ttl) {
this.ttl = ttl;
}
/**
* 生成JWT
* @param skey
* @param openid
* @return
*/
public String createJWT(String skey, String openid) {
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
//在这里我们将用户的openid存入Jwt中,方便后续使用
JwtBuilder builder = Jwts.builder().setId(openid)
.setIssuedAt(now)
//在这里我们将用户的角色存入Jwt中,方便后续鉴权,如果想存别的内容也可以往里写
.signWith(SignatureAlgorithm.HS256, key).claim("skey", skey);
if (ttl > 0) {
builder.setExpiration(new Date(nowMillis + ttl));
}
return builder.compact();
}
/**
* 解析JWT
*
* @param jwtStr
* @return
*/
public Claims parseJWT(String jwtStr) {
return Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jwtStr)
.getBody();
}
}
2. 生成分布式自增id工具类(IdWorker)
package com.tom.utils;
import org.springframework.stereotype.Component;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
/**
* <p>名称:IdWorker.java</p>
* <p>描述:分布式自增长ID</p>
* <pre>
* Twitter的 Snowflake JAVA实现方案
* </pre>
* 核心代码为其IdWorker这个类实现,其原理结构如下,我分别用一个0表示一位,用—分割开部分的作用:
* 1||0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000
* 在上面的字符串中,第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间,
* 然后5位datacenter标识位,5位机器ID(并不算标识符,实际是为线程标识),
* 然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。
* 这样的好处是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和机器ID作区分),
* 并且效率较高,经测试,snowflake每秒能够产生26万ID左右,完全满足需要。
* <p>
* 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加))
*
* @author Polim
*/
@Component
public class IdWorker {
// 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
private final static long twepoch = 1288834974657L;
// 机器标识位数
private final static long workerIdBits = 5L;
// 数据中心标识位数
private final static long datacenterIdBits = 5L;
// 机器ID最大值
private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 数据中心ID最大值
private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
// 毫秒内自增位
private final static long sequenceBits = 12L;
// 机器ID偏左移12位
private final static long workerIdShift = sequenceBits;
// 数据中心ID左移17位
private final static long datacenterIdShift = sequenceBits + workerIdBits;
// 时间毫秒左移22位
private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
/* 上次生产id时间戳 */
private static long lastTimestamp = -1L;
// 0,并发控制
private long sequence = 0L;
private final long workerId;
// 数据标识id部分
private final long datacenterId;
public IdWorker(){
this.datacenterId = getDatacenterId(maxDatacenterId);
this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
}
/**
* @param workerId
* 工作机器ID
* @param datacenterId
* 序列号
*/
public IdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
/**
* 获取下一个ID
*
* @return
*/
public synchronized Long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
// 当前毫秒内,则+1
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
// 当前毫秒内计数满了,则等待下一秒
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
// ID偏移组合生成最终的ID,并返回ID
Long nextId = ((timestamp - twepoch) << timestampLeftShift)
| (datacenterId << datacenterIdShift)
| (workerId << workerIdShift) | sequence;
return nextId;
}
private long tilNextMillis(final long lastTimestamp) {
long timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
/**
* <p>
* 获取 maxWorkerId
* </p>
*/
protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
StringBuffer mpid = new StringBuffer();
mpid.append(datacenterId);
String name = ManagementFactory.getRuntimeMXBean().getName();
if (!name.isEmpty()) {
/*
* GET jvmPid
*/
mpid.append(name.split("@")[0]);
}
/*
* MAC + PID 的 hashcode 获取16个低位
*/
return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
}
/**
* <p>
* 数据标识id部分
* </p>
*/
protected static long getDatacenterId(long maxDatacenterId) {
long id = 0L;
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
id = 1L;
} else {
byte[] mac = network.getHardwareAddress();
id = ((0x000000FF & (long) mac[mac.length - 1])
| (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
id = id % (maxDatacenterId + 1);
}
} catch (Exception e) {
System.out.println(" getDatacenterId: " + e.getMessage());
}
return id;
}
}
2.时间戳生成类(DateTimeTransferUtil)
package com.tom.utils;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* @author Alfalfa99
* @version 1.0
* @date 2020/10/22 14:37
* 获取当前时间戳 <==> 获取当前标准时间
*/
@Component
public class DateTimeTransferUtil {
public static Long getNowTimeStamp(){
Long time = System.currentTimeMillis() / 1000;
return time;
}
public static String getFormatTime(){
String format = "yyyy-MM-dd HH:mm:ss";
return new SimpleDateFormat(format, Locale.CHINA).format(new Date());
}
public static String helpCreateFolds(){
return Calendar.getInstance().get(Calendar.YEAR) + "/" + (Calendar.getInstance().get(Calendar.MONTH)+1)+"/";
}
}
四.实体类(pojo)
用户(User)
package com.tom.entity.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author BeiChen
* @version 1.0
* @date 2021/4/8 19:20
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
/**
* openid
* skey
* 市
* 省
* 国
* 头像
* 性别
* 昵称
*最后登录时间
*创建时间
*/
private String open_id;
private String skey;
private String session_key;
private String city;
private String province;
private String country;
private String avatar_url;
private String gender;
private String nick_name;
private Long last_visit_time;
private Long create_time;
}
五.Controller层(UserController)
package com.tom.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tom.entity.bean.CommonResult;
import com.tom.entity.pojo.User;
import com.tom.service.Impl.UserServiceImpl;
import com.tom.utils.DateTimeTransferUtil;
import com.tom.utils.IdWorker;
import com.tom.utils.JwtUtil;
import com.tom.utils.WechatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author BeiChen
* @version 1.0
* @date 2021/4/7 13:10
*/
@RestController
public class UserController {
@Autowired
private final UserServiceImpl userService;
private final IdWorker idWorker;
private final JwtUtil jwtUtil;
public UserController(UserServiceImpl userService, IdWorker idWorker, JwtUtil jwtUtil) {
this.userService = userService;
this.idWorker = idWorker;
this.jwtUtil = jwtUtil;
}
/**
* 用户登录
* @param
* @return
*/
@PostMapping("/login")
public CommonResult<String> login(@RequestParam String code,
@RequestParam String rawData,
@RequestParam String signature) {
// 用户非敏感信息:rawData
// 签名:signature
JSONObject rawDataJson = JSON.parseObject(rawData);
// 1.接收小程序发送的code
// 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
String openid = SessionKeyOpenId.getString("openid");
String sessionKey = SessionKeyOpenId.getString("session_key");
// 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
if (!signature.equals(signature2)) {
return new CommonResult<>(500, "NO",null);
}
// 5.根据返回的User实体类,判断用户是否是新用户,是的话,将用户信息存到数据库;不是的话,更新最新登录时间
User user =userService.queryUserById(openid);
System.out.println(user);
// IDworker生成唯一key,用于维护微信小程序用户与服务端的会话
String skey = idWorker.nextId().toString();
System.out.println("skey===>"+skey);
if(user==null){
//是新用户则将信息存入
User newUser=new User();
newUser.setOpen_id(openid);
newUser.setSkey(skey);
newUser.setCreate_time(DateTimeTransferUtil.getNowTimeStamp());
newUser.setLast_visit_time(DateTimeTransferUtil.getNowTimeStamp());
newUser.setSession_key(sessionKey);
newUser.setCity(rawDataJson.getString("city"));
newUser.setCountry(rawDataJson.getString("country"));
newUser.setProvince(rawDataJson.getString("province"));
newUser.setGender(rawDataJson.getString("gender"));
newUser.setAvatar_url(rawDataJson.getString("avatarUrl"));
newUser.setNick_name(rawDataJson.getString("nickName"));
userService.addUser(newUser);
}
else{
//老用户,更新登陆时间
user.setLast_visit_time(DateTimeTransferUtil.getNowTimeStamp());
//重置会话skey
user.setSkey(skey);
userService.updateUser(user);
}
//使用token生成工具,生成带有openid和skey的token
String token = jwtUtil.createJWT(skey, openid);
return new CommonResult<>(200, "OK",token);
}
}
六.Service层(UserServiceImpl)
package com.tom.service.Impl;
import com.tom.dao.UserDao;
import com.tom.entity.pojo.User;
import com.tom.service.UserService;
import com.tom.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author BeiChen
* @version 1.0
* @date 2021/4/8 11:40
*/
@Component
@Transactional(rollbackForClassName = "Exception.class")
public class UserServiceImpl implements UserService {
private final UserDao userDao;
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
@Override
public User queryUserById(String openid) {
User user = userDao.queryUserById("openid");
return user;
}
/**
* 添加新用户
* @param user
* @return
*/
@Override
public int addUser(User user) {
return userDao.addUser(user);
}
/**
* 更新用户信息
* @param user
* @return
*/
@Override
public int updateUser(User user) {
return userDao.updateUser(user);
}
}
七.Dao层(UserDao)
package com.tom.dao;
import com.tom.entity.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
* @author BeiChen
* @version 1.0
* @date 2021/4/8 23:43
*/
@Repository
public interface UserDao {
/**
* 添加用户
* @param user
* @return
*/
int addUser(User user);
/**
* 通过openid查找用户
* @param openid
* @return
*/
User queryUserById(@Param("openid") String openid);
/**
* 更新用户信息
* @param user
* @return
*/
int updateUser(User user);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tom.dao.UserDao">
<insert id="addUser" parameterType="User">
insert into user1 (open_id,city,province,country,avatar_url,gender,nick_name,last_visit_time,create_time)
value (#{open_id},#{city},#{province},#{country},#{avatar_url},#{gender},#{nick_name},#{last_visit_time},#{create_time});
</insert>
<select id="queryUserById" resultType="User">
select * from user1
where open_id=#{openid}
</select>
<update id="updateUser" parameterType="User" >
update user1
set open_id = #{open_id},skey = #{skey},session_key=#{session_key},city=#{city},province=#{province},country=#{country},avatar_url=#{avatar_url},gender=#{gender},nick_name=#{nick_name},create_time=#{create_time},last_visit_time=#{last_visit_time}
where open_id=#{open_id};
</update>
</mapper>
八.Token拦截器及其配置类(TokenInterceptor&InterceptorConfig)
package com.tom.interceptor;
import com.tom.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class TokenInterceptor implements HandlerInterceptor {
private final JwtUtil jwtUtil;
public TokenInterceptor(JwtUtil jwtUtil) {
this.jwtUtil = jwtUtil;
}
/**
* 通过拦截器对请求头进行校验
*
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String header = request.getHeader("Authorization");
if (header != null && !"".equals(header)) {
if (header.startsWith("Bearer ")) {
//获得token
String token = header.substring(7);
//验证token
try {
Claims claims = jwtUtil.parseJWT(token);
String skey = (String) claims.get("skey");
if (skey != null) {
request.setAttribute("openid",claims.getId());
request.setAttribute("skey",skey);
return true;
} else {
throw new BadCredentialsException("令牌已失效");
}
} catch (Exception e) {
throw new BadCredentialsException("令牌已失效");
}
}
}
throw new AuthenticationCredentialsNotFoundException("请先登录");
}
}
package com.tom.config;
import com.tom.interceptor.TokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @author Alfalfa99
* @date 2020/9/13
* 拦截器配置类
*/
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
private final TokenInterceptor tokenInterceptor;
public InterceptorConfig(TokenInterceptor tokenInterceptor) {
this.tokenInterceptor = tokenInterceptor;
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
//拦截所有目录,除了通向login和register的接口
registry.addInterceptor(tokenInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/**/login/**", "/**/register/**")
.excludePathPatterns("/**/*.html", "/**/*.js", "/**/*.css");
}
}
九.全局异常处理类(GlobalException&BasicException)
package com.tom.exception;
import com.tom.entity.bean.CommonResult;
import lombok.extern.log4j.Log4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import java.util.List;
/**
* @author Alfalfa99
* @version 1.0
* @date 2020/10/22 18:10
* 全局异常处理类
*/
@RestControllerAdvice
@Log4j
public class GlobalException {
/**
* 捕获所有(Exception.class)中的异常并通过下面的方法返回
*
* @param e 错误类型
* @return 给前端返回报错信息
*/
@ExceptionHandler(value = Exception.class)
public CommonResult<String> toHandleUnexpectException(Exception e) {
e.printStackTrace();
return new CommonResult<>(500,"Error","出现了预料外的错误请联系管理员!:"+ e.getMessage());
}
@ExceptionHandler(value = BasicException.class)
public CommonResult<String> toHandleException(Exception e) {
e.printStackTrace();
return new CommonResult<>(500,"Error",e.getMessage());
}
@ExceptionHandler(value = MaxUploadSizeExceededException.class)
public CommonResult<String> uploadException(Exception e) {
e.printStackTrace();
return new CommonResult<>(500,"Error","文件体积过大");
}
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public CommonResult<String> validException(MethodArgumentNotValidException e){
BindingResult result = e.getBindingResult();
if (result.hasErrors()) {
List<ObjectError> errors = result.getAllErrors();
if (!errors.isEmpty()) {
// 这里列出了全部错误参数,按正常逻辑,只需要第一条错误即可
FieldError fieldError = (FieldError) errors.get(0);
return new CommonResult<>(500, "Error", fieldError.getDefaultMessage());
}
}
return new CommonResult<>(500, "Error", "参数验证错误");
}
@ExceptionHandler(value = AccessDeniedException.class)
public CommonResult<String> accessDeniedException(){
return new CommonResult<>(401, "Error", "请先登录");
}
@ExceptionHandler(value = AuthorizationServiceException.class)
public CommonResult<String> unAuthorization(){
return new CommonResult<>(403, "Error", "权限不足");
}
}
package com.tom.exception;
/**
* @author Alfalfa99
* @version 1.0
* @date 2020/11/1 15:24
* 基础异常
*/
public class BasicException extends RuntimeException {
public BasicException() {
}
public BasicException(String message) {
super(message);
}
public BasicException(String message, Throwable cause) {
super(message, cause);
}
public BasicException(Throwable cause) {
super(cause);
}
public BasicException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
整体的框架:
到这里登录的代码就结束了,这里显示的是后端代码,笔者也是第一次开发小程序后台,对微信小程序不太熟悉,如果有什么问题请指正!
最后
以上就是爱听歌红酒为你收集整理的SpringBoot实现微信小程序后台登录技术栈&工具代码实现整体的框架:的全部内容,希望文章能够帮你解决SpringBoot实现微信小程序后台登录技术栈&工具代码实现整体的框架:所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复