当前位置 主页 > 服务器问题 > Linux/apache问题 >

    基于Java验证jwt token代码实例

    栏目:Linux/apache问题 时间:2019-12-21 16:33

    这篇文章主要介绍了基于Java验证jwt token代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    How to load public certificate from pem file..?地址

    1.HS256对称加密

    package jwt;
     
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.KeyFactory;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.Base64;
    import java.util.Date;
    import java.util.Vector;
    import java.util.Map;
     
    import sun.misc.BASE64Decoder;
     
    import com.auth0.jwt.JWT;
    import com.auth0.jwt.algorithms.Algorithm;
    import com.auth0.jwt.exceptions.JWTVerificationException;
    import com.auth0.jwt.interfaces.Claim;
    import com.auth0.jwt.interfaces.DecodedJWT;
     
     
    public class JWTValidator {
      private static String JWT_Type = "JWT";
       
      protected boolean validated;
      protected Object[] claims;
       
      public JWTValidator() {
        setValidated(false);
        setClaims(null);
      }
      public String Generate(String secret, String issuer, String audience, String subject){
        try {
          Algorithm algorithm = Algorithm.HMAC256(secret); // HS256
          String token = JWT.create()
            .withIssuer(issuer)
            .withAudience(audience)
            .withSubject(subject)
            .sign(algorithm);
          System.out.println(token);
          return token;
        } catch (Exception exception){
          //UTF-8 encoding not supported
          return "";
        }
      }
       
     
      public void Validate(String token, String secret, String issuer, String audience, String subject) {
        DecodedJWT jwt = null;
        setValidated(false);
         
        if (token == null || secret == null || issuer == null || audience == null || subject == null)
          return;
         
        try {
          jwt = JWT.require(Algorithm.HMAC256(secret.getBytes())).build().verify(token);
        } catch (JWTVerificationException e) {
          return;
        }
         
        if (jwt == null || jwt.getType() == null || !jwt.getType().contentEquals(JWT_Type))
          return;
         
        if (!jwt.getIssuer().contentEquals(issuer) ||
          !jwt.getAudience().contains(audience) ||
          !jwt.getSubject().contentEquals(subject))
          return;
         
        Date now = new Date();
         
        if ((jwt.getNotBefore() != null && jwt.getNotBefore().after(now)) ||
          (jwt.getExpiresAt() != null && jwt.getExpiresAt().before(now)))
          return;
         
        setValidated(true);
     
        Map<String, Claim> claimsMap = jwt.getClaims();
        Vector<Claim> claimsVector = new Vector<Claim>();
         
        if (claimsMap != null) {
          for (Map.Entry<String, Claim> entry : claimsMap.entrySet()) {
            String key = entry.getKey();
            if (key != null && !key.matches("aud|sub|iss|exp|iat")) {         
              //claimsVector.add(new Claim(key, entry.getValue().asString()));
            }
          }   
        }
     
        setClaims(claimsVector.isEmpty() ? null : claimsVector.toArray());
      }
     
      public boolean isValidated() { return validated; }
      public void setValidated(boolean val) { validated = val; }
     
      public Object[] getClaims() { return claims; }
      public void setClaims(Object[] val) { claims = (val == null ? new Object[0] : val); }
    }