如何在项目中用token进行权限验证
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在项目中用token进行权限验证相关的知识,希望对你有一定的参考价值。
如何在项目中用token进行权限验证
原理: 当用户首次登录的时候,后台给用户生成一个token,并缓存到Map中,后续每次登录都会根据userId校验,移动端调用后台的每个服务都需要有token的验证通过才视作合法的。
1.首先自定义一个annotations,注解br/>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ApiAuth {
String value() default "";
}
2.自定义一个拦截器
public class ApiAuthInterceptor extends HandlerInterceptorAdapter {
private static final int TOKEN_LONG = 32; //token的长度
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
}
// token验证
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
ApiAuth authPassport = ((HandlerMethod) handler).getMethodAnnotation(ApiAuth.class);
if (authPassport != null) {
String paramToken = request.getParameter("token");
if (paramToken == null) {
fillUnauthorizedResponse(response);
return false;
}
if (!isTokenValid(paramToken)) {
fillTokenUnauthorizedResponse(response);
return false;
}
return true;
}
}
return true;
}
private boolean isTokenValid(String token) {
// token为空,或者token位数不为32位
if (StringUtils.isEmpty(token) || token.length() != TOKEN_LONG) {
return false;
}
// 验证token是否存在
return BaseDataMapCache.checkToken(token);
}
private void fillUnauthorizedResponse(HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(JSON.toJSONString(ResultObject.error("身份验证未通过!")));
out.flush();
out.close();
}
private void fillTokenUnauthorizedResponse(HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(JSON.toJSONString(ResultObject.error("token验证失败!")));
out.flush();
out.close();
}
}
public class BaseDataMapCache {
private static Map<String, String> dataMap = Maps.newHashMap();
public static void push(String key, String value) {
dataMap.put(key, value);
}
public static String putToken(String userId) {
if (!dataMap.containsKey(userId)) {
String token = UUID.randomUUID().toString().replaceAll("-", "");
dataMap.put(userId, token);
}
return dataMap.get(userId);
}
public static boolean checkToken(String token) {
return !dataMap.isEmpty() && dataMap.containsValue(token);
}
}
3.配置spring-mvc.xml文件
以上是关于如何在项目中用token进行权限验证的主要内容,如果未能解决你的问题,请参考以下文章
Spring Security框架下Restful Token的验证方案
Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段