标签:eof cte tty tor 权限 ati stat ada enc
如何在项目中用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文件
标签:eof cte tty tor 权限 ati stat ada enc
原文地址:https://blog.51cto.com/9381188/2354265