Redis
数据库设计
/**
* redis key 前缀
*/
public static final String REDIS_KEY_PREFIX = "easylive:";
/**
* 验证码key
*/
public static final String REDIS_KEY_CHECK_CODE = REDIS_KEY_PREFIX + "check_code:";
/**
* Redis key token web
*/
public static final String REDIS_KEY_TOKEN_WEB = REDIS_KEY_PREFIX + "token:web:";
public static final String TOKEN_WEB = "token";
public static final String TOKEN_ADMIN = "adminToken";
public static final String REDIS_KEY_TOKEN_ADMIN = REDIS_KEY_PREFIX + "token:admin:";
- Redis 数据库存储如下:
easylive:token:admin+token(UUID)
easylive:token:admin+token
作为键,值 为account
账户
easylive:token:web+token(UUID)
easylive:token:web+token
作为键,值为TokenUserInfoDto
{"@class":"com.easylive.entity.dto.TokenUserInfoDto",
"userId":null,
"nickName":null,
"avatar":null,
"expireAt":1730826856010,
"token":"5b09d79f-b5c5-4a37-a4b4-3bba8fbad0ec",
"fansCount":null,
"currentCoinCount":null,
"focusCount":null}
- TokenUserInfoDto实体
@JsonIgnoreProperties(ignoreUnknown = true)
public class TokenUserInfoDto implements Serializable {
private static final long serialVersionUID = -6910208948981307451L;
private String userId;
private String nickName;
private String avatar;
private Long expireAt;
private String token;
}
登录
- admin 端登录
@RequestMapping(value = "/login")
public ResponseVO login(HttpServletRequest request,
HttpServletResponse response,
@NotEmpty String account,
@NotEmpty String password, @NotEmpty String checkCode,
@NotEmpty String checkCodeKey) {
try {
if (!checkCode.equalsIgnoreCase((String) redisUtils.get(Constants.REDIS_KEY_CHECK_CODE + checkCodeKey))) {
throw new BusinessException("图片验证码不正确");
}
if (!account.equals(appConfig.getAdminAccount()) || !password.equals(StringTools.encodeByMD5(appConfig.getAdminPassword()))) {
throw new BusinessException("账号或者密码错误");
}
String token = redisComponent.saveTokenInfo4Admin(account);
// 把token 放入cookie 中
saveToken2Cookie(response, token);
return getSuccessResponseVO(account);
} finally {
// 去掉老的admintoken
redisUtils.delete(Constants.REDIS_KEY_CHECK_CODE + checkCodeKey);
Cookie[] cookies = request.getCookies();
String token = null;
for (Cookie cookie : cookies) {
if (cookie.getName().equals(Constants.TOKEN_ADMIN)) {
token = cookie.getValue();
}
}
if (!StringTools.isEmpty(token)) {
redisComponent.cleanToken4Admin(token);
}
}
}
public String saveTokenInfo4Admin(String account) {
String token = UUID.randomUUID().toString();
redisUtils.setex(Constants.REDIS_KEY_TOKEN_ADMIN + token, account, Constants.REDIS_KEY_EXPIRES_DAY);
return token;
}
public void saveToken2Cookie(HttpServletResponse response, String token) {
Cookie cookie = new Cookie(Constants.TOKEN_ADMIN, token);
cookie.setMaxAge(-1);
cookie.setPath("/");
response.addCookie(cookie);
}
总结
- 把用户信息存入
redis
中,并返回对应的token
, 这个token
+ 对应的前缀就是redis
中对应的 键。后期可以通过这个键找到值。从而进行身份校验。 - 返回的
token
相当于是 用户信息的加密映射。存入cookie
,
Cookie cookie = new Cookie(Constants.TOKEN_ADMIN, token);
草草画个图