com.nimbusds.jwt.JWT Java Examples

The following examples show how to use com.nimbusds.jwt.JWT. 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: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Generic Signing function
 *
 * @param signedJWT
 * @param tenantDomain
 * @param tenantId
 * @return
 * @throws IdentityOAuth2Exception
 */
protected JWT signJWT(SignedJWT signedJWT, String tenantDomain, int tenantId)
        throws IdentityOAuth2Exception {

    if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.RS512.equals(signatureAlgorithm)) {
        return signJWTWithRSA(signedJWT, signatureAlgorithm, tenantDomain, tenantId);
    } else if (JWSAlgorithm.HS256.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS512.equals(signatureAlgorithm)) {
        // return signWithHMAC(payLoad,jwsAlgorithm,tenantDomain,tenantId); implementation
        // need to be done
    } else if (JWSAlgorithm.ES256.equals(signatureAlgorithm) ||
            JWSAlgorithm.ES384.equals(signatureAlgorithm) ||
            JWSAlgorithm.ES512.equals(signatureAlgorithm)) {
        // return signWithEC(payLoad,jwsAlgorithm,tenantDomain,tenantId); implementation
        // need to be done
    }
    log.error("UnSupported Signature Algorithm");
    throw new IdentityOAuth2Exception("UnSupported Signature Algorithm");
}
 
Example #2
Source File: AuthorizationRequestParseRequestObjectHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private void checkOAuthParameters(RoutingContext context, JWT jwt) {
    //So that the request is a valid OAuth 2.0 Authorization Request, values for the response_type and client_id
    // parameters MUST be included using the OAuth 2.0 request syntax, since they are REQUIRED by OAuth 2.0. The
    // values for these parameters MUST match those in the Request Object, if present.
    String clientId = context.request().getParam(io.gravitee.am.common.oauth2.Parameters.CLIENT_ID);
    String responseType = context.request().getParam(io.gravitee.am.common.oauth2.Parameters.RESPONSE_TYPE);

    try {
        Map<String, Object> claims = jwt.getJWTClaimsSet().getClaims();

        String reqObjClientId = (String) claims.get(io.gravitee.am.common.oauth2.Parameters.CLIENT_ID);
        if (reqObjClientId != null && !reqObjClientId.equals(clientId)) {
            throw new InvalidRequestObjectException("client_id does not match request parameter");
        }

        String reqObjResponseType = (String) claims.get(io.gravitee.am.common.oauth2.Parameters.RESPONSE_TYPE);
        if (reqObjResponseType != null && !reqObjResponseType.equals(responseType)) {
            throw new InvalidRequestObjectException("response_type does not match request parameter");
        }

    } catch (ParseException pe) {
        throw new InvalidRequestObjectException();
    }
}
 
Example #3
Source File: RequestObjectServiceImpl.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private Single<JWT> validateSignature(SignedJWT jwt, Client client) {
    return jwkService.getKeys(client)
            .switchIfEmpty(Maybe.error(new InvalidRequestObjectException()))
            .flatMap(new Function<JWKSet, MaybeSource<JWK>>() {
                @Override
                public MaybeSource<JWK> apply(JWKSet jwkSet) throws Exception {
                    return jwkService.getKey(jwkSet, jwt.getHeader().getKeyID());
                }
            })
            .switchIfEmpty(Maybe.error(new InvalidRequestObjectException()))
            .flatMapSingle(new Function<JWK, SingleSource<JWT>>() {
                @Override
                public SingleSource<JWT> apply(JWK jwk) throws Exception {
                    // 6.3.2.  Signed Request Object
                    // To perform Signature Validation, the alg Header Parameter in the
                    // JOSE Header MUST match the value of the request_object_signing_alg
                    // set during Client Registration
                    if (jwt.getHeader().getAlgorithm().getName().equals(client.getRequestObjectSigningAlg()) &&
                            jwsService.isValidSignature(jwt, jwk)) {
                        return Single.just(jwt);
                    } else {
                        return Single.error(new InvalidRequestObjectException("Invalid signature"));
                    }
                }
            });
}
 
