欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于redis的小程序登录实现方法流程分析

程序员文章站 2022-04-09 16:59:29
这张图是小程序的登录流程解析:小程序登陆授权流程:在小程序端调用wx.login()获取code,由于我是做后端开发的这边不做赘述,直接贴上代码了.有兴趣的直接去官方文档看下,链接放这里: wx.lo...

这张图是小程序的登录流程解析:

基于redis的小程序登录实现方法流程分析

小程序登陆授权流程:

在小程序端调用wx.login()获取code,由于我是做后端开发的这边不做赘述,直接贴上代码了.有兴趣的直接去官方文档看下,链接放这里:

wx.login({
 success (res) {
 if (res.code) {
 //发起网络请求
 wx.request({
 url: 'https://test.com/onlogin',
 data: {
 code: res.code
 }
 })
 } else {
 console.log('登录失败!' + res.errmsg)
 }
 }
})

小程序前端登录后会获取code,调用自己的开发者服务接口,调用个get请求:

get https://api.weixin.qq.com/sns/jscode2session?appid=appid&secret=secret&js_code=jscode&grant_type=authorization_code

需要得四个参数:
appid:小程序appid
secret: 小程序密钥
js_code: 刚才获取的code
grant_type:‘authorization_code' //这个是固定的

如果不出意外的话,微信接口服务器会返回四个参数:

基于redis的小程序登录实现方法流程分析

详情可以看下官方文档:jscode2session

下面附上我的代码:

@authignore
 @requestmapping("/login")
 @responsebody
 public responsebean openid(@requestparam(value = "code", required = true) string code,
  @requestparam(value = "avatarurl") string avatarurl,
  @requestparam(value = "city") string city,
  @requestparam(value = "country") string country,
  @requestparam(value = "gender") string gender,
  @requestparam(value = "language") string language,
  @requestparam(value = "nickname") string nickname,
  @requestparam(value = "province") string province,
  httpservletrequest request) { // 小程序端获取的code
 responsebean responsebean = new responsebean();
 try {
 boolean check = (stringutils.isempty(code)) ? true : false;
 if (check) {
 responsebean = new responsebean(false, unicomresponseenums.no_code);
 return responsebean;
 }
 //将获取的用户数据存入数据库;
 map<string, object> msgs = new hashmap<>();
 msgs.put("appid", appid);
 msgs.put("secret", secret);
 msgs.put("js_code", code);
 msgs.put("grant_type", "authorization_code");
 // java的网络请求,返回字符串
 string data = httputils.get(msgs, constants.jscode2session);
 logger.info("======> " + data);
 string openid = jsonobject.parseobject(data).getstring("openid");
 string session_key = jsonobject.parseobject(data).getstring("session_key");
 string unionid = jsonobject.parseobject(data).getstring("unionid");
 string errcode = jsonobject.parseobject(data).getstring("errcode");
 string errmsg = jsonobject.parseobject(data).getstring("errmsg");

 jsonobject json = new jsonobject();
 int userid = -1;

 if (!stringutils.isblank(openid)) {
 users user = userservice.selectuserbyopenid(openid);
 if (user == null) {
  //新建一个用户信息
  users newuser = new users();
  newuser.setopenid(openid);
  newuser.setarea(city);
  newuser.setsex(integer.parseint(gender));
  newuser.setnickname(nickname);
  newuser.setcreatetime(new date());
  newuser.setstatus(0);//初始
  if (!stringutils.isblank(unionid)) {
  newuser.setunionid(unionid);
  }
  userservice.instert(newuser);
  userid = newuser.getid();
 } else {
  userid = user.getid();
 }
 json.put("userid", userid);
 }
 if (!stringutils.isblank(session_key) && !stringutils.isblank(openid)) {
 //这段可不用redis存,直接返回session_key也可以
 string useragent = request.getheader("user-agent");
 string sessionid = tokenservice.generatetoken(useragent, session_key);
 //将session_key存入redis
 redisutil.setex(sessionid, session_key + "###" + userid, constants.session_key_ex);
 json.put("token", sessionid);

 responsebean = new responsebean(true, json);
 } else {
 responsebean = new responsebean<>(false, null, errmsg);
 }
 return responsebean;
 } catch (exception e) {
 e.printstacktrace();
 responsebean = new responsebean(false, unicomresponseenums.jscode2session_erro);
 return responsebean;
 }
 }

