generate token
First, when logging in to register I log in by passing in the phone, password, and then randomly generate a UUID to store it in the cache
@RestController
@CrossOrigin("*")
@RequestMapping("servicerest/auth")
public class AuthController extends BaseController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
//定义一个缓存器
@Resource
private CacheManager cacheManager;
//我的一个实体
@Autowired
private ILoginUserService loginUserService;
/**
* 获取token
* @author: gufeng
*/
@RequestMapping("/getToken")
public AjaxResult getToken(String phone, String pwd) {
//随机生成一个UUID
String uuid = UUID.randomUUID().toString().replaceAll("-","");
//获取我配置的缓存器 (在.xml文件中配置)
Cache cache = cacheManager.getCache("serviceCacheToken");
try {
QueryWrapper<LoginUser> queryWrapper = new QueryWrapper<>();
queryWrapper = queryWrapper.eq("user_phone",phone);
queryWrapper = queryWrapper.eq("user_pwd",pwd);
List<LoginUser> loginUserList = loginUserService.list(queryWrapper);
if(loginUserList.size() > 0){
//将UUID存到缓存中
cache.put(uuid, loginUserList.get(0).getId());
}else{
return AjaxResult.error(ErrorEnum.USERNAME_OR_PASSWORD_ERROR.code, ErrorEnum.USERNAME_OR_PASSWORD_ERROR.message);
}
} catch (Exception e) {
logger.info("发生了异常,异常信息是:"+e.getMessage());
}
JSONObject object = new JSONObject();
//将UUID返回
object.put("serviceToken", uuid);
return success(object);
}
/**
* 销毁token(下线)
* @param serviceToken
* @author: gufeng
* @return
*/
@ServiceTokenRequired
@RequestMapping("/destroy")
public AjaxResult destroy(String serviceToken) {
Cache cache = cacheManager.getCache("cacheToken");
try{
// 删除用户在线状态
cache.evict(serviceToken);
} catch(Exception e) {
logger.error("下线异常:" + e.getMessage());
return error(ErrorEnum.DESTROY_ERROR.toString());
}
return success();
}
}
token validation aspect
/**
* token验证切面,
* @author: gufeng
*/
@Aspect
@Component
public class ServiceValidateTokenAspect extends BaseController {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private CacheManager cacheManager;
@Pointcut("@annotation(com.mbyte.easy.annotation.ServiceTokenRequired)")
public void validateToken(){
}
/**
* 验证token
* @param joinPoint
* @return
* @throws Throwable
* @author: gufeng
*/
@Around("validateToken()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
Object result = null;
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
String token = request.getParameter("serviceToken");
Cache cache = cacheManager.getCache("serviceCacheToken");
if(StringUtils.isEmpty(token)) {
return error(ErrorEnum.TOKEN_EMPTY.toString());
}
if (StringUtils.isEmpty(cache.get(token,Long.class))) {
return error(ErrorEnum.TOKEN_ERROR.toString());
}
result = joinPoint.proceed();
return result;
}
}
Custom Validation Annotations
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
/**
* 用于标注是否需要验证token
* @author: gufeng
*/
public @interface ServiceTokenRequired {
}