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;
}
}