运维开发网

如何在项目中用token进行权限验证

运维开发网 https://www.qedev.com 2020-02-26 16:20 出处:51CTO 作者:zheng854938169
在项目中用token进行权限验证,确保移动端的请求是合法的

如何在项目中用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文件

<!-- APP的token验证 -->

<mvc:interceptors>

<mvc:interceptor>

<mvc:mapping path="/**" />

<bean class="com.flower.mall.commons.interceptors.ApiAuthInterceptor" />

</mvc:interceptor>

</mvc:interceptors>

扫码领视频副本.gif

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号