org.jose4j.jwt.consumer.JwtConsumer Java Examples

The following examples show how to use org.jose4j.jwt.consumer.JwtConsumer. 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: Jose4jVerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: JwtAuthProviderTest.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: JwtAuthApplication.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: BoxDeveloperEditionAPIConnectionTest.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: OauthHelperTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: JwtHelper.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
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 #8
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
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 #9
Source File: Jose4jJWKSTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@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 #10
Source File: JwtUtil.java    From light with Apache License 2.0 5 votes vote down vote up
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 #11
Source File: JWTCredential.java    From thorntail with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #12
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
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 #13
Source File: Token.java    From server_face_recognition with GNU General Public License v3.0 5 votes vote down vote up
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 #14
Source File: JWT_Encrypted_Validator_Callout.java    From iloveapis2015-jwt-jwe-jws with Apache License 2.0 4 votes vote down vote up
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 #15
Source File: JwtAuthenticationServiceImplTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@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 #16
Source File: JwtAuthFilter.java    From dropwizard-auth-jwt with Apache License 2.0 4 votes vote down vote up
private JwtAuthFilter(JwtConsumer consumer, String cookieName) {
    this.consumer = consumer;
    this.cookieName = cookieName;
}
 
Example #17
Source File: JwtAuthFilter.java    From dropwizard-auth-jwt with Apache License 2.0 4 votes vote down vote up
public Builder<P> setJwtConsumer(JwtConsumer consumer) {
    this.consumer = consumer;
    return this;
}
 
Example #18
Source File: RufusApplication.java    From rufus with MIT License 4 votes vote down vote up
@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 #19
Source File: PublicKeyAsJWKSTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
@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 #20
Source File: JwtAuthenticationServiceImplTest.java    From blueocean-plugin with MIT License 2 votes vote down vote up
@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"));
    }