类io.jsonwebtoken.SignatureException源码实例Demo

下面列出了怎么用io.jsonwebtoken.SignatureException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: sureness   文件: JsonWebTokenUtil.java
/**
 *
 * @param jwt json web token
 * @return 解签实体
 * @throws ExpiredJwtException token过期
 * @throws UnsupportedJwtException 不支持的TOKEN
 * @throws MalformedJwtException 参数格式形变等异常
 * @throws SignatureException 签名异常
 * @throws IllegalArgumentException 非法参数
 */
public static Claims parseJwt(String jwt) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
    return  Jwts.parser()
            .setSigningKey(DatatypeConverter.parseBase64Binary(secretKey))
            .parseClaimsJws(jwt)
            .getBody();

    // 令牌ID -- claims.getId()
    // 客户标识 -- claims.getSubject()
    // 客户标识
    // 签发者 -- claims.getIssuer()
    // 签发时间 -- claims.getIssuedAt()
    // 接收方 -- claims.getAudience()
    // 访问主张-角色 -- claims.get("roles", String.class)
    // 访问主张-权限 -- claims.get("perms", String.class)
}
 
源代码2 项目: localization_nifi   文件: JwtService.java
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
    try {
        return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
            @Override
            public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
                final String identity = claims.getSubject();

                // Get the key based on the key id in the claims
                final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class);
                final Key key = keyService.getKey(keyId);

                // Ensure we were able to find a key that was previously issued by this key service for this user
                if (key == null || key.getKey() == null) {
                    throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
                }

                return key.getKey().getBytes(StandardCharsets.UTF_8);
            }
        }).parseClaimsJws(base64EncodedToken);
    } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException | AdministrationException e) {
        // TODO: Exercise all exceptions to ensure none leak key material to logs
        final String errorMessage = "Unable to validate the access token.";
        throw new JwtException(errorMessage, e);
    }
}
 
源代码3 项目: NetworkDisk_Storage   文件: PageProvider.java
/**
 * 跳转到主页面数据处理
 *
 * @author: quhailong
 * @date: 2019/9/27
 */
public String homeHandle(Model model) {
    String token = CookieUtils.getCookie("token");
    if (!StringUtils.isEmpty(token)) {
        try {
            if (jedisClusterUtil.isExistKey("LOGOUT:" + token)) {
                return "login";
            } else {
                UserInfoDTO userInfoDTO = tokenAnalysisUtils.tokenAnalysis(token);
                model.addAttribute("name", userInfoDTO.getUserName());
                return "index";
            }
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException exception) {
            exception.printStackTrace();
            return "user";
        }
    }
    return "login";
}
 
源代码4 项目: NetworkDisk_Storage   文件: PageProvider.java
/**
 * 跳转到分享管理页面数据处理
 *
 * @author: quhailong
 * @date: 2019/9/27
 */
public String shareHandle(Model model) {
    String token = CookieUtils.getCookie("token");
    if (!StringUtils.isEmpty(token)) {
        try {
            if (jedisClusterUtil.isExistKey("LOGOUT:" + token)) {
                return "login";
            } else {
                UserInfoDTO userInfoDTO = tokenAnalysisUtils.tokenAnalysis(token);
                model.addAttribute("name", userInfoDTO.getUserName());
                return "share";
            }
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException exception) {
            exception.printStackTrace();
            return "user";
        }
    }
    return "login";
}
 
源代码5 项目: microprofile-jwt-auth   文件: JjwtVerifierTest.java
@Override
protected void validateToken(String token, RSAPublicKey publicKey, String issuer, int expGracePeriodSecs) throws Exception {
    JwtParser parser = Jwts.parser()
        .setSigningKey(publicKey)
        .requireIssuer(issuer)
        ;
    if(expGracePeriodSecs > 0) {
        parser = parser.setAllowedClockSkewSeconds(expGracePeriodSecs);
    }

    Jwt jwt = parser.parse(token);
    String alg = jwt.getHeader().get("alg").toString();
    if(alg == null || !alg.equals(SignatureAlgorithm.RS256.getValue())) {
        throw new SignatureException("Non-RS256 alg: "+alg);
    }
    Jws<Claims> claims = parser.parseClaimsJws(token);
}
 
