public static boolean Verify(String jwt, String type) throws Exception { try{ Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY)) .parseClaimsJws(jwt).getBody(); //verifica se o issuer é igual ao type return claims.getIssuer().equals(type); } catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) { System.out.println(e.getMessage()); return false; } }
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); } }
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; }
/** * 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); } }
@Override public Authentication authenticate(Authentication authentication) { log.debug("Authenticating: {}", authentication); try { final String token = authentication.getCredentials().toString(); final Claims claims = jwtParser.parseClaimsJws(token).getBody(); checkClaims(claims); return new JwtToken(token, claims); } catch (ExpiredJwtException | MalformedJwtException | PrematureJwtException | SignatureException | UnsupportedJwtException e) { log.warn("{}", e); throw new BadCredentialsException(e.getMessage(), e); } }
@Test public void testAuthenticateUnsupportedJwtException() throws Exception { final String token = "token"; doReturn(token).when(authentication).getCredentials(); doThrow(new UnsupportedJwtException(null)).when(jwtParser).parseClaimsJws(anyString()); exception.expect(BadCredentialsException.class); exception.expectCause(is(instanceOf(UnsupportedJwtException.class))); jwtAuthenticationProvider.authenticate(authentication); }
private String getUsernameFromToken(String authToken) { String username = null; try { username = jwtTokenService.getUsernameFromToken(authToken); } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { log.error("getUsernameFromToken error, token was malformed: {}", authToken, e); } return username; }
@Override public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) { final SignatureAlgorithm inputAlgorithm = SignatureAlgorithm.forName(header.getAlgorithm()); if (!this.requiredAlgorithm.equals(inputAlgorithm)) { throw new UnsupportedJwtException("Invalid algorithm"); } return signatureKey; }
private Optional<Jws<Claims>> parseToken(final String token) { Optional<Jws<Claims>> result = Optional.empty(); if (Objects.nonNull(token)) { try { result = Optional.ofNullable(Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token)); } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { log.warn(e.getMessage()); } } return result; }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) { throw new NotAuthorizedException("Authorization header must be provided"); } String token = authorizationHeader.substring("Bearer".length()).trim(); try { Role userRole = Role.valueOf(TokenServices.validateToken(token)); List<Role> classRoles = extractRoles(resourceInfo.getResourceClass()); List<Role> methodRoles = extractRoles(resourceInfo.getResourceMethod()); if (methodRoles.size() > 0) { if (!methodRoles.contains(userRole)) { requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).build()); } } if (classRoles.size() > 0) { if (!classRoles.contains(userRole)) { requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).build()); } } } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build()); } }
public static String validateToken(String token)throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException { Claims claims = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token).getBody(); String role = null; role = claims.get("role").toString(); Jwts.parser() .requireSubject(claims.getSubject()) .setSigningKey(signingKey) .parseClaimsJws(token); return role; }
@Test public void testJwt() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException, CertificateException { Claims testClaims = Jwts.claims(); testClaims.put("aud", "test"); String newJwt = Jwts.builder().setHeaderParam("kid", "test").setClaims(testClaims) .signWith(SignatureAlgorithm.RS256, getKey()).compact(); assertNotNull("could not build jwt using test certificate",newJwt); Jws<Claims> jwt = Jwts.parser().setSigningKey(getCertificate().getPublicKey()).parseClaimsJws(newJwt); assertNotNull("could not decode jwt using test certificate",jwt); }
@Override public Jwt<Header, Claims> parseClaimsJwt(String claimsJwt) { try { return parse(claimsJwt, new JwtHandlerAdapter<Jwt<Header, Claims>>() { @Override public Jwt<Header, Claims> onClaimsJwt(Jwt<Header, Claims> jwt) { return jwt; } }); } catch (IllegalArgumentException iae) { throw new UnsupportedJwtException("Signed JWSs are not supported.", iae); } }
@Override public Jws<String> parsePlaintextJws(String plaintextJws) { try { return parse(plaintextJws, new JwtHandlerAdapter<Jws<String>>() { @Override public Jws<String> onPlaintextJws(Jws<String> jws) { return jws; } }); } catch (IllegalArgumentException iae) { throw new UnsupportedJwtException("Signed JWSs are not supported.", iae); } }
public PolicyFailure unsupportedJwt(IPolicyContext context, UnsupportedJwtException e) { return createAuthenticationPolicyFailure(context, AUTH_JWT_UNSUPPORTED_JWT, Messages.getString("JWTPolicy.NoTransportSecurity")); //$NON-NLS-1$ }