token 简单理解就是 加密 解密的一个过程

JavaWebToken(加密解密工具)
public class JavaWebToken {

    private static Logger log = LoggerFactory.getLogger(JavaWebToken.class);

    //该方法使用HS256算法和Secret:bankgl生成signKey
private static Key getKeyInstance() {
//We will sign our JavaWebToken with our ApiKey secret
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("bankgl");
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
return signingKey;
} //使用HS256签名算法和生成的signingKey最终的Token,claims中是有效载荷
public static String createJavaWebToken(Map<String, Object> claims) {
return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, getKeyInstance()).compact();
} //解析Token,同时也能验证Token,当验证失败返回null
public static Map<String, Object> parserJavaWebToken(String jwt) {
try {
Map<String, Object> jwtClaims =
Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwt).getBody();
return jwtClaims;
} catch (Exception e) {
log.error("json web token verify failed");
return null;
}
}
}
JavaWebInterceptor(拦截器)
public class JavaWebInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setContentType("multipart/form-data");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter printwriter = new PrintWriter(response.getOutputStream());
String token = request.getParameter("token");
response.setHeader("token", token);
printwriter.println("token:" + token);
if (null != JavaWebToken.parserJavaWebToken(token)) {
Map<String, Object> tokenMapVal = JavaWebToken.parserJavaWebToken(token);//解析token
for (String key : tokenMapVal.keySet()) {
String value = (String) tokenMapVal.get(key);
printwriter.println("解析的内容:(key:" + key + " value:" + value + ")");
}
String endTime=tokenMapVal.get("times").toString();
long currentTime=System.currentTimeMillis();
printwriter.println("当前时间"+currentTime);
printwriter.println("结束时间"+endTime);
if(Long.valueOf(endTime).longValue()<=currentTime){
printwriter.println("token失效,请重新获取token");
printwriter.flush();
printwriter.close();
return false;
}
if (tokenMapVal.get("passwd").equals("123456")){
printwriter.println("登陆验证成功");
}else{
printwriter.println("登陆验证失败");
}
printwriter.flush();
printwriter.close();
return true;
} else {
printwriter.println("没有token信息");
printwriter.flush();
printwriter.close();
return false;
} } @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }
}
spring-mv.xml(配置拦截器)
<mvc:interceptor>
<mvc:mapping path="/hello/ai"/>
<bean class="com.sun.test.aircraft.token.JavaWebInterceptor"/>
</mvc:interceptor>
controller(请求数据)
@RequestMapping("/token")
public String token(Model model, HttpServletRequest request, HttpServletResponse response){
Map<String,Object> map=new HashMap<String,Object>();
map.put("passwd","123456");//负载
map.put("times","1000");//负载
String token=JavaWebToken.createJavaWebToken(map);//创建token
model.addAttribute("token",token);
return "redirect:/hello/ai";
}
引入的jar 包:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
效果:
token 案例,只是测试,功能并不完善(只是看看token 到底是何方神圣)-LMLPHP
做的完善功能远不止这一点
比如:
1、用户登陆成功后生成的token放到数据库中,每次登陆的时候拿token对比
2、把token放到头信息里
3、在负载中加入token的有效时间(也可利用redis的ttl设置有效时间,方式很多种),token失效后重新获取,重新存入数据库(比如:redis,mongodb)中 等
如果看官有认为我理解的错误的地方,可以留下你的评论,我好改正,感谢!
 
05-11 20:07