源代码6 项目: lams   文件: RsaSignatureValidator.java
@Override
public boolean isValid(byte[] data, byte[] signature) {
    if (key instanceof PublicKey) {
        Signature sig = createSignatureInstance();
        PublicKey publicKey = (PublicKey) key;
        try {
            return doVerify(sig, publicKey, data, signature);
        } catch (Exception e) {
            String msg = "Unable to verify RSA signature using configured PublicKey. " + e.getMessage();
            throw new SignatureException(msg, e);
        }
    } else {
        Assert.notNull(this.SIGNER, "RSA Signer instance cannot be null.  This is a bug.  Please report it.");
        byte[] computed = this.SIGNER.sign(data);
        return Arrays.equals(computed, signature);
    }
}
 
源代码7 项目: lams   文件: EllipticCurveSignatureValidator.java
@Override
public boolean isValid(byte[] data, byte[] signature) {
    Signature sig = createSignatureInstance();
    PublicKey publicKey = (PublicKey) key;
    try {
        int expectedSize = getSignatureByteArrayLength(alg);
        /**
         *
         * If the expected size is not valid for JOSE, fall back to ASN.1 DER signature.
         * This fallback is for backwards compatibility ONLY (to support tokens generated by previous versions of jjwt)
         * and backwards compatibility will possibly be removed in a future version of this library.
         *
         * **/
        byte[] derSignature = expectedSize != signature.length && signature[0] == 0x30 ? signature : EllipticCurveProvider.transcodeSignatureToDER(signature);
        return doVerify(sig, publicKey, data, derSignature);
    } catch (Exception e) {
        String msg = "Unable to verify Elliptic Curve signature using configured ECPublicKey. " + e.getMessage();
        throw new SignatureException(msg, e);
    }
}
 
源代码8 项目: nifi-registry   文件: JwtService.java
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
    try {
        return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
            @Override
            public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
                final String identity = claims.getSubject();

                // Get the key based on the key id in the claims
                final String keyId = claims.get(KEY_ID_CLAIM, String.class);
                final Key key = keyService.getKey(keyId);

                // Ensure we were able to find a key that was previously issued by this key service for this user
                if (key == null || key.getKey() == null) {
                    throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
                }

                return key.getKey().getBytes(StandardCharsets.UTF_8);
            }
        }).parseClaimsJws(base64EncodedToken);
    } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException e) {
        // TODO: Exercise all exceptions to ensure none leak key material to logs
        final String errorMessage = "Unable to validate the access token.";
        throw new JwtException(errorMessage, e);
    }
}
 
源代码9 项目: atsea-sample-shop-app   文件: JwtFilter.java
@Override
public void doFilter(final ServletRequest req,
                     final ServletResponse res,
                     final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) req;

    final String authHeader = request.getHeader("Authorization");
    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        throw new ServletException("Missing or invalid Authorization header.");
    }

    final String token = authHeader.substring(7); // The part after "Bearer "

    try {
        final Claims claims = Jwts.parser().setSigningKey("secretkey")
            .parseClaimsJws(token).getBody();
        request.setAttribute("claims", claims);
    }
    catch (final SignatureException e) {
        throw new ServletException("Invalid token.");
    }

    chain.doFilter(req, res);
}
 
源代码10 项目: jwt-angular-spring   文件: JwtFilter.java
@Override
public void doFilter(final ServletRequest req,
                     final ServletResponse res,
                     final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) req;

    final String authHeader = request.getHeader("Authorization");
    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        throw new ServletException("Missing or invalid Authorization header.");
    }

    final String token = authHeader.substring(7); // The part after "Bearer "

    try {
        final Claims claims = Jwts.parser().setSigningKey("secretkey")
            .parseClaimsJws(token).getBody();
        request.setAttribute("claims", claims);
    }
    catch (final SignatureException e) {
        throw new ServletException("Invalid token.");
    }

    chain.doFilter(req, res);
}
 