Example #4
Source File: ReactiveXsuaaJwtDecoder.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
ReactiveXsuaaJwtDecoder(XsuaaServiceConfiguration xsuaaServiceConfiguration, int cacheValidityInSeconds,
		int cacheSize,
		OAuth2TokenValidator<Jwt> tokenValidators, Collection<PostValidationAction> postValidationActions) {
	cache = Caffeine.newBuilder().expireAfterWrite(cacheValidityInSeconds, TimeUnit.SECONDS).maximumSize(cacheSize)
			.build();

	this.tokenInfoExtractor = new TokenInfoExtractor() {
		@Override
		public String getJku(JWT jwt) {
			return (String) jwt.getHeader().toJSONObject().getOrDefault(CLAIM_JKU, null);
		}

		@Override
		public String getKid(JWT jwt) {
			return (String) jwt.getHeader().toJSONObject().getOrDefault(CLAIM_KID, null);
		}

		@Override
		public String getUaaDomain(JWT jwt) {
			return xsuaaServiceConfiguration.getUaaDomain();
		}
	};

	this.tokenValidators.addAll(Arrays.asList(tokenValidators));
	this.postValidationActions = postValidationActions != null ? postValidationActions : Collections.EMPTY_LIST;
}
 
Example #5
Source File: AadController.java    From journaldev with MIT License 6 votes vote down vote up
/**
 * getScurePage: Will check for JWT token details and returns aad.jsp view
 * @param model
 * @param httpRequest
 * @return
 */
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public String getScurePage(ModelMap model, HttpServletRequest httpRequest) {
	HttpSession session = httpRequest.getSession();
	log.debug("session: " + session);
	AuthenticationResult result = (AuthenticationResult) session.getAttribute(CommonUtil.PRINCIPAL_SESSION_NAME);
	if (result == null) {
		model.addAttribute("error", new Exception("AuthenticationResult not found in session."));
		return "/error";
	} else {
		try {
			log.debug("JWT token details:-");
			JWT jwt = JWTParser.parse(result.getIdToken());
			for (String key : jwt.getJWTClaimsSet().getAllClaims().keySet()) {
				log.info(key + ":" + jwt.getJWTClaimsSet().getAllClaims().get(key));
			}
			model.addAttribute("user", jwt.getJWTClaimsSet().getStringClaim("unique_name"));
		} catch (ParseException e) {
			log.error("Exception:", e);
		}

	}
	return "/secure/aad";
}
 
Example #6
Source File: ShibbolethAcrAwareTokenService.java    From shibboleth-oidc with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypt id token.
 *
 * @param client   the client
 * @param idClaims the id claims
 */
private JWT encryptIdToken(final ClientDetailsEntity client, final JWTClaimsSet.Builder idClaims) {
    log.debug("Locating encrypter service for client {}", client.getClientId());
    final JWTEncryptionAndDecryptionService encrypter = encrypters.getEncrypter(client);

    if (encrypter == null) {
        log.error("Couldn't find encrypter for client: {} ", client.getClientId());
        return null;
    }
    log.debug("Found encrypter service for client {}.", client.getClientId());
    final JWTClaimsSet claims = idClaims.build();
    final EncryptedJWT idToken = new EncryptedJWT(new JWEHeader(client.getIdTokenEncryptedResponseAlg(),
            client.getIdTokenEncryptedResponseEnc()), claims);

    log.debug("Encrypting idToken with response alg {} and response encoding {} and claims {}",
            client.getIdTokenEncryptedResponseAlg(),
            client.getIdTokenEncryptedResponseEnc(), claims.getClaims().keySet());
    encrypter.encryptJwt(idToken);
    return idToken;
}
 
Example #7
Source File: LazyJwtToken.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
private void parse() {
    if (! parsed) {
        parsed = true;

        try {
            JWT jwt = JWTParser.parse(token);
            headers = jwt.getHeader().toJSONObject();
            claims = jwt.getJWTClaimsSet().getClaims();
        } catch (ParseException ex){
            // Nothing to do in case of a bad JWT token
        }
    }
}
 
