1. 程式人生 > >如何在項目中用token進行權限驗證

如何在項目中用token進行權限驗證

amp 配置 服務 ring common ole mvc 登錄 flush

如何在項目中用token進行權限驗證
原理: 當用戶首次登錄的時候,後臺給用戶生成一個token,並緩存到Map中,後續每次登錄都會根據userId校驗,移動端調用後臺的每個服務都需要有token的驗證通過才視作合法的。

1.首先自定義一個annotations,註解@Retention(RetentionPolicy.RUNTIME)
br/>@Retention(RetentionPolicy.RUNTIME)
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進行權限驗證