源代码11 项目: nifi   文件: JwtService.java
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
    try {
        return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
            @Override
            public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
                final String identity = claims.getSubject();

                // Get the key based on the key id in the claims
                final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class);
                final Key key = keyService.getKey(keyId);

                // Ensure we were able to find a key that was previously issued by this key service for this user
                if (key == null || key.getKey() == null) {
                    throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
                }

                return key.getKey().getBytes(StandardCharsets.UTF_8);
            }
        }).parseClaimsJws(base64EncodedToken);
    } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException | AdministrationException e) {
        // TODO: Exercise all exceptions to ensure none leak key material to logs
        final String errorMessage = "Unable to validate the access token.";
        throw new JwtException(errorMessage, e);
    }
}
 
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    try {
        Authentication authentication = TokenAuthenticationHelper.getAuthentication(httpServletRequest);

        // 对用 token 获取到的用户进行校验
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException |
            SignatureException | IllegalArgumentException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token expired,登陆已过期");
    }
}
 
/**
 * Make sure Jwt created is formatted according to the Google Cloud IoT Core<a
 * href="https://cloud.google.com/iot/docs/how-tos/credentials/jwts#jwt_composition">spec</a>.
 */
@Test
public void testCreateJwtEc() throws JoseException {
    JwtGenerator jwtGenerator =
            new JwtGenerator(EC_KEY_PAIR, JWT_AUDIENCE, TOKEN_LIFETIME, TEST_CLOCK);
    String rawJwt = jwtGenerator.createJwt();

    // Validate JWT
    Jws<Claims> parsedJwt;
    try {
        parsedJwt = Jwts.parser()
                .setSigningKey(EC_KEY_PAIR.getPublic())
                .parseClaimsJws(rawJwt);
    } catch (UnsupportedJwtException | MalformedJwtException | SignatureException e) {
        fail("Error parsing JWT: " + e);
        return;  // Satisfy compiler
    }

    JwsHeader header = parsedJwt.getHeader();
    Claims claims = parsedJwt.getBody();

    assertThat(header.getAlgorithm()).isEqualTo("ES256");
    assertThat(header.getType()).isEqualTo("JWT");
    assertThat(claims.getAudience()).isEqualTo(JWT_AUDIENCE);

    // JWT requires time in seconds from epoch, not millis, so allow issue time within one
    // second.
    assertThat(claims.getIssuedAt().getTime()).isAtLeast(TEST_CLOCK.millis() - 1000);
    assertThat(claims.getIssuedAt().getTime()).isAtMost(TEST_CLOCK.millis() + 1000);

    // Check expiration time within one second of issue time + TOKEN_LIFETIME
    assertThat(claims.getExpiration().getTime())
            .isLessThan(Clock.offset(TEST_CLOCK, TOKEN_LIFETIME.plusSeconds(1)).millis());
    assertThat(claims.getExpiration().getTime())
            .isAtLeast(Clock.offset(TEST_CLOCK, TOKEN_LIFETIME.minusSeconds(1)).millis());
}
 
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException,
        IOException {
    try {
        Authentication authentication = TokenAuthenticationHelper.getAuthentication(request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException |
            SignatureException | IllegalArgumentException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token expired");
    }
}
 
源代码15 项目: ambari-logsearch   文件: AbstractJWTFilter.java
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
  if (StringUtils.isEmpty(getProvidedUrl())) {
    throw new BadCredentialsException("Authentication provider URL must not be null or empty.");
  }
  if (StringUtils.isEmpty(getPublicKey())) {
    throw new BadCredentialsException("Public key for signature validation must be provisioned.");
  }

  try {
    Claims claims = Jwts
      .parser()
      .setSigningKey(parseRSAPublicKey(getPublicKey()))
      .parseClaimsJws(getJWTFromCookie(request))
      .getBody();
    String userName  = claims.getSubject();
    logger.info("USERNAME: " + userName);
    logger.info("URL = " + request.getRequestURL());
    if (StringUtils.isNotEmpty(claims.getAudience()) && !getAudiences().contains(claims.getAudience())) {
      throw new IllegalArgumentException(String.format("Audience validation failed. (Not found: %s)", claims.getAudience()));
    }
    Authentication authentication = new JWTAuthenticationToken(userName, getPublicKey(), getAuthorities(userName));
    authentication.setAuthenticated(true);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    return authentication;
  } catch (ExpiredJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
    logger.info("URL = " + request.getRequestURL());
    logger.warn("Error during JWT authentication: {}", e.getMessage());
    throw new BadCredentialsException(e.getMessage(), e);
  }
}
 
