Java Examples for org.jose4j.jwt.consumer.InvalidJwtException
The following java examples will help you to understand the usage of org.jose4j.jwt.consumer.InvalidJwtException. These source code samples are taken from different open source projects.
Example 1
| Project: teamcity-azure-active-directory-master File: JWT.java View source code |
/**
* @param jwtString Java Web Token string
* @return parsed Java Web Token
*/
@Nullable
public static JWT parse(@NotNull String jwtString) {
LOG.debug(String.format("Verifying JWT: %s", jwtString));
try {
JWTVerifier.Verify(jwtString);
} catch (InvalidJwtException e) {
LOG.warn("Failed to verify JWT from JWS payload " + jwtString, e);
return null;
}
final String[] jwtParts = jwtString.split(JWT_PARTS_DELIMITER);
if (jwtParts.length != 3) {
LOG.warn(String.format("JWT is malformed since consist of %d parts instead of required 3.", jwtParts.length));
return null;
}
final String jwsPayload = addPadding(jwtParts[1]);
final JsonElement jsonElement;
try {
final byte[] jwsPayloadBytes = jwsPayload.getBytes(UTF8);
jsonElement = new JsonParser().parse(new String(Base64.decodeBase64(jwsPayloadBytes)));
} catch (JsonSyntaxException e) {
LOG.warn("Failed to parse JWT from JWS payload " + jwsPayload, e);
return null;
} catch (JsonParseException e) {
LOG.warn("Failed to parse JWT from JWS payload " + jwsPayload, e);
return null;
} catch (UnsupportedEncodingException e) {
LOG.warn("Failed to parse JWT from JWS payload " + jwsPayload, e);
return null;
}
return new JWT(jsonElement.getAsJsonObject());
}Example 2
| Project: api-sdk-java-master File: OAuthTokenProvider.java View source code |
private static void logRefreshTokenDetails(final String refreshToken) {
JwtConsumer consumer = new JwtConsumerBuilder().setSkipAllDefaultValidators().setRequireExpirationTime().setSkipSignatureVerification().build();
try {
LOGGER.warn("Failed token info: " + consumer.process(refreshToken).getJwtClaims().getRawJson());
} catch (InvalidJwtException e) {
LOGGER.warn("Failed to parse refresh token:", e);
}
}Example 3
| Project: strongbox-master File: SecurityTokenProvider.java View source code |
private JwtClaims getClimes(String token) {
JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireSubject().setVerificationKey(key).setRelaxVerificationKeyValidation().build();
JwtClaims jwtClaims;
try {
jwtClaims = jwtConsumer.processToClaims(token);
} catch (InvalidJwtException e) {
throw new SecurityTokenException(String.format(MESSAGE_INVALID_JWT, token), e);
}
return jwtClaims;
}Example 4
| Project: Opentok-Java-SDK-master File: Helpers.java View source code |
private static Map<String, Object> getClaims(final String token, final Integer apiKey, final String apiSecret) throws InvalidJwtException {
final SecretKeySpec key = new SecretKeySpec(apiSecret.getBytes(), AlgorithmIdentifiers.HMAC_SHA256);
final JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(30).setExpectedIssuer(apiKey.toString()).setVerificationKey(key).build();
return jwtConsumer.processToClaims(token).getClaimsMap();
}Example 5
| Project: git-as-svn-master File: TokenHelper.java View source code |
@Nullable
public static User parseToken(@NotNull JsonWebEncryption jwe, @NotNull String token, int tokenEnsureTime) {
try {
jwe.setCompactSerialization(token);
final JwtClaims claims = JwtClaims.parse(jwe.getPayload());
final NumericDate now = NumericDate.now();
final NumericDate expire = NumericDate.fromMilliseconds(now.getValueInMillis());
if (tokenEnsureTime > 0) {
expire.addSeconds(tokenEnsureTime);
}
if (claims.getExpirationTime() == null || claims.getExpirationTime().isBefore(expire)) {
return null;
}
if (claims.getNotBefore() == null || claims.getNotBefore().isAfter(now)) {
return null;
}
if (claims.getSubject() == null) {
return User.getAnonymous();
}
return User.create(claims.getSubject(), claims.getClaimValue("name", String.class), claims.getClaimValue("email", String.class), claims.getClaimValue("external", String.class));
} catch (JoseExceptionMalformedClaimException | InvalidJwtException | e) {
log.warn("Token parsing error: " + e.getMessage());
return null;
}
}Example 6
| Project: service-proxy-master File: OAuth2AuthorizationServerInterceptorOpenidTest.java View source code |
private static boolean idTokenIsValid(Response response) throws IOException, ParseException {
// TODO: currently only checks if signature is valid -> also check if requested claims are in it
HashMap<String, String> json = Util.parseSimpleJSONResponse(response);
try {
oasi.getJwtGenerator().getClaimsFromSignedIdToken(json.get(ParamNames.ID_TOKEN), oasi.getIssuer(), "abc");
return true;
} catch (InvalidJwtException e) {
return false;
}
}Example 7
| Project: dropwizard-auth-jwt-master File: JwtAuthFilter.java View source code |
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
final Optional<String> optionalToken = getTokenFromCookieOrHeader(requestContext);
if (optionalToken.isPresent()) {
try {
final JwtContext jwtContext = verifyToken(optionalToken.get());
final Optional<P> principal = authenticator.authenticate(jwtContext);
if (principal.isPresent()) {
requestContext.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return principal.get();
}
@Override
public boolean isUserInRole(String role) {
return authorizer.authorize(principal.get(), role);
}
@Override
public boolean isSecure() {
return requestContext.getSecurityContext().isSecure();
}
@Override
public String getAuthenticationScheme() {
return SecurityContext.BASIC_AUTH;
}
});
return;
}
} catch (InvalidJwtException ex) {
LOGGER.warn("Error decoding credentials: " + ex.getMessage(), ex);
} catch (AuthenticationException ex) {
LOGGER.warn("Error authenticating credentials", ex);
throw new InternalServerErrorException();
}
}
throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm));
}Example 8
| Project: kylo-master File: JwtRememberMeServices.java View source code |
/**
* Decodes the specified JWT cookie into tokens.
*
* <p>The first element of the return value with be the JWT subject. The remaining elements are the elements in the {@code groups} list.</p>
*
* @param cookie the JWT cookie
* @return an array with the username and group names
* @throws IllegalStateException if the secret key is invalid
* @throws InvalidCookieException if the cookie cannot be decoded
*/
@Nonnull
@Override
protected String[] decodeCookie(@Nonnull final String cookie) throws InvalidCookieException {
// Build the JWT parser
final JwtConsumer consumer = new JwtConsumerBuilder().setEvaluationTime(NumericDate.fromMilliseconds(DateTimeUtils.currentTimeMillis())).setVerificationKey(getSecretKey()).build();
// Parse the cookie
final String user;
final List<String> groups;
try {
final JwtClaims claims = consumer.processToClaims(cookie);
user = claims.getSubject();
groups = claims.getStringListClaimValue(GROUPS);
} catch (final InvalidJwtException e) {
throw new InvalidCookieException("JWT cookie is invalid: " + e);
} catch (final MalformedClaimException e) {
throw new InvalidCookieException("JWT cookie is malformed: " + cookie);
}
if (StringUtils.isBlank(user)) {
throw new InvalidCookieException("Missing user in JWT cookie: " + cookie);
}
// Build the token array
final Stream<String> userStream = Stream.of(user);
final Stream<String> groupStream = groups.stream();
return Stream.concat(userStream, groupStream).toArray(String[]::new);
}Example 9
| Project: genie-master File: PingFederateJWTTokenServicesUnitTests.java View source code |
/**
* Make sure we can successfully load an authentication.
*
* @throws AuthenticationException On error
* @throws InvalidTokenException When the token is invalid
* @throws InvalidJwtException On invalid JWT token
* @throws MalformedClaimException A bad claim
*/
@Test
public void canLoadAuthentication() throws AuthenticationException, InvalidTokenException, InvalidJwtException, MalformedClaimException {
final JwtClaims claims = Mockito.mock(JwtClaims.class);
final String clientId = UUID.randomUUID().toString();
final String scope1 = "genie_admin";
final String scope2 = UUID.randomUUID().toString();
final Set<String> scopes = Sets.newHashSet(scope1, scope2);
Mockito.when(claims.getClaimValue("client_id", String.class)).thenReturn(clientId);
Mockito.when(claims.getClaimValue("scope", Collection.class)).thenReturn(scopes);
Mockito.when(this.jwtConsumer.processToClaims(Mockito.anyString())).thenReturn(claims);
final OAuth2Authentication authentication = this.tokenServices.loadAuthentication(UUID.randomUUID().toString());
Assert.assertNull(authentication.getUserAuthentication());
Assert.assertThat(authentication.getPrincipal(), Matchers.is(clientId));
final Collection<GrantedAuthority> authorities = authentication.getAuthorities();
Assert.assertThat(authorities.size(), Matchers.is(3));
Assert.assertTrue(authorities.containsAll(Sets.newHashSet(new SimpleGrantedAuthority("ROLE_ADMIN"), new SimpleGrantedAuthority("ROLE_" + scope2.toUpperCase()), new SimpleGrantedAuthority("ROLE_USER"))));
Mockito.verify(this.loadAuthenticationTimer, Mockito.times(1)).record(Mockito.anyLong(), Mockito.eq(TimeUnit.NANOSECONDS));
}Example 10
| Project: light-4j-master File: JwtHelper.java View source code |
public static JwtClaims verifyJwt(String jwt) throws InvalidJwtException, ExpiredTokenException { JwtClaims claims; JwtConsumer consumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build(); JwtContext jwtContext = consumer.process(jwt); JwtClaims jwtClaims = jwtContext.getJwtClaims(); JsonWebStructure structure = jwtContext.getJoseObjects().get(0); String kid = structure.getKeyIdHeaderValue(); int secondsOfAllowedClockSkew = 30; try { if ((NumericDate.now().getValue() - secondsOfAllowedClockSkew) >= jwtClaims.getExpirationTime().getValue()) { logger.info("jwt token is expired!"); throw new ExpiredTokenException("Token is expired"); } } catch (MalformedClaimException e) { logger.error("MalformedClaimException:", e); throw new InvalidJwtException("MalformedClaimException", e); } X509VerificationKeyResolver x509VerificationKeyResolver = new X509VerificationKeyResolver(certMap.get(kid)); x509VerificationKeyResolver.setTryAllOnNoThumbHeader(true); consumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds((Integer) securityJwtConfig.get(JwT_CLOCK_SKEW_IN_SECONDS)).setSkipDefaultAudienceValidation().setVerificationKeyResolver(x509VerificationKeyResolver).build(); // Validate the JWT and process it to the Claims jwtContext = consumer.process(jwt); claims = jwtContext.getJwtClaims(); return claims; }