解析:

这边我的登录获取的session_key出于安全性考虑没有直接在前端传输,而是存到了redis里面给到前端session_key的token传输,
而且session_key的销毁时间是20分钟,时间内可以重复获取用户数据.
如果只是简单使用或者对安全性要求不严的话可以直接传session_key到前端保存.

session_key的作用:

校验用户信息(wx.getuserinfo(object)返回的signature);
解密(wx.getuserinfo(object)返回的encrypteddata);

按照官方的说法,wx.checksession是用来检查 wx.login(object) 的时效性,判断登录是否过期;
疑惑的是(openid,unionid )都是用户唯一标识,不会因为wx.login(object)的过期而改变,所以要是没有使用wx.getuserinfo(object)获得的用户信息,确实没必要使用wx.checksession()来检查wx.login(object) 是否过期;
如果使用了wx.getuserinfo(object)获得的用户信息,还是有必要使用wx.checksession()来检查wx.login(object) 是否过期的,因为用户有可能修改了头像、昵称、城市,省份等信息,可以通过检查wx.login(object) 是否过期来更新着些信息;

小程序的登录状态维护本质就是维护session_key的时效性

这边附上我的httputils工具代码,如果只要用get的话可以复制部分:

如果是直

/**
 * httputils工具类
 *
 * @author
 */