Example #8
Source File: JWSServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void testisValidSignature_PlainJwt() {
    JWT assertion = new PlainJWT(
            new JWTClaimsSet.Builder()
                    .issuer("iss")
                    .subject("client")
                    .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
                    .build()
    );

    assertFalse("Should return false due to ClassCastException",jwsService.isValidSignature(assertion, null));
}
 
Example #9
Source File: ClientAssertionServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
/**
 * This method will parse the JWT bearer then ensure that all requested claims are set as required
 * <a href="https://tools.ietf.org/html/rfc7523#section-3">here</a>
 * @param assertion jwt as string value.
 * @return
 */
private Maybe<JWT> validateJWT(String assertion, String basePath) {
    try {
        JWT jwt = JWTParser.parse(assertion);

        String iss = jwt.getJWTClaimsSet().getIssuer();
        String sub = jwt.getJWTClaimsSet().getSubject();
        List<String> aud = jwt.getJWTClaimsSet().getAudience();
        Date exp = jwt.getJWTClaimsSet().getExpirationTime();

        if  (iss == null || iss.isEmpty() || sub == null || sub.isEmpty() || aud == null || aud.isEmpty() || exp == null) {
            return Maybe.error(NOT_VALID);
        }

        if (exp.before(Date.from(Instant.now()))) {
            return Maybe.error(new InvalidClientException("assertion has expired"));
        }

        //Check audience, here we expect to have absolute token endpoint path.
        OpenIDProviderMetadata discovery = openIDDiscoveryService.getConfiguration(basePath);
        if (discovery == null || discovery.getTokenEndpoint() == null) {
            return Maybe.error(new ServerErrorException("Unable to retrieve discovery token endpoint."));
        }

        if (aud.stream().filter(discovery.getTokenEndpoint()::equals).count()==0) {
            return Maybe.error(NOT_VALID);
        }

        return Maybe.just(jwt);
    } catch (ParseException pe) {
        return Maybe.error(NOT_VALID);
    }
}
 
Example #10
Source File: ClientAssertionServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public Maybe<Client> assertClient(String assertionType, String assertion, String basePath) {

    InvalidClientException unsupportedAssertionType = new InvalidClientException("Unknown or unsupported assertion_type");

    if (assertionType == null || assertionType.isEmpty()) {
        return Maybe.error(unsupportedAssertionType);
    }

    if (JWT_BEARER.equals(assertionType)) {
        return this.validateJWT(assertion, basePath)
                .flatMap(new Function<JWT, MaybeSource<Client>>() {
                    @Override
                    public MaybeSource<Client> apply(JWT jwt) throws Exception {
                        // Handle client_secret_key client authentication
                        if (JWSAlgorithm.Family.HMAC_SHA.contains(jwt.getHeader().getAlgorithm())) {
                            return validateSignatureWithHMAC(jwt);
                        } else {
                            // Handle private_key_jwt client authentication
                            return validateSignatureWithPublicKey(jwt);
                        }
                    }
                });
    }

    return Maybe.error(unsupportedAssertionType);
}
 
Example #11
Source File: LazyJwtToken.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
private void parse() {
    if (! parsed) {
        parsed = true;

        try {
            JWT jwt = JWTParser.parse(token);
            headers = jwt.getHeader().toJSONObject();
            claims = jwt.getJWTClaimsSet().getClaims();
        } catch (ParseException ex){
            // Nothing to do in case of a bad JWT token
        }
    }
}
 
Example #12
Source File: JWEServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private Single<JWT> decrypt(JWEObject jwe, Client client, Predicate<JWK> filter, JWEDecrypterFunction<JWK, JWEDecrypter> function) {
    return jwkService.getKeys(client)
            .flatMap(jwkSet -> jwkService.filter(jwkSet, filter))
            .switchIfEmpty(Maybe.error(new InvalidClientMetadataException("no matching key found to decrypt")))
            .flatMapSingle(jwk -> Single.just(function.apply(jwk)))
            .map(decrypter -> {
                jwe.decrypt(decrypter);
                return jwe.getPayload().toSignedJWT();
            });
}
 