源代码16 项目: Java-EE-8-and-Angular   文件: JWTFilter.java
private String getUserIfValid(String token) {
    Key key = new SecretKeySpec("secret".getBytes(), "DES");
    try {
        Jws<Claims> claims = Jwts.parser().setSigningKey(key)
                .parseClaimsJws(token);
        String scope = claims.getBody().get("scope", String.class);
        System.out.println("scope " + scope);
        return claims.getBody().getSubject();
    } catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) {
        //don't trust the JWT!
        e.printStackTrace();
        throw new NotAuthorizedException("Invalid JWT");
    }
}
 
源代码17 项目: Java-EE-8-and-Angular   文件: JWTFilter.java
private String getUserIfValid(String token) {
    Key key = new SecretKeySpec("secret".getBytes(), "DES");
    try {
        Jws<Claims> claims = Jwts.parser().setSigningKey(key)
                .parseClaimsJws(token);
        String scope = claims.getBody().get("scope", String.class);
        System.out.println("scope " + scope);
        return claims.getBody().getSubject();
    } catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) {
        //don't trust the JWT!            
        throw new NotAuthorizedException("Invalid JWT");
    }
}
 
@Test(expectedExceptions = {BadJWSException.class, SignatureVerificationException.class,
    InvalidJwtSignatureException.class, SignatureException.class},
    description = "Illustrate validation of signer")
public void testFailSignature() throws Exception {
    HashSet<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
    invalidFields.add(TokenUtils.InvalidClaims.SIGNER);
    String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
    RSAPublicKey publicKey = (RSAPublicKey) TokenUtils.readPublicKey("/publicKey.pem");
    int expGracePeriodSecs = 60;
    validateToken(token, publicKey, TEST_ISSUER, expGracePeriodSecs);
}
 
private Jws<Claims> parseToken(final String token) {
    if (token != null) {
        try {
            return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException
                | SignatureException | IllegalArgumentException e) {
            return null;
        }
    }
    return null;
}
 
源代码20 项目: lams   文件: RsaProvider.java
protected void setParameter(Signature sig, PSSParameterSpec spec) {
    try {
        doSetParameter(sig, spec);
    } catch (InvalidAlgorithmParameterException e) {
        String msg = "Unsupported RSASSA-PSS parameter '" + spec + "': " + e.getMessage();
        throw new SignatureException(msg, e);
    }
}
 
源代码21 项目: lams   文件: RsaSigner.java
protected byte[] doSign(byte[] data) throws InvalidKeyException, java.security.SignatureException {
    PrivateKey privateKey = (PrivateKey)key;
    Signature sig = createSignatureInstance();
    sig.initSign(privateKey);
    sig.update(data);
    return sig.sign();
}
 
源代码22 项目: lams   文件: EllipticCurveSigner.java
protected byte[] doSign(byte[] data) throws InvalidKeyException, java.security.SignatureException, JwtException {
    PrivateKey privateKey = (PrivateKey)key;
    Signature sig = createSignatureInstance();
    sig.initSign(privateKey);
    sig.update(data);
    return transcodeSignatureToConcat(sig.sign(), getSignatureByteArrayLength(alg));
}
 
源代码23 项目: lams   文件: SignatureProvider.java
protected Signature createSignatureInstance() {
    try {
        return getSignatureInstance();
    } catch (NoSuchAlgorithmException e) {
        String msg = "Unavailable " + alg.getFamilyName() + " Signature algorithm '" + alg.getJcaName() + "'.";
        if (!alg.isJdkStandard() && !isBouncyCastleAvailable()) {
            msg += " This is not a standard JDK algorithm. Try including BouncyCastle in the runtime classpath.";
        }
        throw new SignatureException(msg, e);
    }
}
 
