码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-02-25 10:43:12      阅读:503      评论:0      收藏:0      [点我收藏+]

标签:eof   cte   tty   tor   权限   ati   stat   ada   enc   

如何在项目中用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进行权限验证

标签:eof   cte   tty   tor   权限   ati   stat   ada   enc   

原文地址:https://blog.51cto.com/9381188/2354265

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!