Example #13
Source File: JWSServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValidSignature(JWT jwt, JWK jwk) {
    try {
        SignedJWT signedJwt = (SignedJWT)jwt;
        return signedJwt.verify(this.verifier(jwk));
    } catch (ClassCastException | JOSEException ex) {
        LOGGER.error(ex.getMessage(),ex);
        return false;
    }
}
 
Example #14
Source File: RequestObjectServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public Single<JWT> readRequestObjectFromURI(String requestUri, Client client) {
    try {
        if (requestUri.startsWith(RESOURCE_OBJECT_URN_PREFIX)) {
            // Extract the identifier
            String identifier = requestUri.substring(RESOURCE_OBJECT_URN_PREFIX.length());

            return requestObjectRepository.findById(identifier)
                    .switchIfEmpty(Single.error(new InvalidRequestObjectException()))
                    .flatMap((Function<RequestObject, Single<JWT>>) req -> {
                        if (req.getExpireAt().after(new Date())) {
                            return readRequestObject(req.getPayload(), client);
                        }

                        return Single.error(new InvalidRequestObjectException());
                    });
        } else {
            return webClient.getAbs(UriBuilder.fromHttpUrl(requestUri).build().toString())
                    .rxSend()
                    .map(HttpResponse::bodyAsString)
                    .flatMap((Function<String, Single<JWT>>) s -> readRequestObject(s, client));
        }
    }
    catch (IllegalArgumentException | URISyntaxException ex) {
        return Single.error(new InvalidRequestObjectException(requestUri+" is not valid."));
    }
}
 
Example #15
Source File: RequestObjectServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public Single<JWT> readRequestObject(String request, Client client) {
    return jweService.decrypt(request, client)
            .onErrorResumeNext(Single.error(new InvalidRequestObjectException("Malformed request object")))
            .flatMap((Function<JWT, SingleSource<JWT>>) jwt -> {
                if (jwt instanceof SignedJWT) {
                    return validateSignature((SignedJWT) jwt, client);
                } else {
                    return Single.just(jwt);
                }
            });
}
 
Example #16
Source File: OPAAuthorizationContext.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
public OPAAuthorizationContext(String jwt) throws AuthorizationFailedException {

        super(jwt);
        try {
            JWT parsedJWT = JWTParser.parse(jwt);
            jwtContent = parsedJWT.getJWTClaimsSet();
        } catch (ParseException e) {
            throw new AuthorizationFailedException("Error while parsing JWT", e);
        }

    }
 
Example #17
Source File: AuthorizationRequestParseRequestObjectHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private void overrideRequestParameters(RoutingContext context, JWT jwt) {
    try {
        Map<String, Object> claims = jwt.getJWTClaimsSet().getClaims();

        OVERRIDABLE_PARAMETERS
                .forEach(key -> {
                    Object property = claims.get(key);
                    if (property != null) {
                        context.request().params().set(key, property.toString());
                    }
                });
    } catch (ParseException pe) {
        throw new InvalidRequestObjectException();
    }
}
 
Example #18
Source File: AuthorizationRequestParseRequestObjectHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private Maybe<JWT> handleRequestObjectURI(RoutingContext context) {
    final String requestUri = context.request().getParam(Parameters.REQUEST_URI);

    if (requestUri != null) {
        // Ensure that the request_uri is not propagated to the next authorization flow step
        context.request().params().remove(Parameters.REQUEST_URI);

        return requestObjectService
                .readRequestObjectFromURI(requestUri, context.get(CLIENT_CONTEXT_KEY))
                .toMaybe();
    } else {
        return Maybe.empty();
    }
}
 
Example #19
Source File: AuthorizationRequestParseRequestObjectHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private Maybe<JWT> handleRequestObjectValue(RoutingContext context) {
    final String request = context.request().getParam(Parameters.REQUEST);

    if (request != null) {
        // Ensure that the request_uri is not propagated to the next authorization flow step
        context.request().params().remove(Parameters.REQUEST);

        return requestObjectService
                .readRequestObject(request, context.get(CLIENT_CONTEXT_KEY))
                .toMaybe();
    } else {
        return Maybe.empty();
    }
}
 
