org.jose4j.jwt.consumer.JwtConsumerBuilder Java Examples
The following examples show how to use
org.jose4j.jwt.consumer.JwtConsumerBuilder.
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: JwtAuthProviderTest.java From dropwizard-auth-jwt with Apache License 2.0 | 6 votes |
protected ContainerRequestFilter getAuthFilter() { final JwtConsumer consumer = new JwtConsumerBuilder() .setRequireExpirationTime() // the JWT must have an expiration time .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew .setRequireSubject() // the JWT must have a subject claim .setExpectedIssuer("Issuer") // whom the JWT needs to have been issued by .setExpectedAudience("Audience") // whom the JWT needs to have been issued by .setVerificationKey(new HmacKey(SECRET_KEY.getBytes(UTF_8))) // verify the signature with the public key .setRelaxVerificationKeyValidation() // relaxes key length requirement .build();// create the JwtConsumer instance return new JwtAuthFilter.Builder<>() .setCookieName(COOKIE_NAME) .setJwtConsumer(consumer) .setPrefix(BEARER_PREFIX) .setAuthorizer(AuthUtil.getTestAuthorizer(ADMIN_USER, ADMIN_ROLE)) .setAuthenticator(AuthUtil.getJWTAuthenticator(ImmutableList.of(ADMIN_USER, ORDINARY_USER))) .buildAuthFilter(); }
Example #2
Source File: JwtAuthApplication.java From dropwizard-auth-jwt with Apache License 2.0 | 6 votes |
@Override public void run(MyConfiguration configuration, Environment environment) throws Exception { final byte[] key = configuration.getJwtTokenSecret(); final JwtConsumer consumer = new JwtConsumerBuilder() .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew .setRequireExpirationTime() // the JWT must have an expiration time .setRequireSubject() // the JWT must have a subject claim .setVerificationKey(new HmacKey(key)) // verify the signature with the public key .setRelaxVerificationKeyValidation() // relaxes key length requirement .build(); // create the JwtConsumer instance environment.jersey().register(new AuthDynamicFeature( new JwtAuthFilter.Builder<MyUser>() .setJwtConsumer(consumer) .setRealm("realm") .setPrefix("Bearer") .setAuthenticator(new ExampleAuthenticator()) .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Principal.class)); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new SecuredResource(configuration.getJwtTokenSecret())); }
Example #3
Source File: BoxDeveloperEditionAPIConnectionTest.java From box-java-sdk with Apache License 2.0 | 6 votes |
private JwtClaims getClaimsFromRequest(Request request) throws Exception { // Get the JWT out of the request body String body = request.getBodyAsString(); String[] tokens = body.split("&"); String jwt = null; for (String s : tokens) { String[] parts = s.split("="); if (parts[0] != null && parts[0].equals("assertion") && parts[1] != null) { jwt = parts[1]; } } if (jwt == null) { throw new Exception("No jwt assertion found in request body"); } // Parse out the JWT to verify the claims JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setSkipSignatureVerification() .setSkipAllValidators() .build(); return jwtConsumer.processToClaims(jwt); }
Example #4
Source File: JwtHelper.java From openhab-core with Eclipse Public License 2.0 | 6 votes |
/** * Performs verifications on a JWT token, then parses it into a {@link AuthenticationException} instance * * @param jwt the base64-encoded JWT token from the request * @return the {@link Authentication} derived from the information in the token * @throws AuthenticationException */ public Authentication verifyAndParseJwtAccessToken(String jwt) throws AuthenticationException { JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(30) .setRequireSubject().setExpectedIssuer(ISSUER_NAME).setExpectedAudience(AUDIENCE) .setVerificationKey(jwtWebKey.getKey()) .setJwsAlgorithmConstraints(ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256).build(); try { JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt); String username = jwtClaims.getSubject(); List<String> roles = jwtClaims.getStringListClaimValue("role"); Authentication auth = new Authentication(username, roles.toArray(new String[roles.size()])); return auth; } catch (Exception e) { logger.error("Error while processing JWT token", e); throw new AuthenticationException(e.getMessage()); } }
Example #5
Source File: Jose4jVerifierTest.java From microprofile-jwt-auth with Apache License 2.0 | 6 votes |
@Override protected void validateToken(String token, RSAPublicKey publicKey, String issuer, int expGracePeriodSecs) throws Exception { JwtConsumerBuilder builder = new JwtConsumerBuilder() .setRequireExpirationTime() .setRequireSubject() .setSkipDefaultAudienceValidation() .setExpectedIssuer(issuer) .setJwsAlgorithmConstraints( new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256)); builder.setVerificationKey(publicKey); if (expGracePeriodSecs > 0) { builder.setAllowedClockSkewInSeconds(expGracePeriodSecs); } else { builder.setEvaluationTime(NumericDate.fromSeconds(0)); } JwtConsumer jwtConsumer = builder.build(); JwtContext jwtContext = jwtConsumer.process(token); String type = jwtContext.getJoseObjects().get(0).getHeader("typ"); // Validate the JWT and process it to the Claims jwtConsumer.processContext(jwtContext); }
Example #6
Source File: JWTAuthPlugin.java From lucene-solr with Apache License 2.0 | 6 votes |
private void initConsumer() { JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder() .setAllowedClockSkewInSeconds(30); // allow some leeway in validating time based claims to account for clock skew String[] issuers = issuerConfigs.stream().map(JWTIssuerConfig::getIss).filter(Objects::nonNull).toArray(String[]::new); if (issuers.length > 0) { jwtConsumerBuilder.setExpectedIssuers(requireIssuer, issuers); // whom the JWT needs to have been issued by } String[] audiences = issuerConfigs.stream().map(JWTIssuerConfig::getAud).filter(Objects::nonNull).toArray(String[]::new); if (audiences.length > 0) { jwtConsumerBuilder.setExpectedAudience(audiences); // to whom the JWT is intended for } else { jwtConsumerBuilder.setSkipDefaultAudienceValidation(); } jwtConsumerBuilder.setRequireSubject(); if (requireExpirationTime) jwtConsumerBuilder.setRequireExpirationTime(); if (algWhitelist != null) jwtConsumerBuilder.setJwsAlgorithmConstraints( // only allow the expected signature algorithm(s) in the given context new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, algWhitelist.toArray(new String[0]))); jwtConsumerBuilder.setVerificationKeyResolver(verificationKeyResolver); jwtConsumer = jwtConsumerBuilder.build(); // create the JwtConsumer instance }
Example #7
Source File: JWTokenFactory.java From eplmp with Eclipse Public License 1.0 | 6 votes |
public static String validateEntityToken(Key key, String jwt) { JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setVerificationKey(key) .setRelaxVerificationKeyValidation() .build(); try { JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt); String subject = jwtClaims.getSubject(); try (JsonReader reader = Json.createReader(new StringReader(subject))) { JsonObject subjectObject = reader.readObject(); // JsonParsingException return subjectObject.getString(ENTITY_KEY); // Npe } } catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) { LOGGER.log(Level.FINE, "Cannot validate jwt token", e); } return null; }
Example #8
Source File: JWTokenFactory.java From eplmp with Eclipse Public License 1.0 | 6 votes |
public static String validateSharedResourceToken(Key key, String jwt) { JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setVerificationKey(key) .setRelaxVerificationKeyValidation() .build(); try { JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt); String subject = jwtClaims.getSubject(); try (JsonReader reader = Json.createReader(new StringReader(subject))) { JsonObject subjectObject = reader.readObject(); // JsonParsingException return subjectObject.getString(SHARED_ENTITY_UUID); // Npe } } catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) { LOGGER.log(Level.FINE, "Cannot validate jwt token", e); } return null; }
Example #9
Source File: OauthHelperTest.java From light-4j with Apache License 2.0 | 6 votes |
private static boolean isTokenExpired(String authorization) { boolean expired = false; String jwt = getJwtFromAuthorization(authorization); if(jwt != null) { JwtConsumer consumer = new JwtConsumerBuilder() .setDisableRequireSignature() .setSkipSignatureVerification() .build(); try { consumer.processToClaims(jwt); } catch (InvalidJwtException e) { if(e.hasExpired()) expired = true; } } return expired; }
Example #10
Source File: OidcJsonWebTokenProducer.java From quarkus with Apache License 2.0 | 5 votes |
private JsonWebToken getTokenCredential(Class<? extends TokenCredential> type) { if (identity.isAnonymous()) { return new NullJsonWebToken(); } if (identity.getPrincipal() instanceof OidcJwtCallerPrincipal && ((OidcJwtCallerPrincipal) identity.getPrincipal()).getCredential().getClass() == type) { return (JsonWebToken) identity.getPrincipal(); } TokenCredential credential = identity.getCredential(type); if (credential != null) { if (credential instanceof AccessTokenCredential && ((AccessTokenCredential) credential).isOpaque()) { throw new OIDCException("Opaque access token can not be converted to JsonWebToken"); } JwtClaims jwtClaims; try { jwtClaims = new JwtConsumerBuilder() .setSkipSignatureVerification() .setSkipAllValidators() .build().processToClaims(credential.getToken()); } catch (InvalidJwtException e) { throw new OIDCException(e); } jwtClaims.setClaim(Claims.raw_token.name(), credential.getToken()); return new OidcJwtCallerPrincipal(jwtClaims, credential); } String tokenType = type == AccessTokenCredential.class ? "access" : "ID"; throw new OIDCException("Current identity is not associated with an " + tokenType + " token"); }
Example #11
Source File: JwtUtil.java From light with Apache License 2.0 | 5 votes |
public static Map<String, Object> verifyJwt(String jwt) throws InvalidJwtException, MalformedClaimException { Map<String, Object> user = null; X509VerificationKeyResolver x509VerificationKeyResolver = new X509VerificationKeyResolver(certificate); x509VerificationKeyResolver.setTryAllOnNoThumbHeader(true); JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setRequireExpirationTime() // the JWT must have an expiration time .setAllowedClockSkewInSeconds((Integer) config.get(CLOCK_SKEW_IN_MINUTE)*60) // allow some leeway in validating time based claims to account for clock skew .setRequireSubject() // the JWT must have a subject claim .setExpectedIssuer(issuer) .setExpectedAudience(audience) .setVerificationKeyResolver(x509VerificationKeyResolver) // verify the signature with the certificates .build(); // create the JwtConsumer instance // Validate the JWT and process it to the Claims JwtClaims claims = jwtConsumer.processToClaims(jwt); if(claims != null) { user = new HashMap<String, Object>(); user.put("userId", claims.getClaimValue("userId")); user.put("clientId", claims.getClaimValue("clientId")); List roles = claims.getStringListClaimValue("roles"); user.put("roles", roles); Object host = claims.getClaimValue("host"); if(host != null) user.put("host", host); } return user; }
Example #12
Source File: JsonWebToken.java From datamill with ISC License | 5 votes |
protected JsonWebToken verify(JwtConsumerBuilder builder, String jwt) { try { JwtClaims claims = builder.build().processToClaims(jwt); return new JsonWebToken(claims); } catch (InvalidJwtException e) { throw new SecurityException(e); } }
Example #13
Source File: JWTCredential.java From thorntail with Apache License 2.0 | 5 votes |
/** * This just parses the token without validation to extract one of the following in order to obtain * the name to be used for the principal: * upn * preferred_username * subject * * If there is an exception it sets the name to INVALID_TOKEN_NAME and saves the exception for access * via {@link #getJwtException()} * * @return the name to use for the principal */ public String getName() { if (name == null) { name = "INVALID_TOKEN_NAME"; try { // Build a JwtConsumer that doesn't check signatures or do any validation. JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder() .setSkipAllValidators() .setDisableRequireSignature() .setSkipSignatureVerification() .build(); //The first JwtConsumer is basically just used to parse the JWT into a JwtContext object. JwtContext jwtContext = firstPassJwtConsumer.process(bearerToken); JwtClaims claimsSet = jwtContext.getJwtClaims(); // We have to determine the unique name to use as the principal name. It comes from upn, preferred_username, sub in that order name = claimsSet.getClaimValue("upn", String.class); if (name == null) { name = claimsSet.getClaimValue("preferred_username", String.class); if (name == null) { name = claimsSet.getSubject(); } } } catch (Exception e) { jwtException = e; } } return name; }
Example #14
Source File: JWTokenFactory.java From eplmp with Eclipse Public License 1.0 | 5 votes |
public static JWTokenUserGroupMapping validateAuthToken(Key key, String jwt) { JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setVerificationKey(key) .setRelaxVerificationKeyValidation() .build(); try { JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt); String subject = jwtClaims.getSubject(); try (JsonReader reader = Json.createReader(new StringReader(subject))) { JsonObject subjectObject = reader.readObject(); // JsonParsingException String login = subjectObject.getString(SUBJECT_LOGIN); // Npe String groupName = subjectObject.getString(SUBJECT_GROUP_NAME); // Npe if (login != null && !login.isEmpty() && groupName != null && !groupName.isEmpty()) { return new JWTokenUserGroupMapping(jwtClaims, new UserGroupMapping(login, groupName)); } } } catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) { LOGGER.log(Level.FINE, "Cannot validate jwt token", e); } return null; }
Example #15
Source File: Jose4jJWKSTest.java From microprofile-jwt-auth with Apache License 2.0 | 5 votes |
@Override protected void validateToken(String token, URL jwksURL, String issuer, int expGracePeriodSecs) throws Exception { JwtConsumerBuilder builder = new JwtConsumerBuilder() .setRequireExpirationTime() .setRequireSubject() .setSkipDefaultAudienceValidation() .setExpectedIssuer(issuer) .setJwsAlgorithmConstraints( new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256)); HttpsJwks keySource = new HttpsJwks(jwksURL.toExternalForm()); List<JsonWebKey> keys = keySource.getJsonWebKeys(); JsonWebKey key = keys.get(0); if(key instanceof PublicJsonWebKey) { PublicJsonWebKey publicJsonWebKey = (PublicJsonWebKey) key; PublicKey pk = publicJsonWebKey.getPublicKey(); byte[] encoded = pk.getEncoded(); String pem = Base64.getEncoder().encodeToString(encoded); System.out.printf("pk.pem: %s\n", pem); } builder.setVerificationKeyResolver(new HttpsJwksVerificationKeyResolver(keySource)); if (expGracePeriodSecs > 0) { builder.setAllowedClockSkewInSeconds(expGracePeriodSecs); } else { builder.setEvaluationTime(NumericDate.fromSeconds(0)); } JwtConsumer jwtConsumer = builder.build(); JwtContext jwtContext = jwtConsumer.process(token); String type = jwtContext.getJoseObjects().get(0).getHeader("typ"); // Validate the JWT and process it to the Claims jwtConsumer.processContext(jwtContext); }
Example #16
Source File: Token.java From server_face_recognition with GNU General Public License v3.0 | 5 votes |
public static Token decypherToken(String token) { JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setRequireExpirationTime() .setAllowedClockSkewInSeconds(30) .setRequireSubject() .setExpectedIssuer("Sanstorik") .setExpectedAudience("User") .setVerificationKey(key.getKey()) .setJwsAlgorithmConstraints( new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256)) .build(); Token decypheredToken = null; try { JwtClaims jwtClaims = jwtConsumer.processToClaims(token); decypheredToken = new Token(token, jwtClaims.getClaimValue(USERNAME_KEY).toString(), jwtClaims.getClaimValue(PASSWORD_KEY).toString(), Integer.valueOf(jwtClaims.getClaimValue(USERID_KEY).toString()) ); } catch (InvalidJwtException e) { e.printStackTrace(); } return decypheredToken; }
Example #17
Source File: DefaultJWTTokenParser.java From smallrye-jwt with Apache License 2.0 | 5 votes |
void setExpectedAudience(JwtConsumerBuilder builder, JWTAuthContextInfo authContextInfo) { final Set<String> expectedAudience = authContextInfo.getExpectedAudience(); if (expectedAudience != null) { builder.setExpectedAudience(expectedAudience.toArray(new String[0])); } else { builder.setSkipDefaultAudienceValidation(); } }
Example #18
Source File: JwtAuthenticationServiceImplTest.java From blueocean-plugin with MIT License | 4 votes |
@Test public void anonymousUserToken() throws Exception{ j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); JenkinsRule.WebClient webClient = j.createWebClient(); String token = getToken(webClient); Assert.assertNotNull(token); JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token); Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature); JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure; String kid = jsw.getHeader("kid"); Assert.assertNotNull(kid); Page page = webClient.goTo("jwt-auth/jwks/"+kid+"/", "application/json"); // for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){ // System.out.println(valuePair); // } JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString()); RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject,null); JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setRequireExpirationTime() // the JWT must have an expiration time .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew .setRequireSubject() // the JWT must have a subject claim .setVerificationKey(rsaJsonWebKey.getKey()) // verify the sign with the public key .build(); // create the JwtConsumer instance JwtClaims claims = jwtConsumer.processToClaims(token); Assert.assertEquals("anonymous",claims.getSubject()); Map<String,Object> claimMap = claims.getClaimsMap(); Map<String,Object> context = (Map<String, Object>) claimMap.get("context"); Map<String,String> userContext = (Map<String, String>) context.get("user"); Assert.assertEquals("anonymous", userContext.get("id")); }
Example #19
Source File: RufusApplication.java From rufus with MIT License | 4 votes |
@Override public void run(RufusConfiguration conf, Environment env) throws Exception { final DBIFactory factory = new DBIFactory(); final DBI jdbi = factory.build(env, conf.getDataSourceFactory(), DB_SOURCE); final UserDao userDao = jdbi.onDemand(UserDao.class); final ArticleDao articleDao = jdbi.onDemand(ArticleDao.class); final FeedProcessorImpl processor = FeedProcessorImpl.newInstance(articleDao); final FeedParser parser = new FeedParser(articleDao, processor); final JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setAllowedClockSkewInSeconds(30) .setRequireExpirationTime() .setRequireSubject() .setVerificationKey(new HmacKey(VERIFICATION_KEY)) .setRelaxVerificationKeyValidation() .build(); final CachingJwtAuthenticator<User> cachingJwtAuthenticator = new CachingJwtAuthenticator<>( env.metrics(), new JwtAuthenticator(userDao), conf.getAuthenticationCachePolicy() ); env.jersey().register(new ArticleResource(userDao, articleDao, processor, parser)); env.jersey().register( new UserResource( new BasicAuthenticator(userDao), new TokenGenerator(VERIFICATION_KEY), userDao, articleDao ) ); //route source env.jersey().setUrlPattern(ROOT_PATH); env.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); env.jersey().register(new AuthDynamicFeature( new JwtAuthFilter.Builder<User>() .setJwtConsumer(jwtConsumer) .setRealm(REALM) .setPrefix(BEARER) .setAuthenticator(cachingJwtAuthenticator) .buildAuthFilter() )); }
Example #20
Source File: OAuth2Test.java From demo-spring-boot-security-oauth2 with MIT License | 4 votes |
@Before public void setup() { jwtConsumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature() .setSkipSignatureVerification().build(); }
Example #21
Source File: JWT_Encrypted_Validator_Callout.java From iloveapis2015-jwt-jwe-jws with Apache License 2.0 | 4 votes |
public ExecutionResult execute (MessageContext msgCtxt, ExecutionContext exeCtxt) { String varName; try { String encryptedJwt = getJwt(msgCtxt); // dot-separated JWT // diagnostic purposes varName = getVarname("jwt"); msgCtxt.setVariable(varName, encryptedJwt); RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(msgCtxt); BASE64Encoder b64 = new BASE64Encoder(); varName = getVarname("PrivateKey"); msgCtxt.setVariable(varName, b64.encode(privateKey.getEncoded())); /***************************RECEIVER'S END ***********************************/ JwtConsumer consumer = new JwtConsumerBuilder() //.setExpectedAudience("Admins") //.setExpectedIssuer("CA") //.setRequireSubject() //.setRequireExpirationTime() .setDecryptionKey(privateKey) .setDisableRequireSignature() .build(); JwtClaims receivedClaims = consumer.processToClaims(encryptedJwt); //System.out.println("SUCESS :: JWT Validation :: " + receivedClaims); String receivedClaimsJSON = receivedClaims.getRawJson(); varName = getVarname("receivedClaims"); msgCtxt.setVariable(varName, receivedClaimsJSON); } catch (Exception e) { //e.printStackTrace(); varName = getVarname("error"); msgCtxt.setVariable(varName, "Exception (A): " + e.toString()); varName = getVarname("stacktrace"); msgCtxt.setVariable(varName, "Stack (A): " + ExceptionUtils.getStackTrace(e)); } return ExecutionResult.SUCCESS; }
Example #22
Source File: TokenUtilsSignEncryptTest.java From microprofile-jwt-auth with Apache License 2.0 | 4 votes |
private void validateToken(String jweCompact, SignatureAlgorithm signatureAlgorithm, boolean jwtExpected) throws Exception { JsonWebEncryption jwe = new JsonWebEncryption(); jwe.setAlgorithmConstraints( new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, "RSA-OAEP")); jwe.setCompactSerialization(jweCompact); RSAPrivateKey privateKey = (RSAPrivateKey) TokenUtils.readPrivateKey("/privateKey.pem"); jwe.setKey(privateKey); String token = jwe.getPlaintextString(); if (jwtExpected) { if (!"JWT".equals(jwe.getHeader("cty"))) { throw new InvalidJwtException("'cty' header is missing", Collections.emptyList(), null); } } else { Assert.assertNull(jwe.getHeader("cty")); } // verify the nested token PublicKey publicKey = signatureAlgorithm == SignatureAlgorithm.RS256 ? TokenUtils.readPublicKey("/publicKey.pem") : TokenUtils.readECPublicKey("/ecPublicKey.pem"); int expGracePeriodSecs = 60; JwtConsumerBuilder builder = new JwtConsumerBuilder(); // 'exp' must be available builder.setRequireExpirationTime(); builder.setSkipDefaultAudienceValidation(); // 'iat' must be available builder.setRequireIssuedAt(); // 'RS256' is required builder.setJwsAlgorithmConstraints( new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, signatureAlgorithm.getAlgorithm())); // issuer must be equal to TCKConstants.TEST_ISSUER builder.setExpectedIssuer(true, TCKConstants.TEST_ISSUER); builder.setVerificationKey(publicKey); builder.setAllowedClockSkewInSeconds(expGracePeriodSecs); JwtClaims claimsSet = builder.build().processToClaims(token); // Confirm all the claims available in /Token1.json have made it into the verified claimSet Assert.assertEquals(claimsSet.getClaimsMap().size(), 19); Assert.assertEquals(claimsSet.getIssuer(), "https://server.example.com"); Assert.assertEquals(claimsSet.getJwtId(), "a-123"); Assert.assertEquals(claimsSet.getSubject(), "24400320"); Assert.assertEquals(claimsSet.getClaimValueAsString("upn"), "[email protected]"); Assert.assertEquals(claimsSet.getClaimValueAsString("preferred_username"), "jdoe"); Assert.assertEquals(claimsSet.getAudience().size(), 1); Assert.assertEquals(claimsSet.getAudience().get(0), "s6BhdRkqt3"); Assert.assertNotNull(claimsSet.getExpirationTime()); long exp = claimsSet.getExpirationTime().getValue(); Assert.assertEquals(claimsSet.getIssuedAt().getValue(), exp - 300); Assert.assertEquals(NumericDate.fromSeconds(claimsSet.getClaimValue("auth_time", Long.class)).getValue(), exp - 300); Assert.assertEquals(claimsSet.getClaimValueAsString("customString"), "customStringValue"); Assert.assertEquals(claimsSet.getClaimValue("customInteger", Long.class), Long.valueOf(123456789)); Assert.assertEquals(claimsSet.getClaimValue("customDouble", Double.class), 3.141592653589793); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("roles")).size(), 1); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("groups")).size(), 4); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("customStringArray")).size(), 3); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("customIntegerArray")).size(), 4); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("customDoubleArray")).size(), 5); Assert.assertEquals(((Map<?, ?>)claimsSet.getClaimsMap().get("customObject")).size(), 3); }
Example #23
Source File: TokenUtilsTest.java From microprofile-jwt-auth with Apache License 2.0 | 4 votes |
private void validateToken(String token, SignatureAlgorithm algorithm, Long expectedExpValue) throws Exception { PublicKey publicKey = algorithm == SignatureAlgorithm.RS256 ? TokenUtils.readPublicKey("/publicKey.pem") : TokenUtils.readECPublicKey("/ecPublicKey.pem"); int expGracePeriodSecs = 60; JwtConsumerBuilder builder = new JwtConsumerBuilder(); // 'exp' must be available builder.setRequireExpirationTime(); builder.setSkipDefaultAudienceValidation(); // 'iat' must be available builder.setRequireIssuedAt(); // 'RS256' is required builder.setJwsAlgorithmConstraints( new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, algorithm.getAlgorithm())); // issuer must be equal to TCKConstants.TEST_ISSUER builder.setExpectedIssuer(true, TCKConstants.TEST_ISSUER); builder.setVerificationKey(publicKey); builder.setAllowedClockSkewInSeconds(expGracePeriodSecs); JwtClaims claimsSet = builder.build().processToClaims(token); // Confirm all the claims available in /Token1.json have made it into the verified claimSet Assert.assertEquals(claimsSet.getClaimsMap().size(), 19); Assert.assertEquals(claimsSet.getIssuer(), "https://server.example.com"); Assert.assertEquals(claimsSet.getJwtId(), "a-123"); Assert.assertEquals(claimsSet.getSubject(), "24400320"); Assert.assertEquals(claimsSet.getClaimValueAsString("upn"), "[email protected]"); Assert.assertEquals(claimsSet.getClaimValueAsString("preferred_username"), "jdoe"); Assert.assertEquals(claimsSet.getAudience().size(), 1); Assert.assertEquals(claimsSet.getAudience().get(0), "s6BhdRkqt3"); if (expectedExpValue != null) { Assert.assertEquals(claimsSet.getExpirationTime().getValue(), (long)expectedExpValue); Assert.assertEquals(claimsSet.getIssuedAt().getValue(), expectedExpValue - 5); Assert.assertEquals(NumericDate.fromSeconds(claimsSet.getClaimValue("auth_time", Long.class)).getValue(), expectedExpValue - 5); } else { Assert.assertNotNull(claimsSet.getExpirationTime()); long exp = claimsSet.getExpirationTime().getValue(); Assert.assertEquals(claimsSet.getIssuedAt().getValue(), exp - 300); Assert.assertEquals(NumericDate.fromSeconds(claimsSet.getClaimValue("auth_time", Long.class)).getValue(), exp - 300); } Assert.assertEquals(claimsSet.getClaimValueAsString("customString"), "customStringValue"); Assert.assertEquals(claimsSet.getClaimValue("customInteger", Long.class), Long.valueOf(123456789)); Assert.assertEquals(claimsSet.getClaimValue("customDouble", Double.class), 3.141592653589793); Assert.assertTrue(claimsSet.getClaimValue("customBoolean", Boolean.class)); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("roles")).size(), 1); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("groups")).size(), 4); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("customStringArray")).size(), 3); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("customIntegerArray")).size(), 4); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("customDoubleArray")).size(), 5); Assert.assertEquals(((Map<?, ?>)claimsSet.getClaimsMap().get("customObject")).size(), 3); }
Example #24
Source File: TokenUtilsEncryptTest.java From microprofile-jwt-auth with Apache License 2.0 | 4 votes |
private void validateToken(String token, Long expectedExpValue) throws Exception { RSAPrivateKey privateKey = (RSAPrivateKey) TokenUtils.readPrivateKey("/privateKey.pem"); int expGracePeriodSecs = 60; JwtConsumerBuilder builder = new JwtConsumerBuilder(); builder.setDisableRequireSignature(); builder.setEnableRequireEncryption(); // 'exp' must be available builder.setRequireExpirationTime(); builder.setSkipDefaultAudienceValidation(); // 'iat' must be available builder.setRequireIssuedAt(); // 'RSA-OAEP' is required builder.setJwsAlgorithmConstraints( new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, "RSA-OAEP")); // issuer must be equal to TCKConstants.TEST_ISSUER builder.setExpectedIssuer(true, TCKConstants.TEST_ISSUER); builder.setDecryptionKey(privateKey); builder.setAllowedClockSkewInSeconds(expGracePeriodSecs); JwtClaims claimsSet = builder.build().processToClaims(token); // Confirm all the claims available in /Token1.json have made it into the verified claimSet Assert.assertEquals(claimsSet.getClaimsMap().size(), 19); Assert.assertEquals(claimsSet.getIssuer(), "https://server.example.com"); Assert.assertEquals(claimsSet.getJwtId(), "a-123"); Assert.assertEquals(claimsSet.getSubject(), "24400320"); Assert.assertEquals(claimsSet.getClaimValueAsString("upn"), "[email protected]"); Assert.assertEquals(claimsSet.getClaimValueAsString("preferred_username"), "jdoe"); Assert.assertEquals(claimsSet.getAudience().size(), 1); Assert.assertEquals(claimsSet.getAudience().get(0), "s6BhdRkqt3"); if (expectedExpValue != null) { Assert.assertEquals(claimsSet.getExpirationTime().getValue(), (long)expectedExpValue); Assert.assertEquals(claimsSet.getIssuedAt().getValue(), expectedExpValue - 5); Assert.assertEquals(NumericDate.fromSeconds(claimsSet.getClaimValue("auth_time", Long.class)).getValue(), expectedExpValue - 5); } else { Assert.assertNotNull(claimsSet.getExpirationTime()); long exp = claimsSet.getExpirationTime().getValue(); Assert.assertEquals(claimsSet.getIssuedAt().getValue(), exp - 300); Assert.assertEquals(NumericDate.fromSeconds(claimsSet.getClaimValue("auth_time", Long.class)).getValue(), exp - 300); } Assert.assertEquals(claimsSet.getClaimValueAsString("customString"), "customStringValue"); Assert.assertEquals(claimsSet.getClaimValue("customInteger", Long.class), Long.valueOf(123456789)); Assert.assertEquals(claimsSet.getClaimValue("customDouble", Double.class), 3.141592653589793); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("roles")).size(), 1); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("groups")).size(), 4); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("customStringArray")).size(), 3); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("customIntegerArray")).size(), 4); Assert.assertEquals(((List<?>)claimsSet.getClaimsMap().get("customDoubleArray")).size(), 5); Assert.assertEquals(((Map<?, ?>)claimsSet.getClaimsMap().get("customObject")).size(), 3); }
Example #25
Source File: PublicKeyAsJWKSTest.java From tomee with Apache License 2.0 | 4 votes |
@Test public void validateJWKS() throws Exception { System.setProperty(Names.VERIFIER_PUBLIC_KEY, ""); System.setProperty(Names.VERIFIER_PUBLIC_KEY_LOCATION, "file://" + Paths.get("").toAbsolutePath().toString() + "/src/test/resources/signer-keyset4k.jwk"); System.setProperty(Names.ISSUER, TCKConstants.TEST_ISSUER); final PrivateKey privateKey = TokenUtils.readPrivateKey("/privateKey4k.pem"); final String kid = "publicKey4k"; final String token = TokenUtils.generateTokenString(privateKey, kid, "/Token1.json", null, new HashMap<>()); System.out.println("token = " + token); final JWTAuthConfigurationProperties JWTAuthConfigurationProperties = new JWTAuthConfigurationProperties(); JWTAuthConfigurationProperties.init(null); final JWTAuthConfiguration jwtAuthConfiguration = JWTAuthConfigurationProperties.getJWTAuthConfiguration().orElseThrow(IllegalArgumentException::new); final JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder() .setRequireExpirationTime() .setRequireSubject() .setSkipDefaultAudienceValidation() .setExpectedIssuer(jwtAuthConfiguration.getIssuer()) .setJwsAlgorithmConstraints(new AlgorithmConstraints(WHITELIST, RSA_USING_SHA256)) .setSkipDefaultAudienceValidation() .setVerificationKey(jwtAuthConfiguration.getPublicKey()); if (jwtAuthConfiguration.getExpGracePeriodSecs() > 0) { jwtConsumerBuilder.setAllowedClockSkewInSeconds(jwtAuthConfiguration.getExpGracePeriodSecs()); } else { jwtConsumerBuilder.setEvaluationTime(NumericDate.fromSeconds(0)); } if (jwtAuthConfiguration.isSingleKey()) { jwtConsumerBuilder.setVerificationKey(jwtAuthConfiguration.getPublicKey()); } else { jwtConsumerBuilder.setVerificationKeyResolver(new JwksVerificationKeyResolver(jwtAuthConfiguration.getPublicKeys())); } final JwtConsumer jwtConsumer = jwtConsumerBuilder.build(); final JwtContext jwtContext = jwtConsumer.process(token); Assert.assertEquals(jwtContext.getJwtClaims().getStringClaimValue("upn"), "[email protected]"); }
Example #26
Source File: JwtAuthenticationServiceImplTest.java From blueocean-plugin with MIT License | 2 votes |
@Test public void getToken() throws Exception { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); User user = User.get("alice"); user.setFullName("Alice Cooper"); user.addProperty(new Mailer.UserProperty("[email protected]")); JenkinsRule.WebClient webClient = j.createWebClient(); webClient.login("alice"); String token = getToken(webClient); Assert.assertNotNull(token); JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token); Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature); JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure; System.out.println(token); System.out.println(jsw.toString()); String kid = jsw.getHeader("kid"); Assert.assertNotNull(kid); Page page = webClient.goTo("jwt-auth/jwks/"+kid+"/", "application/json"); // for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){ // System.out.println(valuePair); // } JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString()); System.out.println(jsonObject.toString()); RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject,null); JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setRequireExpirationTime() // the JWT must have an expiration time .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew .setRequireSubject() // the JWT must have a subject claim .setVerificationKey(rsaJsonWebKey.getKey()) // verify the sign with the public key .build(); // create the JwtConsumer instance JwtClaims claims = jwtConsumer.processToClaims(token); Assert.assertEquals("alice",claims.getSubject()); Map<String,Object> claimMap = claims.getClaimsMap(); Map<String,Object> context = (Map<String, Object>) claimMap.get("context"); Map<String,String> userContext = (Map<String, String>) context.get("user"); Assert.assertEquals("alice", userContext.get("id")); Assert.assertEquals("Alice Cooper", userContext.get("fullName")); Assert.assertEquals("[email protected]", userContext.get("email")); }