com.nimbusds.jwt.JWTParser Java Examples

The following examples show how to use com.nimbusds.jwt.JWTParser. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
Source File: ReactiveXsuaaJwtDecoder.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Jwt> decode(String token) throws JwtException {
	return Mono.just(token).map(jwtToken -> {
		try {
			return JWTParser.parse(jwtToken);
		} catch (ParseException e) {
			throw new JwtException("Error initializing JWT decoder:" + e.getMessage());
		}
	}).map(jwtToken -> {
		String cacheKey = tokenInfoExtractor.getJku(jwtToken) + tokenInfoExtractor.getKid(jwtToken);
		return cache.get(cacheKey, k -> this.getDecoder(tokenInfoExtractor.getJku(jwtToken)));
	}).flatMap(decoder -> decoder.decode(token))
			.doOnSuccess(jwt -> postValidationActions.forEach(act -> act.perform(jwt)));
}
 
Example #9
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 #10
Source File: AuthPageController.java    From ms-identity-java-webapp with MIT License 5 votes vote down vote up
private void setAccountInfo(ModelAndView model, HttpServletRequest httpRequest) throws ParseException {
    IAuthenticationResult auth = SessionManagementHelper.getAuthSessionObject(httpRequest);

    String tenantId = JWTParser.parse(auth.idToken()).getJWTClaimsSet().getStringClaim("tid");

    model.addObject("tenantId", tenantId);
    model.addObject("account", SessionManagementHelper.getAuthSessionObject(httpRequest).account());
}
 
Example #11
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 #12
Source File: PoPAuthenticationManager.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication)
    throws AuthenticationException {
    Authentication authenticationResult = authenticationManager
        .authenticate(authentication);

    if (authenticationResult.isAuthenticated()) {
        // validates nonce because JWT is already valid
        if (authentication instanceof PoPAuthenticationToken) {
            PoPAuthenticationToken popAuthentication = (PoPAuthenticationToken) authentication;

            // starts validating nonce here
            String nonce = popAuthentication.getNonce();
            if (nonce == null) {
                throw new UnapprovedClientAuthenticationException(
                    "This request does not have a valid signed nonce");
            }

            String token = (String) popAuthentication.getPrincipal();

            System.out.println("access token:" + token);

            try {
                JWT jwt = JWTParser.parse(token);
                String publicKey = jwt.getJWTClaimsSet().getClaim("public_key").toString();
                JWK jwk = JWK.parse(publicKey);

                JWSObject jwsNonce = JWSObject.parse(nonce);
                JWSVerifier verifier = new RSASSAVerifier((RSAKey) jwk);
                if (!jwsNonce.verify(verifier)) {
                    throw new InvalidTokenException("Client hasn't possession of given token");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }

    return authenticationResult;
}
 
Example #13
Source File: AuthHelper.java    From ms-identity-java-webapp with MIT License 4 votes vote down vote up
private String getNonceClaimValueFromIdToken(String idToken) throws ParseException {
    return (String) JWTParser.parse(idToken).getJWTClaimsSet().getClaim("nonce");
}
 
Example #14
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 #15
Source File: AuthFilter.java    From ms-identity-java-webapp with MIT License 4 votes vote down vote up
private String getNonceClaimValueFromIdToken(String idToken) throws ParseException {
    return (String) JWTParser.parse(idToken).getJWTClaimsSet().getClaim("nonce");
}
 
Example #16
Source File: JWETest.java    From graviteeio-access-management with Apache License 2.0 3 votes vote down vote up
@Test
public void test() throws ParseException {
    String jwt = "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.K52jFwAQJH-DxMhtaq7sg5tMuot_mT5dm1DR_01wj6ZUQQhJFO02vPI44W5nDjC5C_v4pW1UiJa3cwb5y2Rd9kSvb0ZxAqGX9c4Z4zouRU57729ML3V05UArUhck9ZvssfkDW1VclingL8LfagRUs2z95UkwhiZyaKpmrgqpKX8azQFGNLBvEjXnx-xoDFZIYwHOno290HOpig3aUsDxhsioweiXbeLXxLeRsivaLwUWRUZfHRC_HGAo8KSF4gQZmeJtRgai5mz6qgbVkg7jPQyZFtM5_ul0UKHE2y0AtWm8IzDE_rbAV14OCRZJ6n38X5urVFFE5sdphdGsNlA.gjI_RIFWZXJwaO9R.oaE5a-z0N1MW9FBkhKeKeFa5e7hxVXOuANZsNmBYYT8G_xlXkMD0nz4fIaGtuWd3t9Xp-kufvvfD-xOnAs2SBX_Y1kYGPto4mibBjIrXQEjDsKyKwndxzrutN9csmFwqWhx1sLHMpJkgsnfLTi9yWBPKH5Krx23IhoDGoSfqOquuhxn0y0WkuqH1R3z-fluUs6sxx9qx6NFVS1NRQ-LVn9sWT5yx8m9AQ_ng8MBWz2BfBTV0tjliV74ogNDikNXTAkD9rsWFV0IX4IpA.sOLijuVySaKI-FYUaBywpg";

    JWT parse = JWTParser.parse(jwt);

    System.out.println(parse.getHeader());

}
 
Example #17
Source File: AuthPageController.java    From ms-identity-java-webapp with MIT License 3 votes vote down vote up
private void setAccountInfo(ModelAndView model, HttpServletRequest httpRequest) throws ParseException {
    IAuthenticationResult auth = getAuthSessionObject(httpRequest);

    model.addObject("idTokenClaims", JWTParser.parse(auth.idToken()).getJWTClaimsSet().getClaims());

    model.addObject("account", getAuthSessionObject(httpRequest).account());
}