如何在項目中用token進行權限驗證
原理: 當用戶首次登陸的時候,後臺給用戶生成一個token,並緩存到Map中,後續每次登陸都會根據userId校驗,移動端調用後臺的每一個服務都須要有token的驗證經過才視做合法的。spring
1.首先自定義一個annotations,註解br/>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ApiAuth {
String value() default "";
}json
2.自定義一個攔截器
public class ApiAuthInterceptor extends HandlerInterceptorAdapter {spring-mvc
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 {mvc
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); }
}app
3.配置spring-mvc.xml文件
<!-- APP的token驗證 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.flower.mall.commons.interceptors.ApiAuthInterceptor" />
</mvc:interceptor>
</mvc:interceptors>dom