基于redis实现token验证用户是否登陆
基于项目需求, 我们要实现一个基于redis实现token登录验证,该如何实现呢:
后端实现:
1.引入redis相关的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>2.0.5.RELEASE</version> </dependency>
2.Controller层生成token信息并存入redis中
//若用户登录验证成功后将对应的登陆信息和登陆凭证一起存入redis中 //生成登陆凭证token UUID String uuidToken= UUID.randomUUID().toString(); uuidToken=uuidToken.replace("-",""); //将token和用户登录态之间建立联系 redisTemplate.opsForValue().set(uuidToken,userModel); redisTemplate.expire(uuidToken,1, TimeUnit.HOURS); // 下发token return CommonReturnType.create(uuidToken);
3.需要验证的登陆的地方调用即可
String token = httpServletRequest.getParameterMap().get("token")[0]; if (StringUtils.isEmpty(token)) { throw new BusinessException(EmBusinessError.USER_NOT_LOGIN, "用户还未登陆,不能下单"); } //获取用户的登陆信息 UserModel userModel= (UserModel) redisTemplate.opsForValue().get(token); if(userModel==null){ throw new BusinessException(EmBusinessError.USER_NOT_LOGIN, "用户还未登陆,不能下单"); } OrderModel orderModel = orderService.creatOrder(userModel.getId(), itemId, promoId, amount); return CommonReturnType.create(null);
前端实现
1.从返回值中取出token并存入localstorage
if(data.status == "success") { alert("登陆成功"); //取出token放入localstorage var token = data.data; window.localStorage["token"] = token; window.location.href = "listitem.html"; }
2.验证用户是否登陆
var token = window.localStorage["token"]; if(token == null){ alert("没有登录,不能下单"); window.location.href="login.html" rel="external nofollow" ; return false; }
3.当然,需要把token传入后端再校验一次
url:"http://"+g_host+"/order/createorder?token="+token,
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持安科网。
相关推荐
qidiantianxia 2020-10-21
kiven 2020-09-11
wolfjin 2020-09-10
HMHYY 2020-06-28
苦咖啡flask 2020-06-18
playis 2020-06-16
xuanwenchao 2020-06-14
sqliang 2020-06-14
TesterJingel 2020-06-10
RocketJ 2020-06-09
powderhose 2020-06-08
rongxionga 2020-06-08
Burgesszheng 2020-06-07
huangyx 2020-05-29
RuoShangM 2020-05-14
数据库之扑朔迷离 2020-05-06