Java Code Examples for com.nimbusds.jwt.SignedJWT#getJWTClaimsSet()
The following examples show how to use
com.nimbusds.jwt.SignedJWT#getJWTClaimsSet() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ScooldUtils.java From scoold with Apache License 2.0 | 7 votes |
public boolean isValidJWToken(String jwt) { try { String secret = Config.getConfigParam("app_secret_key", ""); if (secret != null && jwt != null) { JWSVerifier verifier = new MACVerifier(secret); SignedJWT sjwt = SignedJWT.parse(jwt); if (sjwt.verify(verifier)) { Date referenceTime = new Date(); JWTClaimsSet claims = sjwt.getJWTClaimsSet(); Date expirationTime = claims.getExpirationTime(); Date notBeforeTime = claims.getNotBeforeTime(); String jti = claims.getJWTID(); boolean expired = expirationTime != null && expirationTime.before(referenceTime); boolean notYetValid = notBeforeTime != null && notBeforeTime.after(referenceTime); boolean jtiRevoked = isApiKeyRevoked(jti, expired); return !(expired || notYetValid || jtiRevoked); } } } catch (JOSEException e) { logger.warn(null, e); } catch (ParseException ex) { logger.warn(null, ex); } return false; }
Example 2
Source File: SelfContainedTokenValidator.java From cellery-security with Apache License 2.0 | 6 votes |
/** * Validates a self contained access security. * * @param token Incoming security. JWT to be validated. * @param cellStsRequest Request which reaches cell STS. * @throws TokenValidationFailureException TokenValidationFailureException. */ @Override public void validateToken(String token, CellStsRequest cellStsRequest) throws TokenValidationFailureException { if (StringUtils.isEmpty(token)) { throw new TokenValidationFailureException("No token found in the request."); } try { log.debug("Validating token: {}", token); SignedJWT parsedJWT = SignedJWT.parse(token); JWTClaimsSet jwtClaimsSet = parsedJWT.getJWTClaimsSet(); validateIssuer(jwtClaimsSet, cellStsRequest); validateAudience(jwtClaimsSet, cellStsRequest); validateExpiry(jwtClaimsSet); validateSignature(parsedJWT, cellStsRequest); } catch (ParseException e) { throw new TokenValidationFailureException("Error while parsing JWT: " + token, e); } }
Example 3
Source File: KnoxService.java From nifi with Apache License 2.0 | 6 votes |
/** * Validate the jwt expiration. * * @param jwtToken knox jwt * @return whether this jwt is not expired * @throws ParseException if the payload of the jwt doesn't represent a valid json object and a jwt claims set */ private boolean validateExpiration(final SignedJWT jwtToken) throws ParseException { boolean valid = false; final JWTClaimsSet claimsSet = jwtToken.getJWTClaimsSet(); if (claimsSet == null) { logger.error("Claims set is missing from Knox JWT."); return false; } final Date now = new Date(); final Date expiration = claimsSet.getExpirationTime(); // the token is not expired if the expiration isn't present or the expiration is after now if (expiration == null || now.before(expiration)) { valid = true; } if (!valid) { logger.error("The Knox JWT is expired."); } return valid; }
Example 4
Source File: KnoxService.java From nifi with Apache License 2.0 | 6 votes |
/** * Extracts the authentication from the token and verify it. * * @param jwt signed jwt string * @return the user authentication * @throws ParseException if the payload of the jwt doesn't represent a valid json object and a jwt claims set * @throws JOSEException if the JWS object couldn't be verified */ public String getAuthenticationFromToken(final String jwt) throws ParseException, JOSEException { if (!configuration.isKnoxEnabled()) { throw new IllegalStateException("Apache Knox SSO is not enabled."); } // attempt to parse the signed jwt final SignedJWT signedJwt = SignedJWT.parse(jwt); // validate the token if (validateToken(signedJwt)) { final JWTClaimsSet claimsSet = signedJwt.getJWTClaimsSet(); if (claimsSet == null) { logger.info("Claims set is missing from Knox JWT."); throw new InvalidAuthenticationException("The Knox JWT token is not valid."); } // extract the user identity from the token return claimsSet.getSubject(); } else { throw new InvalidAuthenticationException("The Knox JWT token is not valid."); } }
Example 5
Source File: SecurityUtils.java From para with Apache License 2.0 | 6 votes |
/** * Validates a JWT token. * @param secret secret used for generating the token * @param jwt token to validate * @return true if token is valid */ public static boolean isValidJWToken(String secret, SignedJWT jwt) { try { if (secret != null && jwt != null) { JWSVerifier verifier = new MACVerifier(secret); if (jwt.verify(verifier)) { Date referenceTime = new Date(); JWTClaimsSet claims = jwt.getJWTClaimsSet(); Date expirationTime = claims.getExpirationTime(); Date notBeforeTime = claims.getNotBeforeTime(); boolean expired = expirationTime == null || expirationTime.before(referenceTime); boolean notYetValid = notBeforeTime != null && notBeforeTime.after(referenceTime); return !(expired || notYetValid); } } } catch (JOSEException e) { logger.warn(null, e); } catch (ParseException ex) { logger.warn(null, ex); } return false; }
Example 6
Source File: MACVerifierExtendedTest.java From shiro-jwt with MIT License | 6 votes |
@Test public void invalidTokenExpirationTime() throws JOSEException, ParseException { JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date()); JWSHeader header = new JWSHeader(JWSAlgorithm.HS256); Payload payload = new Payload(jwtClaims.toJSONObject()); JWSObject jwsObject = new JWSObject(header, payload); JWSSigner signer = new MACSigner(sharedKey); jwsObject.sign(signer); String token = jwsObject.serialize(); SignedJWT signed = SignedJWT.parse(token); JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet()); signed.verify(verifier); Assert.assertFalse("Must be invalid", signed.verify(verifier)); }
Example 7
Source File: MACVerifierExtendedTest.java From shiro-jwt with MIT License | 6 votes |
@Test public void invalidTokenNotBeforeTime() throws JOSEException, ParseException { JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(new Date().getTime() + 100000), new Date(new Date().getTime() + 200000)); JWSHeader header = new JWSHeader(JWSAlgorithm.HS256); Payload payload = new Payload(jwtClaims.toJSONObject()); JWSObject jwsObject = new JWSObject(header, payload); JWSSigner signer = new MACSigner(sharedKey); jwsObject.sign(signer); String token = jwsObject.serialize(); SignedJWT signed = SignedJWT.parse(token); JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet()); signed.verify(verifier); Assert.assertFalse("Must be invalid", signed.verify(verifier)); }
Example 8
Source File: MACVerifierExtendedTest.java From shiro-jwt with MIT License | 6 votes |
@Test public void validToken() throws JOSEException, ParseException { JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date(new Date().getTime() + 100000)); JWSHeader header = new JWSHeader(JWSAlgorithm.HS256); Payload payload = new Payload(jwtClaims.toJSONObject()); JWSObject jwsObject = new JWSObject(header, payload); JWSSigner signer = new MACSigner(sharedKey); jwsObject.sign(signer); String token = jwsObject.serialize(); SignedJWT signed = SignedJWT.parse(token); JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet()); signed.verify(verifier); Assert.assertTrue("Must be valid", signed.verify(verifier)); }
Example 9
Source File: CustomJWTClaimsInterceptor.java From msf4j with Apache License 2.0 | 6 votes |
@Override public boolean interceptRequest(Request request, Response response) throws Exception { HttpHeaders headers = request.getHeaders(); if (headers != null) { String jwtHeader = headers.getHeaderString(JWT_HEADER); if (jwtHeader != null) { SignedJWT signedJWT = SignedJWT.parse(jwtHeader); ReadOnlyJWTClaimsSet readOnlyJWTClaimsSet = signedJWT.getJWTClaimsSet(); if (readOnlyJWTClaimsSet != null) { // Do something with claims return true; } } } response.setHeader(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE, AUTH_TYPE_JWT); response.setStatus(javax.ws.rs.core.Response.Status.UNAUTHORIZED.getStatusCode()); return false; }
Example 10
Source File: CellerySignedJWTValidator.java From cellery-security with Apache License 2.0 | 6 votes |
private boolean isSignedJWTValid(SignedJWT signedJWT) throws IdentityOAuth2Exception { try { JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet(); if (claimsSet == null) { throw new IdentityOAuth2Exception("Claim values are empty in the validated JWT."); } else { validateMandatoryJWTClaims(claimsSet); validateConsumerKey(claimsSet); validateExpiryTime(claimsSet); validateNotBeforeTime(claimsSet); validateAudience(claimsSet); IdentityProvider trustedIdp = getTrustedIdp(claimsSet); return Utils.validateSignature(signedJWT, trustedIdp); } } catch (ParseException ex) { throw new IdentityOAuth2Exception("Error while validating JWT.", ex); } }
Example 11
Source File: JwtLoginService.java From cruise-control with BSD 2-Clause "Simplified" License | 5 votes |
@Override public UserIdentity login(String username, Object credentials, ServletRequest request) { if (!(credentials instanceof SignedJWT)) { return null; } if (!(request instanceof HttpServletRequest)) { return null; } SignedJWT jwtToken = (SignedJWT) credentials; JWTClaimsSet claimsSet; boolean valid; try { claimsSet = jwtToken.getJWTClaimsSet(); valid = validateToken(jwtToken, claimsSet, username); } catch (ParseException e) { JWT_LOGGER.warn(String.format("%s: Couldn't parse a JWT token", username), e); return null; } if (valid) { String serializedToken = (String) request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE); UserIdentity rolesDelegate = _authorizationService.getUserIdentity((HttpServletRequest) request, username); if (rolesDelegate == null) { return null; } else { return getUserIdentity(jwtToken, claimsSet, serializedToken, username, rolesDelegate); } } else { return null; } }
Example 12
Source File: ExtendedJWTBearerGrantHandler.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Method to retrieve claims from the JWT * @param signedJWT JWT token * @return JWTClaimsSet Object */ private JWTClaimsSet getClaimSet(SignedJWT signedJWT) { JWTClaimsSet claimsSet = null; try { claimsSet = signedJWT.getJWTClaimsSet(); } catch (ParseException e) { log.error("Error when trying to retrieve claimsSet from the JWT:", e); } return claimsSet; }
Example 13
Source File: SampleActivity.java From PoyntSamples with MIT License | 5 votes |
@Override public void run(AccountManagerFuture<Bundle> result) { try { if (progress != null) { progress.dismiss(); } Bundle bundle = result.getResult(); Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT); if (launch != null) { Log.d("TransactionTestActivity", "received intent to login"); startActivityForResult(launch, AUTHORIZATION_CODE); } else { Log.d("TransactionTestActivity", "token user:" + bundle.get(AccountManager.KEY_ACCOUNT_NAME)); accessToken = bundle .getString(AccountManager.KEY_AUTHTOKEN); Log.d("TransactionTestActivity", "received token result: " + accessToken); // display the claims in the screen SignedJWT signedJWT = SignedJWT.parse(accessToken); StringBuilder claimsStr = new StringBuilder(); ReadOnlyJWTClaimsSet claims = signedJWT.getJWTClaimsSet(); claimsStr.append("Subject: " + claims.getSubject()); claimsStr.append(", Type: " + claims.getType()); claimsStr.append(", Issuer: " + claims.getIssuer()); claimsStr.append(", JWT ID: " + claims.getJWTID()); claimsStr.append(", IssueTime : " + claims.getIssueTime()); claimsStr.append(", Expiration Time: " + claims.getExpirationTime()); claimsStr.append(", Not Before Time: " + claims.getNotBeforeTime()); Map<String, Object> customClaims = claims.getCustomClaims(); for (Map.Entry<String, Object> entry : customClaims.entrySet()) { claimsStr.append(", " + entry.getKey() + ": " + entry.getValue()); } tokenInfo.setText(claimsStr.toString()); } } catch (Exception e) { Log.d("TransactionTestActivity", "Exception received: " + e.getMessage()); } }
Example 14
Source File: CellerySignedJWTValidator.java From cellery-security with Apache License 2.0 | 5 votes |
@Override public boolean validateAccessToken(OAuth2TokenValidationMessageContext validationContext) throws IdentityOAuth2Exception { // validate mandatory attributes String accessToken = getAccessTokenIdentifier(validationContext); try { SignedJWT signedJWT = SignedJWT.parse(accessToken); boolean signedJWTValid = isSignedJWTValid(signedJWT); if (signedJWTValid) { JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet(); // These two properties are set to avoid token lookup from the database in the case of signed JWTs // issued by external IDPs. validationContext.addProperty(OAuth2Util.REMOTE_ACCESS_TOKEN, Boolean.TRUE); validationContext.addProperty(OAuth2Util.JWT_ACCESS_TOKEN, Boolean.TRUE); validationContext.addProperty(OAuth2Util.IAT, String.valueOf(getTimeInSeconds(claimsSet.getIssueTime()))); validationContext.addProperty(OAuth2Util.EXP, String.valueOf(getTimeInSeconds(claimsSet.getExpirationTime()))); validationContext.addProperty(OAuth2Util.CLIENT_ID, claimsSet.getClaim(CONSUMER_KEY)); validationContext.addProperty(OAuth2Util.SUB, claimsSet.getSubject()); validationContext.addProperty(OAuth2Util.SCOPE, claimsSet.getClaim(OAuth2Util.SCOPE)); validationContext.addProperty(OAuth2Util.ISS, claimsSet.getIssuer()); validationContext.addProperty(OAuth2Util.JTI, claimsSet.getJWTID()); } return signedJWTValid; } catch (ParseException e) { throw new IdentityOAuth2Exception("Error validating signed jwt.", e); } }
Example 15
Source File: KnoxService.java From nifi with Apache License 2.0 | 5 votes |
/** * Validate the jwt audience. * * @param jwtToken knox jwt * @return whether this jwt audience is valid * @throws ParseException if the payload of the jwt doesn't represent a valid json object and a jwt claims set */ private boolean validateAudience(final SignedJWT jwtToken) throws ParseException { if (audiences == null) { return true; } final JWTClaimsSet claimsSet = jwtToken.getJWTClaimsSet(); if (claimsSet == null) { logger.error("Claims set is missing from Knox JWT."); return false; } final List<String> tokenAudiences = claimsSet.getAudience(); if (tokenAudiences == null) { logger.error("Audience is missing from the Knox JWT."); return false; } boolean valid = false; for (final String tokenAudience : tokenAudiences) { // ensure one of the audiences is matched if (audiences.contains(tokenAudience)) { valid = true; break; } } if (!valid) { logger.error(String.format("The Knox JWT does not have the required audience(s). Required one of [%s]. Present in JWT [%s].", StringUtils.join(audiences, ", "), StringUtils.join(tokenAudiences, ", "))); } return valid; }
Example 16
Source File: AuthUtils.java From blog with MIT License | 5 votes |
public static ReadOnlyJWTClaimsSet decodeToken(String authHeader) throws ParseException, JOSEException { SignedJWT signedJWT = SignedJWT.parse(getSerializedToken(authHeader)); if (signedJWT.verify(new MACVerifier(TOKEN_SECRET))) { return signedJWT.getJWTClaimsSet(); } else { throw new JOSEException("Signature verification failed"); } }
Example 17
Source File: LoginActivity.java From PoyntSamples with MIT License | 4 votes |
private void displayAccessTokenInfo(String accessToken) { try { SignedJWT signedJWT = SignedJWT.parse(accessToken); StringBuilder claimsBuffer = new StringBuilder(); ReadOnlyJWTClaimsSet claims = signedJWT.getJWTClaimsSet(); claimsBuffer.append("Subject: " + claims.getSubject()) .append("\nType: " + claims.getType()) .append("\nIssuer: " + claims.getIssuer()) .append("\nJWT ID: " + claims.getJWTID()) .append("\nIssueTime : " + claims.getIssueTime()) .append("\nExpiration Time: " + claims.getExpirationTime()) .append("\nNot Before Time: " + claims.getNotBeforeTime()); for (String audience : claims.getAudience()) { claimsBuffer.append("\nAudience: " + audience); } Map<String, Object> customClaims = claims.getCustomClaims(); for (Map.Entry<String, Object> entry : customClaims.entrySet()) { String key = entry.getKey(); switch (key) { case "poynt.did": key += " (Device ID)"; break; case "poynt.biz": key += " (Business ID)"; break; case "poynt.ist": key += " (Issued To)"; break; case "poynt.sct": key += " (Subject Credential Type [J=JWT, E=EMAIL, U=USERNAME])"; break; case "poynt.str": key += " (Store ID)"; break; case "poynt.kid": key += " (Key ID)"; break; case "poynt.ure": key += " (User Role [O=Owner, E=Employee])"; break; case "poynt.uid": key += " (Poynt User ID)"; break; case "poynt.scv": key += " (Subject Credential Value)"; break; default: break; } claimsBuffer.append("\n" + key + ": " + entry.getValue()); } final String claimsStr = claimsBuffer.toString(); Log.d(TAG, "claims: " + claimsStr); consoleText.setText(claimsStr); } catch (ParseException e) { e.printStackTrace(); } }
Example 18
Source File: DefaultConsentReferencePolicy.java From XS2A-Sandbox with Apache License 2.0 | 4 votes |
@SuppressWarnings("PMD") private ConsentReference verifyParseJWT(String encryptedConsentId, String authorizationId, String cookieString, boolean strict) { Date refTime = new Date(); try { SignedJWT jwt = SignedJWT.parse(cookieString); JWTClaimsSet jwtClaimsSet = jwt.getJWTClaimsSet(); // Validate xsrf Object authorizationIdClaim = jwtClaimsSet.getClaim(AUTH_ID_JWT_CLAIM_NAME); if (strict && authorizationIdClaim == null) { throw invalidConsent(String.format("Wrong jwt. CSRF allert. Missing claim %s for jwt with redirectId %s", AUTH_ID_JWT_CLAIM_NAME, jwtClaimsSet.getClaim(REDIRECT_ID_JWT_CLAIM_NAME))); } if (authorizationIdClaim != null && !StringUtils.equalsIgnoreCase(authorizationIdClaim.toString(), authorizationId)) { throw invalidConsent(String.format("Wrong jwt. CSRF allert. Wrong %s for token with redirectId %s", AUTH_ID_JWT_CLAIM_NAME, jwtClaimsSet.getClaim(REDIRECT_ID_JWT_CLAIM_NAME))); } Object encryptedConsentIdClaim = jwtClaimsSet.getClaim(ENC_CONSENT_ID_JWT_CLAIM_NAME); if (encryptedConsentIdClaim == null || !StringUtils.equalsIgnoreCase(encryptedConsentIdClaim.toString(), encryptedConsentId)) { throw invalidConsent(String.format("Wrong jwt. CSRF allert. Wrong %s for token with redirectId %s", ENC_CONSENT_ID_JWT_CLAIM_NAME, jwtClaimsSet.getClaim(REDIRECT_ID_JWT_CLAIM_NAME))); } JWSHeader header = jwt.getHeader(); // CHeck algorithm if (!JWSAlgorithm.HS256.equals(header.getAlgorithm())) { throw invalidConsent(String.format("Wrong jws algo for token with subject : %s", jwtClaimsSet.getSubject())); } // CHeck expiration if (jwtClaimsSet.getExpirationTime() == null || jwtClaimsSet.getExpirationTime().before(refTime)) { throw invalidConsent(String.format( "Token with subject %s is expired at %s and reference time is %s : ", jwtClaimsSet.getSubject(), jwtClaimsSet.getExpirationTime(), refTime)); } // check signature. boolean verified = jwt.verify(new MACVerifier(hmacSecret)); if (!verified) { throw invalidConsent(String.format("Could not verify signature of token with subject %s: ", jwtClaimsSet.getSubject())); } return consentReference(encryptedConsentId, authorizationId, jwtClaimsSet); } catch (ParseException | JOSEException e) { // If we can not parse the token, we log the error and return false. throw invalidConsent(e.getMessage()); } }