1、什么是token
token的意思是“令牌”,是服务端生成的一串字符串,作为客户端进行请求的一个标识。
当用户第一次登录后,服务器生成一个token并将此token返回给客户端,以后客户端只需带上这个token前来请求数据即可,无需再次带上用户名和密码。
简单token的组成;uid(用户唯一的身份标识)、time(当前时间的时间戳)、sign(签名,token的前几位以哈希算法压缩成的一定长度的十六进制字符串。为防止token泄露)
2、SSM基于XML配置
pom.xml引入
<!-- token --> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency>
spring-mvc.xml
配置拦截器
<mvc:interceptors> <!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 --> <!-- <bean class="com.bybo.aca.web.interceptor.Login"/> --> <mvc:interceptor> <!-- 进行拦截:/**表示拦截所有controller --> <mvc:mapping path="/**" /> <!-- 不进行拦截 --> <mvc:exclude-mapping path="/user/login"/> <!-- 不进行拦截 --> <mvc:exclude-mapping path="/get/tableInforAllByStatus" /> <bean class="com.baccarat.util.JWTInterceptor" /> </mvc:interceptor> </mvc:interceptors>
拦截器实体类
package com.baccarat.util; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.baccarat.controller.UserController; import com.baccarat.entity.User; @Component public class JWTInterceptor implements HandlerInterceptor{ public static Logger logger = Logger.getLogger(UserController.class); public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub } public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub } /** * Token validates the interceptor * @author Stephen * @time 2019-10-11 17:00:32 * */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws IOException { ResultVO result = new ResultVO(); PrintWriter out = null ; String token = request.getHeader("token"); String userId = request.getHeader("userId"); /** 您的处理逻辑 */ //以下是返回拦截器拦截后返回json格式的方式 result.setStatus(203); result.setMessage("Login verification failed, please login again"); String jsonStr = BaccaratUtil.toJSon(result); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); out = response.getWriter(); out.append(jsonStr); return false; } }
JWTUtil.java
package com.baccarat.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.auth0.jwt.JWTSigner; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.internal.com.fasterxml.jackson.databind.ObjectMapper; import com.baccarat.controller.UserController; import com.baccarat.entity.User; /** * @Todo JWT(json web token),util * @author Stephen * @Time 2019-10-11 12:12:04 */ public class JWTUtil { private static Logger logger = Logger.getLogger(UserController.class); private static final String SECRET = "XX#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf>?N<:{LWPW"; private static final String EXP = "exp"; private static final String PAYLOAD = "payload"; private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * @Todo Encrypt, passing in an object and expiration date * @author Stephen * @Time 2019-10-11 12:12:44 */ public static <T> String sign(T object, long maxAge) { try { final JWTSigner signer = new JWTSigner(SECRET); final Map<String, Object> claims = new HashMap<String, Object>(); ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(object); claims.put(PAYLOAD, jsonString); claims.put(EXP, System.currentTimeMillis() + maxAge); return signer.sign(claims); } catch (Exception e) { return null; } } /** * @Todo Decrypt, passing in an encrypted token string and decrypted type * @author Stephen * @Time 2019-10-11 12:13:08 * @param jwt,classT * @return T */ public static <T> T unsign(String jwt, Class<T> classT) { final JWTVerifier verifier = new JWTVerifier(SECRET); try { final Map<String, Object> claims = verifier.verify(jwt); if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) { long exp = (Long) claims.get(EXP); long currentTimeMillis = System.currentTimeMillis(); if (exp > currentTimeMillis) { String json = (String) claims.get(PAYLOAD); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(json, classT); } } return null; } catch (Exception e) { return null; } } }
如有疑问请留意