public class httputils {
 /**
 * 请求方式:post
 */
 public static string post = "post";
 /**
 * 编码格式:utf-8
 */
 private static final string charset_utf_8 = "utf-8";
 /**
 * 报文头部json
 */
 private static final string application_json = "application/json";
 /**
 * 请求超时时间
 */
 private static final int connect_timeout = 60 * 1000;
 /**
 * 传输超时时间
 */
 private static final int so_timeout = 60 * 1000;
 /**
 * 日志
 */
 private static final logger logger = loggerfactory.getlogger(httputils.class);
 /**
 * @param protocol
 * @param url
 * @param paramap
 * @return
 * @throws exception
 */
 public static string dopost(string protocol, string url,
  map<string, object> paramap) throws exception {
 closeablehttpclient httpclient = null;
 closeablehttpresponse resp = null;
 string rtnvalue = null;
 try {
 if (protocol.equals("http")) {
 httpclient = httpclients.createdefault();
 } else {
 // 获取https安全客户端
 httpclient = httputils.gethttpsclient();
 }
 httppost httppost = new httppost(url);
 list<namevaluepair> list = msgs2valuepairs(paramap);
// list<namevaluepair> list = new arraylist<namevaluepair>();
// if (null != paramap &&paramap.size() > 0) {
// for (entry<string, object> entry : paramap.entryset()) {
//  list.add(new basicnamevaluepair(entry.getkey(), entry
//  .getvalue().tostring()));
// }
// }
 requestconfig requestconfig = requestconfig.custom()
  .setsockettimeout(so_timeout)
  .setconnecttimeout(connect_timeout).build();// 设置请求和传输超时时间
 httppost.setconfig(requestconfig);
 httppost.setentity(new urlencodedformentity(list, charset_utf_8));
 resp = httpclient.execute(httppost);
 rtnvalue = entityutils.tostring(resp.getentity(), charset_utf_8);
 } catch (exception e) {
 logger.error(e.getmessage());
 throw e;
 } finally {
 if (null != resp) {
 resp.close();
 }
 if (null != httpclient) {
 httpclient.close();
 }
 }
 return rtnvalue;
 }
 /**
 * 获取https,单向验证
 *
 * @return
 * @throws exception
 */
 public static closeablehttpclient gethttpsclient() throws exception {
 try {
 trustmanager[] trustmanagers = new trustmanager[]{new x509trustmanager() {
 public void checkclienttrusted(
  x509certificate[] paramarrayofx509certificate,
  string paramstring) throws certificateexception {
 }
 public void checkservertrusted(
  x509certificate[] paramarrayofx509certificate,
  string paramstring) throws certificateexception {
 }
 public x509certificate[] getacceptedissuers() {
  return null;
 }
 }};
 sslcontext sslcontext = sslcontext
  .getinstance(sslconnectionsocketfactory.tls);
 sslcontext.init(new keymanager[0], trustmanagers,
  new securerandom());
 sslcontext.setdefault(sslcontext);
 sslcontext.init(null, trustmanagers, null);
 sslconnectionsocketfactory connectionsocketfactory = new sslconnectionsocketfactory(
  sslcontext,
  sslconnectionsocketfactory.allow_all_hostname_verifier);
 httpclientbuilder clientbuilder = httpclients.custom()
  .setsslsocketfactory(connectionsocketfactory);
 clientbuilder.setredirectstrategy(new laxredirectstrategy());
 closeablehttpclient httpclient = clientbuilder.build();
 return httpclient;
 } catch (exception e) {
 throw new exception("http client 远程连接失败", e);
 }
 }
 /**
 * post请求
 *
 * @param msgs
 * @param url
 * @return
 * @throws clientprotocolexception
 * @throws unknownhostexception
 * @throws ioexception
 */
 public static string post(map<string, object> msgs, string url)
 throws clientprotocolexception, unknownhostexception, ioexception {
 closeablehttpclient httpclient = httpclients.createdefault();
 try {
 httppost request = new httppost(url);
 list<namevaluepair> valuepairs = msgs2valuepairs(msgs);
// list<namevaluepair> valuepairs = new arraylist<namevaluepair>();
// if (null != msgs) {
// for (entry<string, object> entry : msgs.entryset()) {
//  if (entry.getvalue() != null) {
//  valuepairs.add(new basicnamevaluepair(entry.getkey(),
//  entry.getvalue().tostring()));
//  }
// }
// }
 request.setentity(new urlencodedformentity(valuepairs, charset_utf_8));
 closeablehttpresponse resp = httpclient.execute(request);
 return entityutils.tostring(resp.getentity(), charset_utf_8);
 } finally {
 httpclient.close();
 }
 }
 /**
 * post请求
 *
 * @param msgs
 * @param url
 * @return
 * @throws clientprotocolexception
 * @throws unknownhostexception
 * @throws ioexception
 */
 public static byte[] postgetbyte(map<string, object> msgs, string url)
 throws clientprotocolexception, unknownhostexception, ioexception {
 closeablehttpclient httpclient = httpclients.createdefault();
 inputstream inputstream = null;
 byte[] data = null;
 try {
 httppost request = new httppost(url);
 list<namevaluepair> valuepairs = msgs2valuepairs(msgs);
// list<namevaluepair> valuepairs = new arraylist<namevaluepair>();
// if (null != msgs) {
// for (entry<string, object> entry : msgs.entryset()) {
//  if (entry.getvalue() != null) {
//  valuepairs.add(new basicnamevaluepair(entry.getkey(),
//  entry.getvalue().tostring()));
//  }
// }
// }
 request.setentity(new urlencodedformentity(valuepairs, charset_utf_8));
 closeablehttpresponse response = httpclient.execute(request);
 try {
 // 获取相应实体
 httpentity entity = response.getentity();
 if (entity != null) {
  inputstream = entity.getcontent();
  data = readinputstream(inputstream);
 }
 return data;
 } catch (exception e) {
 e.printstacktrace();
 } finally {
 httpclient.close();
 return null;
 }
 } finally {
 httpclient.close();
 }
 }
 /** 将流 保存为数据数组
 * @param instream
 * @return
 * @throws exception
 */
 public static byte[] readinputstream(inputstream instream) throws exception {
 bytearrayoutputstream outstream = new bytearrayoutputstream();
 // 创建一个buffer字符串
 byte[] buffer = new byte[1024];
 // 每次读取的字符串长度,如果为-1,代表全部读取完毕
 int len = 0;
 // 使用一个输入流从buffer里把数据读取出来
 while ((len = instream.read(buffer)) != -1) {
 // 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
 outstream.write(buffer, 0, len);
 }
 // 关闭输入流
 instream.close();
 // 把outstream里的数据写入内存
 return outstream.tobytearray();
 }
 /**
 * get请求
 *
 * @param msgs
 * @param url
 * @return
 * @throws clientprotocolexception
 * @throws unknownhostexception
 * @throws ioexception
 */
 public static string get(map<string, object> msgs, string url)
 throws clientprotocolexception, unknownhostexception, ioexception {
 closeablehttpclient httpclient = httpclients.createdefault();
 try {
 list<namevaluepair> valuepairs = msgs2valuepairs(msgs);
// list<namevaluepair> valuepairs = new arraylist<namevaluepair>();
// if (null != msgs) {
// for (entry<string, object> entry : msgs.entryset()) {
//  if (entry.getvalue() != null) {
//  valuepairs.add(new basicnamevaluepair(entry.getkey(),
//  entry.getvalue().tostring()));
//  }
// }
// }
 // entityutils.tostring(new urlencodedformentity(valuepairs),
 // charset);
 url = url + "?" + urlencodedutils.format(valuepairs, charset_utf_8);
 httpget request = new httpget(url);
 closeablehttpresponse resp = httpclient.execute(request);
 return entityutils.tostring(resp.getentity(), charset_utf_8);
 } finally {
 httpclient.close();
 }
 }
 public static <t> t post(map<string, object> msgs, string url,
  class<t> clazz) throws clientprotocolexception,
 unknownhostexception, ioexception {
 string json = httputils.post(msgs, url);
 t t = json.parseobject(json, clazz);
 return t;
 }
 public static <t> t get(map<string, object> msgs, string url, class<t> clazz)
 throws clientprotocolexception, unknownhostexception, ioexception {
 string json = httputils.get(msgs, url);
 t t = json.parseobject(json, clazz);
 return t;
 }
 public static string postwithjson(map<string, object> msgs, string url)
 throws clientprotocolexception, ioexception {
 closeablehttpclient httpclient = httpclients.createdefault();
 try {
 string jsonparam = json.tojsonstring(msgs);
 httppost post = new httppost(url);
 post.setheader("content-type", application_json);
 post.setentity(new stringentity(jsonparam, charset_utf_8));
 closeablehttpresponse response = httpclient.execute(post);
 return new string(entityutils.tostring(response.getentity()).getbytes("iso8859-1"), charset_utf_8);
 } finally {
 httpclient.close();
 }
 }
 public static <t> t postwithjson(map<string, object> msgs, string url, class<t> clazz) throws clientprotocolexception,
 unknownhostexception, ioexception {
 string json = httputils.postwithjson(msgs, url);
 t t = json.parseobject(json, clazz);
 return t;
 }
 public static list<namevaluepair> msgs2valuepairs(map<string, object> msgs) {
 list<namevaluepair> valuepairs = new arraylist<namevaluepair>();
 if (null != msgs) {
 for (entry<string, object> entry : msgs.entryset()) {
 if (entry.getvalue() != null) {
  valuepairs.add(new basicnamevaluepair(entry.getkey(),
  entry.getvalue().tostring()));
 }
 }
 }
 return valuepairs;
 }
}