Example #20
Source File: AuthResource.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
private IDTokenClaimsSet validateToken(OAuthProvider provider, OAuthLoginRequestDTO oAuthLoginRequestDTO)
        throws MalformedURLException, ParseException, BadJOSEException, JOSEException {
    Issuer iss = new Issuer(provider.getIssuer());
    ClientID clientID = new ClientID(provider.getClientID());
    Nonce nonce = new Nonce(oAuthLoginRequestDTO.getNonce());
    URL jwkSetURL = new URL(provider.getJwkSetURL());
    JWSAlgorithm jwsAlg = JWSAlgorithm.parse(provider.getJwsAlgorithm());
    IDTokenValidator validator = new IDTokenValidator(iss, clientID, jwsAlg, jwkSetURL);
    JWT idToken = JWTParser.parse(oAuthLoginRequestDTO.getIdToken());
    return validator.validate(idToken, nonce);
}
 
Example #21
Source File: FirebaseJwtTokenDecoder.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private SignedJWT parse(String token) {
	try {
		JWT jwt = JWTParser.parse(token);
		if (!(jwt instanceof SignedJWT)) {
			throw new JwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm());
		}
		return (SignedJWT) jwt;
	}
	catch (Exception ex) {
		throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
	}
}
 
Example #22
Source File: JWKSBasedJWTValidator.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateSignature(String jwtString, String jwksUri, String algorithm, Map<String, Object> opts)
        throws TokenValidationFailureException {

    try {
        JWT jwt = JWTParser.parse(jwtString);
        return this.validateSignature(jwt, jwksUri, algorithm, opts);

    } catch (ParseException e) {
        throw new TokenValidationFailureException("Error occurred while parsing JWT string.", e);
    }
}
 
Example #23
Source File: XsuaaJwtDecoder.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
XsuaaJwtDecoder(XsuaaServiceConfiguration xsuaaServiceConfiguration, int cacheValidityInSeconds, int cacheSize,
		OAuth2TokenValidator<Jwt> tokenValidators, Collection<PostValidationAction> postValidationActions) {

	this.cache = Caffeine.newBuilder().expireAfterWrite(cacheValidityInSeconds, TimeUnit.SECONDS)
			.maximumSize(cacheSize)
			.build();
	this.tokenValidators = tokenValidators;
	this.xsuaaServiceConfiguration = xsuaaServiceConfiguration;

	this.tokenInfoExtractor = new TokenInfoExtractor() {
		@Override
		public String getJku(JWT jwt) {
			return (String) jwt.getHeader().toJSONObject().getOrDefault(CLAIM_JKU, null);
		}

		@Override
		public String getKid(JWT jwt) {
			return (String) jwt.getHeader().toJSONObject().getOrDefault(CLAIM_KID, null);
		}

		@Override
		public String getUaaDomain(JWT jwt) {
			return xsuaaServiceConfiguration.getUaaDomain();
		}
	};
	this.postValidationActions = postValidationActions != null ? postValidationActions : Collections.emptyList();
}
 
Example #24
Source File: XsuaaJwtDecoder.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Override
public Jwt decode(String token) throws JwtException {
	Assert.notNull(token, "token is required");
	JWT jwt;

	try {
		jwt = JWTParser.parse(token);
	} catch (ParseException ex) {
		throw new JwtException("Error initializing JWT decoder: " + ex.getMessage());
	}
	final Jwt verifiedToken = verifyToken(jwt);
	postValidationActions.forEach(action -> action.perform(verifiedToken));
	return verifiedToken;
}
 
Example #25
Source File: XsuaaJwtDecoder.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
private Jwt verifyToken(JWT jwt) {
	try {
		String jku = tokenInfoExtractor.getJku(jwt);
		String kid = tokenInfoExtractor.getKid(jwt);
		String uaaDomain = tokenInfoExtractor.getUaaDomain(jwt);
		return verifyToken(jwt.getParsedString(), jku, kid, uaaDomain);
	} catch (JwtException e) {
		return tryToVerifyWithVerificationKey(jwt.getParsedString(), e);
	}
}
 
