Implement token to verify whether users are logged in based on redis
Based on the project requirements, we want to implement a redis-based token login authentication, how to achieve it:
Backend implementation:
1. Introduce redis-related dependencies
Org.springframework.boot spring-boot-starter-data-redis org.springframework.session spring-session-data-redis 2.0.5.RELEASE
The 2.Controller layer generates token information and stores it in redis.
/ / if the login verification is successful, the corresponding login information and login credentials will be stored in redis / / generate login credentials token UUIDString uuidToken= UUID.randomUUID (). ToString (); uuidToken=uuidToken.replace ("-", "); / / establish a connection between token and user login status redisTemplate.opsForValue (). Set (uuidToken,userModel); redisTemplate.expire (uuidToken,1, TimeUnit.HOURS); / / issue tokenreturn CommonReturnType.create (uuidToken)
3. You can call the login place that needs to be verified.
String token = httpServletRequest.getParameterMap (). Get ("token") [0]; if (StringUtils.isEmpty (token)) {throw new BusinessException (EmBusinessError.USER_NOT_LOGIN, "the user has not logged in yet and cannot place an order");} / / obtain the user's login information UserModel userModel= (UserModel) redisTemplate.opsForValue (). Get (token); if (userModel==null) {throw new BusinessException (EmBusinessError.USER_NOT_LOGIN, "user has not logged in yet and cannot place an order") } OrderModel orderModel = orderService.creatOrder (userModel.getId (), itemId, promoId, amount); return CommonReturnType.create (null)
Front-end implementation
1. Take out the token from the return value and save it to localstorage
If (data.status = = "success") {alert ("login succeeded"); / / take out the token and put it in localstorage var token = data.data; window.localStorage ["token"] = token; _ window.location.href = "listitem.html";}
two。 Verify whether the user is logged in
Var token = window.localStorage ["token"]; if (token = = null) {alert ("not logged in, order cannot be placed"); _ window.location.href= "login.html" rel= "external nofollow"; return false;}
3. Of course, you need to pass the token to the backend and verify it again.
Url: "http://"+g_host+"/order/createorder?token="+token,
The above is the whole content of this article, I hope it will be helpful to your study, and I also hope that you will support it.