接传session_key到前端的,下面的可以不用看了.
如果是redis存的sesssion_key的token的话,这边附上登陆的时候的token转换为session_key.

自定义拦截器注解:

import java.lang.annotation.*;
@target({elementtype.method,elementtype.type})
@retention(retentionpolicy.runtime)
@documented
public @interface authignore {
}

拦截器部分代码:

 @override
 public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception {
 authignore annotation;
 if(handler instanceof handlermethod) {
 annotation = ((handlermethod) handler).getmethodannotation(authignore.class);
 }else{
 return true;
 }
 //如果有@authignore注解,则不验证token
 if(annotation != null){
 return true;
 }
// //获取微信access_token;
// if(!redisutil.exists(constants.access_token)){
// map<string, object> msgs = new hashmap<>();
// msgs.put("appid",appid);
// msgs.put("secret",secret);
// msgs.put("grant_type","client_credential");
// string data = httputils.get(msgs,constants.getaccesstoken); // java的网络请求,返回字符串
// string errcode= jsonobject.parseobject(data).getstring("errcode");
// string errmsg= jsonobject.parseobject(data).getstring("errmsg");
// if(stringutils.isblank(errcode)){
// //存储access_token
// string access_token= jsonobject.parseobject(data).getstring("access_token");
// long expires_in=long.parselong(jsonobject.parseobject(data).getstring("expires_in"));
// redisutil.setex("access_token",access_token, expires_in);
// }else{
// //异常返回数据拦截,返回json数据
// response.setcharacterencoding("utf-8");
// response.setcontenttype("application/json; charset=utf-8");
// printwriter out = response.getwriter();
// responsebean<object> responsebean=new responsebean<>(false,null, errmsg);
// out = response.getwriter();
// out.append(json.tojson(responsebean).tostring());
// return false;
// }
// }
 //获取用户凭证
 string token = request.getheader(constants.user_token);
// if(stringutils.isblank(token)){
// token = request.getparameter(constants.user_token);
// }
// if(stringutils.isblank(token)){
// object obj = request.getattribute(constants.user_token);
// if(null!=obj){
// token=obj.tostring();
// }
// }
// //token凭证为空
// if(stringutils.isblank(token)){
// //token不存在拦截,返回json数据
// response.setcharacterencoding("utf-8");
// response.setcontenttype("application/json; charset=utf-8");
// printwriter out = response.getwriter();
// try{
// responsebean<object> responsebean=new responsebean<>(false,null, unicomresponseenums.token_empty);
// out = response.getwriter();
// out.append(json.tojson(responsebean).tostring());
// return false;
// }
// catch (exception e) {
// e.printstacktrace();
// response.senderror(500);
// return false;
// }
// }
 if(token==null||!redisutil.exists(token)){
 //用户未登录,返回json数据
 response.setcharacterencoding("utf-8");
 response.setcontenttype("application/json; charset=utf-8");
 printwriter out = response.getwriter();
 try{
 responsebean<object> responsebean=new responsebean<>(false,null, unicomresponseenums.dis_login);
 out = response.getwriter();
 out.append(json.tojson(responsebean).tostring());
 return false;
 }
 catch (exception e) {
 e.printstacktrace();
 response.senderror(500);
 return false;
 }
 }
 tokenmanager.refreshusertoken(token);
 return true;
 }
}