源代码24 项目: klask-io   文件: TokenProvider.java
public boolean validateToken(String authToken) {
    try {
        Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken);
        return true;
    } catch (SignatureException e) {
        log.info("Invalid JWT signature: " + e.getMessage());
        return false;
    }
}
 
源代码25 项目: javaee8-jaxrs-sample   文件: TokenProvider.java
public boolean validateToken(String authToken) {
    try {
        Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken);
        return true;
    } catch (SignatureException e) {
        LOGGER.log(Level.INFO, "Invalid JWT signature: {0}", e.getMessage());
        return false;
    }
}
 
源代码26 项目: iotplatform   文件: RawAccessJwtToken.java
/**
 * Parses and validates JWT Token signature.
 *
 * @throws BadCredentialsException
 * @throws JwtExpiredTokenException
 *
 */
public Jws<Claims> parseClaims(String signingKey) {
  try {
    return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token);
  } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
    logger.error("Invalid JWT Token", ex);
    throw new BadCredentialsException("Invalid JWT token: ", ex);
  } catch (ExpiredJwtException expiredEx) {
    logger.info("JWT Token is expired", expiredEx);
    throw new JwtExpiredTokenException(this, "JWT Token expired", expiredEx);
  }
}
 
源代码27 项目: gpmr   文件: TokenProvider.java
public boolean validateToken(String authToken) {
    try {
        Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken);
        return true;
    } catch (SignatureException e) {
        log.info("Invalid JWT signature: " + e.getMessage());
        return false;
    }
}
 
/**
 * Parses and validates JWT Token signature.
 * 
 * @throws BadCredentialsException
 * @throws JwtExpiredTokenException
 * 
 */
public Jws<Claims> parseClaims(String signingKey) {
    try {
        return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token);
    } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
        logger.error("Invalid JWT Token", ex);
        throw new BadCredentialsException("Invalid JWT token: ", ex);
    } catch (ExpiredJwtException expiredEx) {
        logger.info("JWT Token is expired", expiredEx);
        throw new JwtExpiredTokenException(this, "JWT Token expired", expiredEx);
    }
}
 
源代码29 项目: zevencourse   文件: Auth.java
public static void main (String [] args) {
    Map<String,Object> claims = new HashMap<String, Object>();
    claims.put("id",1);
    claims.put("name","zeven");
    claims.put("role","admin");
    String s = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, key).compact();
    System.out.println(s);
    Claims result;
    try {
        result = Jwts.parser().setSigningKey(key).parseClaimsJws(s).getBody();
        System.out.println(result.get("id")+"|"+result.get("name")+"|"+result.get("role"));
    } catch (SignatureException e){
        System.out.println("401 No Authentication");
    }
}
 
源代码30 项目: athenz   文件: InstanceProviderHandlerImpl.java
@Override
public InstanceConfirmation postRefreshConfirmation(ResourceContext context,
        InstanceConfirmation confirmation) {
    
    System.out.println("Processing postRefreshConfirmation...");
    System.out.println(JSON.string(confirmation));
    
    // our attestation data is jws so we're going to validate
    // the signature first to make sure that it was signed by us
    
    Jws<Claims> claims = null;
    try {
        claims = Jwts.parser().setSigningKey(providerKey)
            .parseClaimsJws(confirmation.getAttestationData());
    } catch (SignatureException e) {
        throw new ResourceException(ResourceException.UNAUTHORIZED);
    }
    
    // we're going to verify that issuer specified in jwt
    // is indeed ourselves
    
    final String provider = claims.getBody().getIssuer();
    if (!instanceProvider.equals(provider)) {
        throw new ResourceException(ResourceException.BAD_REQUEST,
                "Unknown provider: " + provider);
    }
    
    // we can do other validation possibly - maybe checking
    // with our manager service that the given instance
    // was indeed booted for the given domain and service
    // and it is still running
    
    return confirmation;
}
 
 类所在包
 类方法