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); } }
@Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { Collection<?> thisPrincipals = principals.fromRealm(getName()); if(thisPrincipals != null && !thisPrincipals.isEmpty()) { Optional<List<String>> scopes = thisPrincipals.stream().map(p -> { try { if(p.toString().split("\\.").length == 3) return getScopesFromToken(p.toString()); } catch(MalformedJwtException e) { //ignore } return null; }).filter(s -> s != null).findFirst(); if (scopes.isPresent()) return new SimpleAuthorizationInfo(Sets.newHashSet(scopes.get())); } return new SimpleAuthorizationInfo(); }
@Test(expected = MalformedJwtException.class) public void should_throw_MalformedJwtException_whet_pass_token_without_expiration_and_type() throws Exception { // Create payload Long userId = RandomUtils.nextLong(10, 1000); Set<Integer> actions = new HashSet<>(); actions.add(0); Set<String> networkIds = new HashSet<>(); networkIds.add("string"); Set<String> deviceTypeIds = new HashSet<>(); deviceTypeIds.add("string"); Set<String> deviceIds = new HashSet<>(); deviceIds.add("string"); JwtUserPayload.JwtUserPayloadBuilder jwtUserPayloadBuilder = new JwtUserPayload.JwtUserPayloadBuilder(); JwtUserPayload payload = jwtUserPayloadBuilder.withPublicClaims(userId, actions, networkIds, deviceTypeIds).buildPayload(); // Generate key without expiration date and token type Map<String, Object> jwtMap = new HashMap<>(); jwtMap.put(JwtUserPayload.JWT_CLAIM_KEY, payload); Claims claims = Jwts.claims(jwtMap); String malformedToken = Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.HS256, jwtSecretService.getJwtSecret()) .compact(); jwtClientService.getUserPayload(malformedToken); }
private JwtPayload getJwtPayload(JwtPayload.JwtPayloadBuilder jwtPayloadBuilder, LinkedHashMap<String, Object> payloadMap) { Optional<Long> expiration = Optional.ofNullable((Long)payloadMap.get(EXPIRATION)); Optional<Integer> tokenType = Optional.ofNullable((Integer) payloadMap.get(TOKEN_TYPE)); if (!tokenType.isPresent() && !expiration.isPresent()) { throw new MalformedJwtException("Token type and expiration date should be provided in the token"); } else { if (tokenType.isPresent()) jwtPayloadBuilder.withTokenType(tokenType.get()); else throw new MalformedJwtException("Token type should be provided in the token"); if (expiration.isPresent()) jwtPayloadBuilder.withExpirationDate(new Date(expiration.get())); else throw new MalformedJwtException("Expiration date should be provided in the token"); return jwtPayloadBuilder.buildPayload(); } }
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 testAuthenticateMalformedJwtException() throws Exception { final String token = "token"; doReturn(token).when(authentication).getCredentials(); doThrow(new MalformedJwtException(null)).when(jwtParser).parseClaimsJws(anyString()); exception.expect(BadCredentialsException.class); exception.expectCause(is(instanceOf(MalformedJwtException.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; }
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; }
private Map<String, Object> validateJwt(String token, ApiRequest request, JWTPolicyBean config) throws ExpiredJwtException, PrematureJwtException, MalformedJwtException, SignatureException, InvalidClaimException { JwtParser parser = Jwts.parser() .setSigningKey(config.getSigningKey()) .setAllowedClockSkewSeconds(config.getAllowedClockSkew()); // Set all claims config.getRequiredClaims().stream() // TODO add type variable to allow dates, etc .forEach(requiredClaim -> parser.require(requiredClaim.getClaimName(), requiredClaim.getClaimValue())); return parser.parse(token, new ConfigCheckingJwtHandler(config)); }
@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); }
@SuppressWarnings("unchecked") protected Map<String, Object> readValue(String val) { try { return objectMapper.readValue(val, Map.class); } catch (IOException e) { throw new MalformedJwtException("Unable to read JSON value: " + val, e); } }
@Test(expected = MalformedJwtException.class) public void getAuthenticationInvalidToken() { String invalidJwt = "invalidJwt"; this.tokenProvider.getAuthentication(invalidJwt); }
public PolicyFailure jwtMalformed(IPolicyContext context, MalformedJwtException e) { return createAuthenticationPolicyFailure(context, AUTH_JWT_MALFORMED, e.getLocalizedMessage()); }