赞
踩
1.引入jjwt
maven pom.xml
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
2.写个工具类简单封装一下创建和鉴权步骤
注意:jwt标准注册声明中比较重要的就是exp字段,用于判断token是否过期,其他的可以按照个人喜好情况自行添加.
public class Jwt { private static String key = "WkskpDhSkuBUOP*ITB*123123123"; public static String createJwt(String userId){ //默认签发有效期24小时的token return createJwt(userId,"subject","issure",86400000); } public static String createJwt(String id, String subject, String issure, long till) { JwtBuilder jwtBuilder = Jwts.builder().setId(id) .signWith(SignatureAlgorithm.HS256, new SecretKeySpec(DatatypeConverter.parseBase64Binary(key), SignatureAlgorithm.HS256.getJcaName())) .setIssuer(issure) .setSubject(subject) .setExpiration(new Date(System.currentTimeMillis() + till)); return jwtBuilder.compact(); } public static Claims parseJwt(String token) throws Exception { Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(key)).parseClaimsJws(token).getBody(); return claims; } }
3.拦截器使用鉴权
注意:这里我们只判断token是否伪造和过期,不在拦截器里面判断用户权限信息.
这里token我们默认加上bearer加空格前缀。。。
public class ApiInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String authorization=request.getHeader("Authorization"); if(authorization == null || ! authorization.startsWith("Bearer ")){ this.setErrorResponse(response,"未携带token"); return false; } String token=authorization.substring(7); try { request.setAttribute("user",Jwt.parseJwt(token)); }catch(Exception e) { this.setErrorResponse(response,e.getMessage()); return false; } return true; } protected void setErrorResponse(HttpServletResponse response,String message) throws IOException { response.setHeader("Content-type", "text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(message); response.getWriter().flush(); response.getWriter().close(); } }
4.配置拦截器
springmvc-xml
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/*"/>
<!-- 排除登录-->
<mvc:exclude-mapping path="/login"/>
<bean class="cn.dishenghk.Interceptor.ApiInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。