过滤器配置:

@configuration
public class interceptorconfig extends webmvcconfigureradapter {
 @override
 public void addinterceptors(interceptorregistry registry) {
 registry.addinterceptor(authorizationinterceptor())
 .addpathpatterns("/**")// 拦截所有请求,通过判断是否有 @authignore注解 决定是否需要登录
 .excludepathpatterns("/user/login");//排除登录
 }
 @bean
 public authorizationinterceptor authorizationinterceptor() {
 return new authorizationinterceptor();
 }
}

token管理:

@service
public class tokenmanager {
 @resource
 private redisutil redisutil;
 //生成token(格式为token:设备-加密的用户名-时间-六位随机数)
 public string generatetoken(string useragentstr, string username) {
 stringbuilder token = new stringbuilder("token:");
 //设备
 useragent useragent = useragent.parseuseragentstring(useragentstr);
 if (useragent.getoperatingsystem().ismobiledevice()) {
 token.append("mobile-");
 } else {
 token.append("pc-");
 }
 //加密的用户名
 token.append(md5utils.md5encode(username) + "-");
 //时间
 token.append(new simpledateformat("yyyymmddhhmmsssss").format(new date()) + "-");
 //六位随机字符串
 token.append(uuid.randomuuid().tostring());
 system.out.println("token-->" + token.tostring());
 return token.tostring();
 }
 /**
 * 登录用户,创建token
 *
 * @param token
 */
 //把token存到redis中
 public void save(string token, users user) {
 if (token.startswith("token:pc")) {
 redisutil.setex(token,json.tojsonstring(user), constants.token_ex);
 } else {
 redisutil.setex(token,json.tojsonstring(user), constants.token_ex);
 }
 }
 /**
 * 刷新用户
 *
 * @param token
 */
 public void refreshusertoken(string token) {
 if (redisutil.exists(token)) {
 string value=redisutil.get(token);
 redisutil.setex(token, value, constants.token_ex);
 }
 }
 /**
 * 用户退出登陆
 *
 * @param token
 */
 public void loginout(string token) {
 redisutil.remove(token);
 }
 /**
 * 获取用户信息
 *
 * @param token
 * @return
 */
 public users getuserinfobytoken(string token) {
 if (redisutil.exists(token)) {
 string jsonstring = redisutil.get(token);
 users user =jsonobject.parseobject(jsonstring, users.class);
 return user;
 }
 return null;
 }
}