Example #26
Source File: AuthorizationRequestParseRequestObjectHandler.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    // Even if a scope parameter is present in the Request Object value, a scope parameter MUST always be passed
    // using the OAuth 2.0 request syntax containing the openid scope value to indicate to the underlying OAuth 2.0
    // logic that this is an OpenID Connect request.
    String scope = context.request().getParam(io.gravitee.am.common.oauth2.Parameters.SCOPE);
    HashSet<String> scopes = scope != null && !scope.isEmpty() ? new HashSet<>(Arrays.asList(scope.split("\\s+"))) : null;
    if (scopes == null || !scopes.contains(Scope.OPENID.getKey())) {
        context.next();
        return;
    }

    // if there is no request or request_uri parameters, continue
    if ((context.request().getParam(Parameters.REQUEST) == null || context.request().getParam(Parameters.REQUEST).isEmpty())
            && ((context.request().getParam(Parameters.REQUEST_URI) == null || context.request().getParam(Parameters.REQUEST_URI).isEmpty()))) {
        context.next();
        return;
    }

    // check request object parameters
    checkRequestObjectParameters(context);

    // Proceed request and request_uri parameters
    Maybe<JWT> requestObject = null;

    if (context.request().getParam(Parameters.REQUEST) != null) {
        requestObject = handleRequestObjectValue(context);
    } else if (context.request().getParam(Parameters.REQUEST_URI) != null) {
        requestObject = handleRequestObjectURI(context);
    }

    requestObject
            .subscribe(
                    jwt -> {
                        try {
                            // Check OAuth2 parameters
                            checkOAuthParameters(context, jwt);
                            overrideRequestParameters(context, jwt);
                            context.next();
                        } catch (Exception ex) {
                            context.fail(ex);
                        }
                    },
                    context::fail,
                    () -> context.next());
}
 
Example #27
Source File: ShibbolethAcrAwareTokenService.java    From shibboleth-oidc with Apache License 2.0 4 votes vote down vote up
@Override
    public JWT createIdToken(final ClientDetailsEntity client, final OAuth2Request request,
                             final Date issueTime, final String sub,
                             final OAuth2AccessTokenEntity accessToken) {

        JWSAlgorithm signingAlg = jwtService.getDefaultSigningAlgorithm();

        if (client.getIdTokenSignedResponseAlg() != null) {
            signingAlg = client.getIdTokenSignedResponseAlg();
        }

        final JWTClaimsSet.Builder idClaims = new JWTClaimsSet.Builder();

        log.debug("Request {} extension {}", ConnectRequestParameters.MAX_AGE, request.getExtensions().get(ConnectRequestParameters.MAX_AGE));
        log.debug("Request {} extension {}", OIDCConstants.ID_TOKEN, request.getExtensions().get(OIDCConstants.ID_TOKEN));
        log.debug("Client require authN time {}", client.getRequireAuthTime());

        calculateAuthTimeClaim(request, idClaims);

        idClaims.issueTime(issueTime);

        calculateAmrAndAcrClaims(accessToken, idClaims);
        calculateExpirationClaim(client, idClaims);

        idClaims.issuer(configBean.getIssuer());
        log.debug("issuer is set to {}", configBean.getIssuer());

        idClaims.subject(sub);
        log.debug("sub is set to {}", sub);

        idClaims.audience(Lists.newArrayList(client.getClientId()));
        log.debug("audience is set to {}", client.getClientId());

        final String jwtId = UUID.randomUUID().toString();
        idClaims.jwtID(jwtId);
        log.debug("JWT id is set to {}", jwtId);
        
        calculateNonceClaim(request, idClaims);

        final Set<String> responseTypes = request.getResponseTypes();

        calculateAtHashClaim(accessToken, signingAlg, idClaims, responseTypes);

        JWT idToken = null;
        if (client.getIdTokenEncryptedResponseAlg() != null
                && !client.getIdTokenEncryptedResponseAlg().equals(Algorithm.NONE)
                && client.getIdTokenEncryptedResponseEnc() != null
                && !client.getIdTokenEncryptedResponseEnc().equals(Algorithm.NONE)
                && (!Strings.isNullOrEmpty(client.getJwksUri()) || client.getJwks() != null)) {

            idToken = encryptIdToken(client, idClaims);
        } else {
            idToken = signIdToken(client, signingAlg, idClaims);
        }

        log.debug("Mapping the idToken to the authentication of client {}",
                accessToken.getAuthenticationHolder().getClientId());
        return idToken;
        
//        idTokenEntity.setAuthenticationHolder(accessToken.getAuthenticationHolder());
//
//        // create a scope set with just the special "id-token" scope
//        final Set<String> idScopes = Sets.newHashSet(SystemScopeService.ID_TOKEN_SCOPE);
//        idTokenEntity.setScope(idScopes);
//        log.debug("Configured scopes for the idToken scope {} are {}",
//                SystemScopeService.ID_TOKEN_SCOPE, idScopes);
//
//        idTokenEntity.setClient(accessToken.getClient());
//
//        return idTokenEntity;
    }
 
