Java Code Examples for com.nimbusds.jwt.JWTClaimsSet#getClaim()
The following examples show how to use
com.nimbusds.jwt.JWTClaimsSet#getClaim() .
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: JWTValidatorImpl.java From carbon-apimgt with Apache License 2.0 | 6 votes |
private void createJWTValidationInfoFromJWT(JWTValidationInfo jwtValidationInfo, JWTClaimsSet jwtClaimsSet) throws ParseException { jwtValidationInfo.setIssuer(jwtClaimsSet.getIssuer()); jwtValidationInfo.setValid(true); jwtValidationInfo.setClaims(jwtClaimsSet.getClaims()); jwtValidationInfo.setExpiryTime(jwtClaimsSet.getExpirationTime().getTime()); jwtValidationInfo.setIssuedTime(jwtClaimsSet.getIssueTime().getTime()); jwtValidationInfo.setUser(jwtClaimsSet.getSubject()); jwtValidationInfo.setJti(jwtClaimsSet.getJWTID()); if(jwtClaimsSet.getClaim(APIConstants.JwtTokenConstants.SCOPE) != null){ jwtValidationInfo.setScopes(Arrays.asList(jwtClaimsSet.getStringClaim(APIConstants.JwtTokenConstants.SCOPE) .split(APIConstants.JwtTokenConstants.SCOPE_DELIMITER))); } }
Example 2
Source File: DefaultJWTTransformer.java From carbon-apimgt with Apache License 2.0 | 6 votes |
@Override public String getTransformedConsumerKey(JWTClaimsSet jwtClaimsSet) throws APIManagementException { try { if (tokenIssuer.getConsumerKeyClaim() == null) { if (jwtClaimsSet.getClaim(APIConstants.JwtTokenConstants.CONSUMER_KEY) != null) { return jwtClaimsSet.getStringClaim(APIConstants.JwtTokenConstants.CONSUMER_KEY); } else if (jwtClaimsSet.getClaim(APIConstants.JwtTokenConstants.AUTHORIZED_PARTY) != null) { return jwtClaimsSet.getStringClaim(APIConstants.JwtTokenConstants.AUTHORIZED_PARTY); } } else { if (jwtClaimsSet.getClaim(tokenIssuer.getConsumerKeyClaim()) != null) { return jwtClaimsSet.getStringClaim(tokenIssuer.getConsumerKeyClaim()); } } } catch (ParseException e) { throw new APIManagementException("Error while parsing JWT claims", e); } return null; }
Example 3
Source File: DefaultJWTTransformer.java From carbon-apimgt with Apache License 2.0 | 6 votes |
@Override public List<String> getTransformedScopes(JWTClaimsSet jwtClaimsSet) throws APIManagementException { try { String scopeClaim = APIConstants.JwtTokenConstants.SCOPE; if (StringUtils.isNotEmpty(tokenIssuer.getScopesClaim())){ scopeClaim = tokenIssuer.getScopesClaim(); } if (jwtClaimsSet.getClaim(scopeClaim) instanceof String) { return Arrays.asList(jwtClaimsSet.getStringClaim(scopeClaim) .split(APIConstants.JwtTokenConstants.SCOPE_DELIMITER)); } else if (jwtClaimsSet.getClaim(scopeClaim) instanceof List) { return jwtClaimsSet.getStringListClaim(scopeClaim); } } catch (ParseException e) { throw new APIManagementException("Error while parsing JWT claims", e); } return Arrays.asList(APIConstants.OAUTH2_DEFAULT_SCOPE); }
Example 4
Source File: SelfContainedTokenValidator.java From cellery-security with Apache License 2.0 | 5 votes |
private boolean isReqAddressedToComposite(JWTClaimsSet claimsSet, CellStsRequest request) { String destination = (String) claimsSet.getClaim(Constants.DESTINATION); log.debug("Destination of the jwt is : " + destination); log.debug("Destination derived from request : " + request.getDestination().getWorkload()); if (!CellStsUtils.isCompositeSTS()) { log.debug("Not composite STS. Hence audience has to be validated with proper cell name."); return false; } log.debug("Composite STS checking whether the incoming jwt is addressed towards composite"); if (StringUtils.equals(destination, request.getDestination().getWorkload())) { // Request has reached to the intended service in composite. Hence not validating audience log.debug("Destination found in the token matches with the actual destination. Hence audience is valid " + "for composite."); return true; } if (StringUtils.isBlank(destination) && globalIssuer.equalsIgnoreCase(claimsSet.getIssuer())) { // Assumes the request is from global gateway. log.debug("Destination is not available and the issuer is global. Hence audience is considered as valid " + "by composite STS."); return true; } log.debug("Request is not addressed towards composite STS"); return false; }
Example 5
Source File: CellerySignedJWTValidator.java From cellery-security with Apache License 2.0 | 5 votes |
private void validateConsumerKey(JWTClaimsSet claimsSet) throws IdentityOAuth2Exception { String consumerKey = (String) claimsSet.getClaim(CONSUMER_KEY); if (StringUtils.isNotBlank(consumerKey)) { try { OAuth2Util.getAppInformationByClientId(consumerKey); } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) { throw new IdentityOAuth2Exception("Invalid consumerKey. Cannot find a registered app for consumerKey: " + consumerKey); } } else { throw new IdentityOAuth2Exception("Mandatory claim 'consumerKey' is missing in the signedJWT."); } }
Example 6
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()); } }
Example 7
Source File: ResourceServerFilter.java From authmore-framework with Apache License 2.0 | 4 votes |
private Set<String> extractSetFrom(JWTClaimsSet claimsSet, String key) { JSONArray scopeArray = (JSONArray) claimsSet.getClaim(key); String[] scopesStrings = scopeArray.toArray(new String[0]); return Arrays.stream(scopesStrings).collect(Collectors.toSet()); }
Example 8
Source File: TokenUtils.java From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License | 4 votes |
/** * Utility method to generate a JWT string from a JSON resource file that is signed by the pk * test resource key, possibly with invalid fields. * * @param pk - the private key to sign the token with * @param kid - the kid claim to assign to the token * @param jsonResName - name of test resources file * @param timeClaims - used to return the exp, iat, auth_time claims * @return the JWT string * @throws Exception on parse failure */ public static String generateTokenString(PrivateKey pk, String kid, String jsonResName, Map<String, Long> timeClaims) throws Exception { InputStream contentIS = TokenUtils.class.getResourceAsStream(jsonResName); if (contentIS == null) { throw new IllegalStateException("Failed to find resource: " + jsonResName); } byte[] tmp = new byte[4096]; int length = contentIS.read(tmp); byte[] content = new byte[length]; System.arraycopy(tmp, 0, content, 0, length); JSONParser parser = new JSONParser(DEFAULT_PERMISSIVE_MODE); JSONObject jwtContent = parser.parse(content, JSONObject.class); long currentTimeInSecs = currentTimeInSecs(); long exp = currentTimeInSecs + DEFAULT_DURATION; // If exp was passed in, use it if (timeClaims.containsKey(Claims.exp.name())) { exp = timeClaims.get(Claims.exp.name()); } System.out.printf("Setting exp: %d / %s\n", exp, new Date(1000*exp)); long iat = currentTimeInSecs; long authTime = currentTimeInSecs; jwtContent.put(Claims.exp.name(), exp); jwtContent.put(Claims.iat.name(), iat); jwtContent.put(Claims.auth_time.name(), authTime); // Return the token time values if requested if (timeClaims != null) { timeClaims.put(Claims.iat.name(), iat); timeClaims.put(Claims.auth_time.name(), authTime); timeClaims.put(Claims.exp.name(), exp); } // Create RSA-signer with the private key JWSSigner signer = new RSASSASigner(pk); JWTClaimsSet claimsSet = JWTClaimsSet.parse(jwtContent); for (String claim : claimsSet.getClaims().keySet()) { Object claimValue = claimsSet.getClaim(claim); System.out.printf("\tAdded claim: %s, value: %s\n", claim, claimValue); } JWSAlgorithm alg = JWSAlgorithm.RS256; JWSHeader jwtHeader = new JWSHeader.Builder(alg) .keyID(kid) .type(JOSEObjectType.JWT) .build(); SignedJWT signedJWT = new SignedJWT(jwtHeader, claimsSet); signedJWT.sign(signer); return signedJWT.serialize(); }
Example 9
Source File: GatewayUtils.java From carbon-apimgt with Apache License 2.0 | 4 votes |
/** * Validate whether the user is subscribed to the invoked API. If subscribed, return a JSON object containing * the API information. * * @param apiContext API context * @param apiVersion API version * @param payload The payload of the JWT token * @return an JSON object containing subscribed API information retrieved from token payload. * If the subscription information is not found, return a null object. * @throws APISecurityException if the user is not subscribed to the API */ public static JSONObject validateAPISubscription(String apiContext, String apiVersion, JWTClaimsSet payload, String[] splitToken, boolean isOauth) throws APISecurityException { JSONObject api = null; if (payload.getClaim(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS) != null) { // Subscription validation JSONArray subscribedAPIs = (JSONArray) payload.getClaim(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS); for (int i = 0; i < subscribedAPIs.size(); i++) { JSONObject subscribedAPIsJSONObject = (JSONObject) subscribedAPIs.get(i); if (apiContext.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_CONTEXT)) && apiVersion.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_VERSION) )) { api = subscribedAPIsJSONObject; if (log.isDebugEnabled()) { log.debug("User is subscribed to the API: " + apiContext + ", " + "version: " + apiVersion + ". Token: " + getMaskedToken(splitToken[0])); } break; } } if (api == null) { if (log.isDebugEnabled()) { log.debug("User is not subscribed to access the API: " + apiContext + ", version: " + apiVersion + ". Token: " + getMaskedToken(splitToken[0])); } log.error("User is not subscribed to access the API."); throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN, APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE); } } else { if (log.isDebugEnabled()) { log.debug("No subscription information found in the token."); } // we perform mandatory authentication for Api Keys if (!isOauth) { log.error("User is not subscribed to access the API."); throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN, APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE); } } return api; }