redis工具类:

@component
public class redisutil {
 @resource
 private redistemplate<string, string> redistemplate;
 public void set(string key, string value) {
 valueoperations<string, string> valueoperations = redistemplate.opsforvalue();
 valueoperations.set(key, value);
 }
 public void setex(string key, string value, long seconds) {
 valueoperations<string, string> valueoperations = redistemplate.opsforvalue();
 valueoperations.set(key, value, seconds,timeunit.seconds);
 }
 public boolean exists(string key) {
 return redistemplate.haskey(key);
 }
 public void remove(string key) {
 redistemplate.delete(key);
 }
 public string get(string key) {
 valueoperations<string, string> valueoperations = redistemplate.opsforvalue();
 return valueoperations.get(key);
 }
}

最后redis要实现序列化,序列化最终的目的是为了对象可以跨平台存储,和进行网络传输。而我们进行跨平台存储和网络传输的方式就是io,而我们的io支持的数据格式就是字节数组。本质上存储和网络传输 都需要经过 把一个对象状态保存成一种跨平台识别的字节格式,然后其他的平台才可以通过字节信息解析还原对象信息。

@configuration
@conditionalonclass(redisoperations.class)
@enableconfigurationproperties(redisproperties.class)
public class redisconfig {
 @bean
 @conditionalonmissingbean(name = "redistemplate")
 public redistemplate<object, object> redistemplate(
 redisconnectionfactory redisconnectionfactory) {
 redistemplate<object, object> template = new redistemplate<>();
 //使用fastjson序列化
 fastjsonredisserializer fastjsonredisserializer = new fastjsonredisserializer(object.class);
 // value值的序列化采用fastjsonredisserializer
 template.setvalueserializer(fastjsonredisserializer);
 template.sethashvalueserializer(fastjsonredisserializer);
 // key的序列化采用stringredisserializer
 template.setkeyserializer(new stringredisserializer());
 template.sethashkeyserializer(new stringredisserializer());
 template.setconnectionfactory(redisconnectionfactory);
 return template;
 }
 @bean
 @conditionalonmissingbean(stringredistemplate.class)
 public stringredistemplate stringredistemplate(
 redisconnectionfactory redisconnectionfactory) {
 stringredistemplate template = new stringredistemplate();
 template.setconnectionfactory(redisconnectionfactory);
 return template;
 }
}

作者:gigass
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

总结

到此这篇关于基于redis的小程序登录实现的文章就介绍到这了,更多相关redis小程序登录内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!