Example #28
Source File: XsuaaJwtDecoderTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
@Override
public String getJku(JWT jwt) {
	return jku;
}
 
Example #29
Source File: JWEServiceImpl.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public Single<JWT> decrypt(String jwt, Client client) {
    try {
        // Parse a first time to check if the JWT is encrypted
        JWT parsedJwt = JWTParser.parse(jwt);

        if (parsedJwt instanceof EncryptedJWT) {

            JWEObject jweObject = JWEObject.parse(jwt);

            JWEAlgorithm algorithm = jweObject.getHeader().getAlgorithm();

            //RSA decryption
            if (RSACryptoProvider.SUPPORTED_ALGORITHMS.contains(algorithm)) {
                return decrypt(jweObject, client, JWKFilter.RSA_KEY_ENCRYPTION(), jwk ->
                        new RSADecrypter(JWKConverter.convert((RSAKey) jwk))
                );
            }
            //Curve decryption (Elliptic "EC" & Edward "OKP")
            else if (ECDHCryptoProvider.SUPPORTED_ALGORITHMS.contains(algorithm)) {
                return decrypt(jweObject, client, JWKFilter.CURVE_KEY_ENCRYPTION(), jwk -> {
                    if (KeyType.EC.getValue().equals(jwk.getKty())) {
                        return new ECDHDecrypter(JWKConverter.convert((ECKey) jwk));
                    }
                    return new X25519Decrypter(JWKConverter.convert((OKPKey) jwk));
                });
            }
            //AES decryption ("OCT" keys)
            else if (AESCryptoProvider.SUPPORTED_ALGORITHMS.contains(algorithm)) {
                return decrypt(jweObject, client, JWKFilter.OCT_KEY_ENCRYPTION(algorithm), jwk ->
                        new AESDecrypter(JWKConverter.convert((OCTKey) jwk))
                );
            }
            //Direct decryption ("OCT" keys)
            else if (DirectCryptoProvider.SUPPORTED_ALGORITHMS.contains(algorithm)) {
                return decrypt(jweObject, client, JWKFilter.OCT_KEY_ENCRYPTION(jweObject.getHeader().getEncryptionMethod()), jwk ->
                        new DirectDecrypter(JWKConverter.convert((OCTKey) jwk))
                );
            }
            //Password Base decryption ("OCT" keys)
            else if (PasswordBasedCryptoProvider.SUPPORTED_ALGORITHMS.contains(algorithm)) {
                return decrypt(jweObject, client, JWKFilter.OCT_KEY_ENCRYPTION(), jwk -> {
                    OctetSequenceKey octKey = JWKConverter.convert((OCTKey) jwk);
                    return new PasswordBasedDecrypter(octKey.getKeyValue().decode());
                });
            }

            return Single.error(new ServerErrorException("Unable to perform Json Web Decryption, unsupported algorithm: " + algorithm.getName()));
        } else {
            return Single.just(parsedJwt);
        }
    } catch (Exception ex) {
        return Single.error(ex);
    }
}
 
Example #30
Source File: XsuaaJwtDecoderTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
@Override
public String getKid(JWT jwt) {
	return "kid";
}