token学习

编程入门 行业动态 更新时间:2024-10-21 11:43:10

<a href=https://www.elefans.com/category/jswz/34/1770646.html style=token学习"/>

token学习

jwt学习

为什么使用jwt
  • session存储在服务器内存,当用户过多时服务器压力大
  • 集群环境需要额外处理(多台服务器时,一台服务器存储的session需要让另一台知道)
  • csrf:cookie被截获后可能发生跨站点请求伪造
  • cookie的跨域读写不方便
jwt组成
  • Header.Payload.Signature
jwt实现方式
  • java-jwt
public class JavaJwtTest {//key为密钥String key = "123456abc";@Test/*** 生成token*/public void testGenerateToken(){Calendar calendar =Calendar.getInstance();//设置有效时间为10分钟calendar.add(Calendar.MINUTE,10);下面的为生成payload所用的参数JWTCreator.Builder builder = JWT.create().withClaim("userId", 123).withClaim("userName", "hzpJava").withClaim("url", "nenu.edu");//设置过期时间       builder.withExpiresAt(calendar.getTime());//设置加密算法String token = builder.sign(Algorithm.HMAC256(key));System.out.println(token);}@Test/*** 校验*/public void testVerify(){//这是上面的代码生成的tokenString token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6Imh6cEphdmEiLCJleHAiOjE2NDk2ODg5NDYsInVzZXJJZCI6MTIzLCJ1cmwiOiJuZW51LmVkdS5jbiJ9.A07W5npWP5ELwmkdUGAPjLU767jc_wTyTd3CWIEMWr0";DecodedJWT verity = null ;try{verity=JWT.require(Algorithm.HMAC256(key)).build().verify(token);} catch (SignatureVerificationException e){e.printStackTrace();System.out.println("签名不一致");}catch (TokenExpiredException e){e.printStackTrace();System.out.println("token过期");}catch (AlgorithmMismatchException e){e.printStackTrace();System.out.println("签名算法不匹配");}catch (InvalidParameterException e){e.printStackTrace();System.out.println("payload不可用");}catch (Exception e){e.printStackTrace();System.out.println("校验失败");}if(verity!=null){//可用getClaim方法获取之前设置的值,但参数类型需要一致,不然为nullint id = verity.getClaim("userId").asInt();System.out.println(id);}}
}
  • jjwt
public class JjwtTest {String key = "huozhipeng";/*** 获取*/@Testpublic void jjwtGenerateTest(){Calendar calendar = Calendar.getInstance();calendar.add(Calendar.SECOND,60*10);Map<String,Object> claims = new HashMap<>();claims.put("userId",123321456);claims.put("userName","java");claims.put("url","com.nenu.edu");JwtBuilder builder =Jwts.builder().setClaims(claims).setExpiration(calendar.getTime()).signWith(SignatureAlgorithm.HS256, key);String compact = builderpact();System.out.println(compact);}@Test/*** 校验*/public void testVerify(){String token = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6ImphdmEiLCJleHAiOjE2NDk3NjEwMjYsInVzZXJJZCI6MTIzMzIxNDU2LCJ1cmwiOiJjb20ubmVudS5lZHUuY24ifQ.U-WYNJf3w_15_8pzr7ju51T0JmKXO10BV3_GyzS77II";Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();Integer userId = claims.get("userId",Integer.class);String username = claims.get("username",String.class);String url = claims.get("url",String.class);System.out.println("userId:"+userId);}
}

上面是在test中测的,下面为部署到服务器上的:
写一个工具类:

public class jwtUtil {private static final String KEY = "123456abc";/*** 生成token*/public static String Generate(User user){Calendar calendar = Calendar.getInstance();//日期设为一天calendar.add(Calendar.DATE,1);if(user==null){return null;}JWTCreator.Builder builder = JWT.create().withClaim("userInfo", JSON.toJSONString(user)).withExpiresAt(calendar.getTime());String token = builder.sign(Algorithm.HMAC256(KEY));return token;}/*** 校验token,*/public static DecodedJWT verify(String token){DecodedJWT verity = null ;try{verity=JWT.require(Algorithm.HMAC256(KEY)).build().verify(token);} catch (SignatureVerificationException e){e.printStackTrace();System.out.println("签名不一致");}catch (TokenExpiredException e){e.printStackTrace();System.out.println("token过期");}catch (AlgorithmMismatchException e){e.printStackTrace();System.out.println("签名算法不匹配");}catch (InvalidParameterException e){e.printStackTrace();System.out.println("payload不可用");}catch (Exception e){e.printStackTrace();System.out.println("校验失败");}return verity;}/***根据校验返回user对象,user对象就name和password两个属性*/public static User parse(DecodedJWT decodedJWT){Claim claim = decodedJWT.getClaim("userInfo");if(claim!=null){String s = claim.asString();User user = JSON.parseObject(s,User.class);return user;}return null;}
}

下面是过滤器:

public class Authfilter implements Filter {@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletResponse resp =(HttpServletResponse) response;HttpServletRequest req = (HttpServletRequest) request;String type = req.getParameter("type");String method = req.getMethod();if("option".equals(method)){chain.doFilter(request,response);return;}if("login".equals(type)){chain.doFilter(request,response);return;}System.out.println(jwtUtil.Generate(new User("hhh","ppp")));String token;token = req.getHeader("token");if(token == null){token = req.getParameter("token");}if(token == null){Map<String,String> map = new HashMap<>();map.put("msg","未获取到token");respUtil.respAppJson(resp,map);return;}DecodedJWT verify = jwtUtil.verify(token);if (verify == null) {//token错误Map<String,String> map = new HashMap<>();map.put("msg","校验失败");respUtil.respAppJson(resp,map);return;}User user = jwtUtil.parse(verify);if(user==null){Map<String,String> map = new HashMap<>();map.put("msg","payload不合法");respUtil.respAppJson(resp,map);return;}System.out.println("获取到filter里的user信息:"+ JSON.toJSONString(user));chain.doFilter(request,response);}
}

本文为jwt实战的学习笔记

更多推荐

token学习

本文发布于:2024-03-10 20:29:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1728956.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:token

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!