token鉴权思路
1.用户注册的时候生成token,这个token可以是任意的一串字符保证全局唯一即可,实例中用的是UUID,做测试基本也够用了
2.生成出来的token保存到Redis缓存中(实际项目中,缓存和数据库个保存一份避免数据丢失),这里要设置缓存持久化以免服务器或服务宕机,用户token丢失
3.当用户拿着token登录时,我们首先需要在缓存中去验证这个token是否存在,当token存在并且数据中有次用户信息即可登录成功,否则登录失败,当这个token在缓存中存在数据库用户不存在这也不行也不能登录,需要把缓存删除掉保持与数据库一致
package com.example.demo.controller;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.redis.RedisUtil;
import com.example.demo.redis.UserTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* Created with IntelliJ IDEA.
*
* @Auther: ljt
* @Version 1.0
* @Date: 2020/05/07/15:30
* @Description:
*/
@RestController
@RequestMapping("/user")
public class UserApiController {
@Autowired
private RedisUtil redisUtil;
//查询所有注册信息
@RequestMapping("/getInfo")
public Object userInfo(){
return redisUtil.hmget("user");
}
//通过token登录
@RequestMapping("/login")
public Object login(String token){
Object object = redisUtil.hget("user",token);
JSONObject jsonObject = new JSONObject();
jsonObject.put("token",token);
if(object != null ){
jsonObject.put("data",object);
jsonObject.put("msg","token存在,可以登录");
}else {
jsonObject.put("msg","token不存在");
}
return jsonObject;
}
//注册用户
@RequestMapping("/add")
public Object addInfo(){
String token = UUID.randomUUID().toString().replace("-","");
Map<String,Object> map = new HashMap<>();
UserTest userTest = new UserTest(token, UUID.randomUUID().toString(),
"test","12L", new Date());
map.put(token,userTest);
JSONObject jsonObject = new JSONObject();
jsonObject.put("token",token);
jsonObject.put("reg",redisUtil.hmset("user",map));
jsonObject.put("msg","注册成功,已分配token");
return jsonObject;
}
}