org.jose4j.jwt.NumericDate Java Examples

The following examples show how to use org.jose4j.jwt.NumericDate. 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: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void encOnlyWithIntegrityIssues() throws Exception
{
    String jwt = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..zWNzKpA-QA0BboVl02nz-A.oSy4V6cQ6EnuIMyazDCqc9jEZMC7k8LwLKkrC12Pf-wpFRyDtQjGdIZ_Ndq9JMAnrCbx0bgFSxjKISbXbcnHiA.QsGX3JhHP1Pwy4zQ8Ha9FQ";
    JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk("{\"kty\":\"oct\",\"k\":\"30WEMkbhwHPBkg_fIfm_4GuzIz5pPZB7_BSfI3dHbbQ\"}");
    DecryptionKeyResolver decryptionKeyResolver = new JwksDecryptionKeyResolver(Collections.singletonList(jsonWebKey));
    JwtConsumer consumer = new JwtConsumerBuilder()
            .setDecryptionKeyResolver(decryptionKeyResolver)
            .setEvaluationTime(NumericDate.fromSeconds(1420230888))
            .setExpectedAudience("me")
            .setExpectedIssuer("me")
            .setRequireExpirationTime()
            .setDisableRequireSignature()
            .build();

    JwtClaims jwtClaims = consumer.processToClaims(jwt);
    Assert.assertThat("value", equalTo(jwtClaims.getStringClaimValue("name")));

    // change some things and make sure it fails
    jwt = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..zWNzKpA-QA0BboVl02nz-A.eyJpc3MiOiJtZSIsImF1ZCI6Im1lIiwiZXhwIjoxNDIwMjMxNjA2LCJuYW1lIjoidmFsdWUifQ.QsGX3JhHP1Pwy4zQ8Ha9FQ";
    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, consumer);

    jwt = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..zWNzKpA-QA0BboVl02nz-A.u1D7JCpDFeRl69G1L-h3IRrmcOXiWLnhr23ugO2kkDqKVNcO1YQ4Xvl9Sag4aYOnkqUbqe6Wdz8KK3d9q178tA.QsGX3JhHP1Pwy4zQ8Ha9FQ";
    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, consumer);
}
 
Example #2
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void skipSignatureVerification() throws Exception
{
    String jwt = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9." +
            "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ." +
            "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";

    JwtConsumer consumer = new JwtConsumerBuilder()
            .setSkipSignatureVerification()
            .setEvaluationTime(NumericDate.fromSeconds(1300819372))
            .setExpectedIssuer("joe")
            .setRequireExpirationTime()
            .build();
    JwtContext context = consumer.process(jwt);
    Assert.assertTrue(context.getJwtClaims().getClaimValue("http://example.com/is_root", Boolean.class));
    assertThat(1, equalTo(context.getJoseObjects().size()));
}
 
Example #3
Source File: DefaultJWTTokenParser.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
private void verifyTimeToLive(JWTAuthContextInfo authContextInfo, JwtClaims claimsSet) throws ParseException {
    final Long maxTimeToLiveSecs = authContextInfo.getMaxTimeToLiveSecs();

    if (maxTimeToLiveSecs != null) {
        final NumericDate iat;
        final NumericDate exp;

        try {
            iat = claimsSet.getIssuedAt();
            exp = claimsSet.getExpirationTime();
        } catch (Exception e) {
            throw PrincipalMessages.msg.failedToVerifyMaxTTL(e);
        }

        if (exp.getValue() - iat.getValue() > maxTimeToLiveSecs) {
            throw PrincipalMessages.msg.expExceeded(exp, maxTimeToLiveSecs, iat);
        }
    } else {
        PrincipalLogging.log.noMaxTTLSpecified();
    }
}
 
Example #4
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test (expected = InvalidJwtSignatureException.class)
public void jwtBadSig() throws Exception
{
    String jwt = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9." +
            "eyJpc3MiOiJqb2UiLAogImV4cCI6MTkwMDgxOTM4MCwKICJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZX0." +
            "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
    String jwk = "{\"kty\":\"oct\",\"k\":\"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow\"}";

    JwtConsumer consumer = new JwtConsumerBuilder()
            .setVerificationKey(JsonWebKey.Factory.newJwk(jwk).getKey())
            .setEvaluationTime(NumericDate.fromSeconds(1900000380))
            .setExpectedIssuer("joe")
            .setRequireExpirationTime()
            .build();
    consumer.process(jwt);
}
 
Example #5
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
private static String createToken(Key key, JsonObject jsonClaims) {

        JwtClaims claims = new JwtClaims();
        claims.setSubject(jsonClaims.toString());
        claims.setIssuedAtToNow();
        claims.setExpirationTime(NumericDate.fromSeconds(NumericDate.now().getValue() + JWT_TOKEN_EXPIRES_TIME));

        JsonWebSignature jws = new JsonWebSignature();
        jws.setDoKeyValidation(false);
        jws.setPayload(claims.toJson());
        jws.setKey(key);
        jws.setAlgorithmHeaderValue(ALG);

        try {
            return jws.getCompactSerialization();
        } catch (JoseException ex) {
            LOGGER.log(Level.SEVERE, null, ex);
        }

        return null;
    }
 
Example #6
Source File: TokenHelper.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@NotNull
public static String createToken(@NotNull JsonWebEncryption jwe, @NotNull User user, @NotNull NumericDate expireAt) {
  try {
    JwtClaims claims = new JwtClaims();
    claims.setExpirationTime(expireAt);
    claims.setGeneratedJwtId(); // a unique identifier for the token
    claims.setIssuedAtToNow();  // when the token was issued/created (now)
    claims.setNotBeforeMinutesInThePast(0.5f); // time before which the token is not yet valid (30 seconds ago)
    if (!user.isAnonymous()) {
      claims.setSubject(user.getUsername()); // the subject/principal is whom the token is about
      setClaim(claims, "email", user.getEmail());
      setClaim(claims, "name", user.getRealName());
      setClaim(claims, "external", user.getExternalId());
      setClaim(claims, "type", user.getType().name());
    }
    jwe.setPayload(claims.toJson());
    return jwe.getCompactSerialization();
  } catch (JoseException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #7
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 #8
Source File: LfsAuthHelper.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@NotNull
private static Link createToken(
    @NotNull SharedContext context,
    @NotNull URI baseLfsUrl,
    @NotNull User user,
    int tokenExpireSec,
    float tokenEnsureTime
) {
  int expireSec = tokenExpireSec <= 0 ? LocalLfsConfig.DEFAULT_TOKEN_EXPIRE_SEC : tokenExpireSec;
  int ensureSec = (int) Math.ceil(expireSec * tokenEnsureTime);
  NumericDate now = NumericDate.now();
  NumericDate expireAt = NumericDate.fromSeconds(now.getValue() + expireSec);
  NumericDate ensureAt = NumericDate.fromSeconds(now.getValue() + ensureSec);
  return new Link(
      baseLfsUrl,
      createTokenHeader(context, user, expireAt),
      new Date(ensureAt.getValueInMillis())
  );
}
 
Example #9
Source File: JwtBuildUtils.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
static void setDefaultJwtClaims(JwtClaims claims) {

        long currentTimeInSecs = currentTimeInSecs();
        if (!claims.hasClaim(Claims.iat.name())) {
            claims.setIssuedAt(NumericDate.fromSeconds(currentTimeInSecs));
        }
        setExpiryClaim(claims);
        if (!claims.hasClaim(Claims.jti.name())) {
            claims.setGeneratedJwtId();
        }
        if (!claims.hasClaim(Claims.iss.name())) {
            String issuer = getConfigProperty("smallrye.jwt.new-token.issuer", String.class);
            if (issuer != null) {
                claims.setIssuer(issuer);
            }
        }
    }
 
Example #10
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
public static void refreshTokenIfNeeded(Key key, HttpServletResponse response, JWTokenUserGroupMapping jwTokenUserGroupMapping) {

        try {
            NumericDate expirationTime = jwTokenUserGroupMapping.getClaims().getExpirationTime();

            if (NumericDate.now().getValue() + JWT_TOKEN_REFRESH_BEFORE >= expirationTime.getValue()) {
                UserGroupMapping userGroupMapping = jwTokenUserGroupMapping.getUserGroupMapping();
                response.addHeader("jwt", createAuthToken(key, userGroupMapping));
            }

        } catch (MalformedClaimException e) {
            LOGGER.log(Level.FINE, "Cannot get expiration time from claims", e);
        }

    }
 
Example #11
Source File: TokenGenerator.java    From rufus with MIT License 5 votes vote down vote up
public static boolean isExpired(JwtContext context) {
    try {
        return context.getJwtClaims().getExpirationTime().isBefore(NumericDate.now());
    } catch (MalformedClaimException e) {
        logger.debug("failed to validate token {}", e);
        return false;
    }
}
 
Example #12
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isJWTValidBefore(Key key, int seconds, String authorizationString) {
    JWTokenUserGroupMapping jwTokenUserGroupMapping = validateAuthToken(key, authorizationString);
    if (jwTokenUserGroupMapping != null) {
        try {
            NumericDate issuedAt = jwTokenUserGroupMapping.getClaims().getIssuedAt();
            issuedAt.addSeconds(seconds);
            return NumericDate.now().isBefore(issuedAt);
        } catch (MalformedClaimException e) {
            return false;
        }
    }
    return false;
}
 
Example #13
Source File: JwtGenerator.java    From cloud-iot-core-androidthings with Apache License 2.0 5 votes vote down vote up
/**
 * Create JSON web token for a Google Cloud IoT project.
 *
 * @return JWT for project
 */
String createJwt() throws JoseException {
    Instant now = mClock.instant();

    mClaims.setIssuedAt(NumericDate.fromMilliseconds(now.toEpochMilli()));
    mClaims.setExpirationTime(
            NumericDate.fromMilliseconds(now.plus(mTokenLifetime).toEpochMilli()));

    mJws.setPayload(mClaims.toJson());
    return mJws.getCompactSerialization();
}
 
Example #14
Source File: TokenHelperTest.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void anonymous() {
  final User expected = User.getAnonymous();
  final String token = TokenHelper.createToken(createToken("secret"), expected, NumericDate.fromMilliseconds(System.currentTimeMillis() + 2000));
  final User actual = TokenHelper.parseToken(createToken("secret"), token, 0);
  Assert.assertEquals(actual, expected);
}
 
Example #15
Source File: TokenHelperTest.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void simpleWithExternal() {
  final User expected = User.create("foo", "bar", "[email protected]", "user-1", UserType.Local, null);
  final String token = TokenHelper.createToken(createToken("secret"), expected, NumericDate.fromMilliseconds(System.currentTimeMillis() + 2000));
  final User actual = TokenHelper.parseToken(createToken("secret"), token, 0);
  Assert.assertEquals(actual, expected);
}
 
Example #16
Source File: TokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
private static JwtClaims createJwtClaims(String jsonResName, Set<InvalidClaims> invalidClaims,
        Map<String, Long> timeClaims) throws Exception {
    
    String content = readJsonContent(jsonResName);
    JwtClaims claims = JwtClaims.parse(content);

    // Change the issuer to INVALID_ISSUER for failure testing if requested
    if (invalidClaims.contains(InvalidClaims.ISSUER)) {
        claims.setIssuer("INVALID_ISSUER");
    }
    long currentTimeInSecs = currentTimeInSecs();
    long exp = currentTimeInSecs + 300;
    long iat = currentTimeInSecs;
    long authTime = currentTimeInSecs;
    boolean expWasInput = false;
    // Check for an input exp to override the default of now + 300 seconds
    if (timeClaims != null && timeClaims.containsKey(Claims.exp.name())) {
        exp = timeClaims.get(Claims.exp.name());
        expWasInput = true;
    }
    // iat and auth_time should be before any input exp value
    if (expWasInput) {
        iat = exp - 5;
        authTime = exp - 5;
    }
    claims.setIssuedAt(NumericDate.fromSeconds(iat));
    claims.setClaim(Claims.auth_time.name(), authTime);
    // If the exp claim is not updated, it will be an old value that should be seen as expired
    if (!invalidClaims.contains(InvalidClaims.EXP)) {
        claims.setExpirationTime(NumericDate.fromSeconds(exp));
    }
    // Return the token time values if requested
    if (timeClaims != null) {
        timeClaims.put(Claims.iat.name(), iat);
        timeClaims.put(Claims.auth_time.name(), authTime);
        timeClaims.put(Claims.exp.name(), exp);
    }
    return claims;
}
 
Example #17
Source File: TokenHelperTest.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void simpleWithoutExternal() {
  final User expected = User.create("foo", "bar", "[email protected]", null, UserType.Local, null);
  final String token = TokenHelper.createToken(createToken("secret"), expected, NumericDate.fromMilliseconds(System.currentTimeMillis() + 2000));
  final User actual = TokenHelper.parseToken(createToken("secret"), token, 0);
  Assert.assertEquals(actual, expected);
}
 
Example #18
Source File: LfsAuthHelper.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
public static NumericDate getExpire(int tokenExpireSec) {
  // Calculate expire time and token.
  NumericDate expireAt = NumericDate.now();
  expireAt.addSeconds(tokenExpireSec <= 0 ? LocalLfsConfig.DEFAULT_TOKEN_EXPIRE_SEC : tokenExpireSec);
  return expireAt;
}
 
Example #19
Source File: LfsAuthHelper.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
public static Map<String, String> createTokenHeader(@NotNull SharedContext context,
                                                    @NotNull User user,
                                                    @NotNull NumericDate expireAt) {
  WebServer webServer = context.sure(WebServer.class);
  final String accessToken = TokenHelper.createToken(webServer.createEncryption(), user, expireAt);
  return ImmutableMap.<String, String>builder()
      .put(Constants.HEADER_AUTHORIZATION, WebServer.AUTH_TOKEN + accessToken)
      .build();
}
 
Example #20
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void nestedBackwards() throws Exception
{
    // a JWT that's a JWE inside a JWS, which is unusual but legal
    String jwt = "eyJjdHkiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.ZXlKNmFYQWlPaUpFUlVZaUxDSmhiR2NpT2lKRlEwUklMVVZUSWl3aVpXNWpJam9pUVRFeU9FTkNReTFJVXpJMU5pSXNJbVZ3YXlJNmV5SnJkSGtpT2lKRlF5SXNJbmdpT2lKYVIwczNWbkZOUzNKV1VGcEphRXc1UkRsT05tTnpNV0ZhYlU5MVpqbHlUWGhtUm1kRFVURjFaREJuSWl3aWVTSTZJbTAyZW01VlQybEtjMnMwTlRaRVVWb3RjVTEzZEVKblpqQkRNVXh4VDB0dk5HYzNjakpGUTBkQllUZ2lMQ0pqY25ZaU9pSlFMVEkxTmlKOWZRLi4xSndRWThoVFJVczdUMFNpOWM1VE9RLkFOdUpNcFowTU1KLTBrbVdvVHhvRDlxLTA1YUxrMkpvRzMxLXdVZ01ZakdaaWZiWG96SDEzZGRuaXZpWXNtenhMcFdVNU1lQnptN3J3TExTeUlCdjB3LmVEb1lFTEhFWXBnMHFpRzBaeHUtWEE.NctFu0mNSArPnMXakIMQKagWyU4v7733dNhDNK3KwiFP2MahpfaH0LA7x0knRk0sjASRxDuEIW6UZGfPTFOjkw";

    PublicJsonWebKey sigKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"HVDkXtG_j_JQUm_mNaRPSbsEhr6gdK0a6H4EURypTU0\",\"y\":\"NxdYFS2hl1w8VKf5UTpGXh2YR7KQ8gSBIHu64W0mK8M\",\"crv\":\"P-256\",\"d\":\"ToqTlgJLhI7AQYNLesI2i-08JuaYm2wxTCDiF-VxY4A\"}");
    PublicJsonWebKey encKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"7kaETHB4U9pCdsErbjw11HGv8xcQUmFy3NMuBa_J7Os\",\"y\":\"FZK-vSMpKk9gLWC5wdFjG1W_C7vgJtdm1YfNPZevmCw\",\"crv\":\"P-256\",\"d\":\"spOxtF0qiKrrCTaUs_G04RISjCx7HEgje_I7aihXVMY\"}");

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .build();
    JwtContext jwtContext = firstPassConsumer.process(jwt);

    JwtConsumer consumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420226222))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    JwtContext ctx = consumer.process(jwt);
    consumer.processContext(jwtContext);

    for (JwtContext context : new JwtContext[] {ctx, jwtContext})
    {
        JwtClaims jwtClaims = context.getJwtClaims();
        Assert.assertThat("eh", equalTo(jwtClaims.getStringClaimValue("message")));
        List<JsonWebStructure> joseObjects = context.getJoseObjects();
        assertThat(2, equalTo(joseObjects.size()));
        assertTrue(joseObjects.get(0) instanceof JsonWebEncryption);
        assertTrue(joseObjects.get(1) instanceof JsonWebSignature);
    }

}
 
Example #21
Source File: BoxDeveloperEditionAPIConnection.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
private String constructJWTAssertion(NumericDate now) {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(this.getClientID());
    claims.setAudience(JWT_AUDIENCE);
    if (now == null) {
        claims.setExpirationTimeMinutesInTheFuture(0.5f);
    } else {
        now.addSeconds(30L);
        claims.setExpirationTime(now);
    }
    claims.setSubject(this.entityID);
    claims.setClaim("box_sub_type", this.entityType.toString());
    claims.setGeneratedJwtId(64);

    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(this.decryptPrivateKey());
    jws.setAlgorithmHeaderValue(this.getAlgorithmIdentifier());
    jws.setHeader("typ", "JWT");
    if ((this.publicKeyID != null) && !this.publicKeyID.isEmpty()) {
        jws.setHeader("kid", this.publicKeyID);
    }

    String assertion;

    try {
        assertion = jws.getCompactSerialization();
    } catch (JoseException e) {
        throw new BoxAPIException("Error serializing JSON Web Token assertion.", e);
    }

    return assertion;
}
 
Example #22
Source File: BoxDeveloperEditionAPIConnection.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
private NumericDate getDateForJWTConstruction(BoxAPIException apiException, long secondsSinceResponseDateReceived) {
    NumericDate currentTime;
    List<String> responseDates = apiException.getHeaders().get("Date");

    if (responseDates != null) {
        String responseDate = responseDates.get(0);
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz");
        try {
            Date date = dateFormat.parse(responseDate);
            currentTime = NumericDate.fromMilliseconds(date.getTime());
            currentTime.addSeconds(secondsSinceResponseDateReceived);
        } catch (ParseException e) {
            currentTime = NumericDate.now();
        }
    } else {
        currentTime = NumericDate.now();
    }
    return currentTime;
}
 
Example #23
Source File: X509VerificationKeyResolverInJwtConsumerTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void x5tStuff() throws Exception
{
    String jwt = "eyJ4NXQiOiJaYjFIVDdyeUNSQUFqMndjUThoV2J6YXFYMXMiLCJhbGciOiJSUzI1NiJ9." +
            "eyJpc3MiOiJtZSIsImF1ZCI6InlvdSIsImV4cCI6MTQyMDI5NjI1Nywic3ViIjoiYWJvdXQifQ." +
            "RidDM9z0OJkfV2mwxABtEh2Gr_BCFbTuetOTV_dmnFofarBK7VDPPdsdAhtIs3u7WQq9guoo6H3AUGfj4mTFKX3axi2TsaYRKM9wSoRjx" +
            "FO7ednGcRGx8bnSerqqrbBuM9ZUUt93sIXuneJHYRKlh0Tt9mCXISv1H4OMEueXOJhck-JPgLPfLDqIPa8t93SULKTQtLvs8KEby2uJOL" +
            "8vIy-a-lFp9irCWwTnd0QRidpuLAPLr428LPNPycEVqD2TpY7y_xaQJh49oqoq_AmQCmIn3CpZLDLqD1wpEPxLQyd1vbvgQ583y2XJ95_" +
            "QufjbRd2Oshv3Z3JxpIm9Yie6yQ";

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .build();

    JwtContext jwtContext = firstPassConsumer.process(jwt);

    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setVerificationKeyResolver(new X509VerificationKeyResolver(CERT_LIST))
            .setEvaluationTime(NumericDate.fromSeconds(1420296253))
            .setExpectedAudience("you")
            .build();

    JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
    Assert.assertThat("about", CoreMatchers.equalTo(jwtClaims.getSubject()));
    jwtConsumer.processContext(jwtContext);
    Assert.assertThat("about", CoreMatchers.equalTo(jwtContext.getJwtClaims().getSubject()));

    jwtConsumer = new JwtConsumerBuilder()
            .setVerificationKeyResolver(new X509VerificationKeyResolver(CERT_LIST.get(0), CERT_LIST.get(2), CERT_LIST.get(3), CERT_LIST.get(4)))
            .setEvaluationTime(NumericDate.fromSeconds(1420296253))
            .setExpectedAudience("you")
            .build();

    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, jwtContext, jwtConsumer);
}
 
Example #24
Source File: X509VerificationKeyResolverInJwtConsumerTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void x5tS256Stuff() throws Exception
{
    String jwt = "eyJ4NXQjUzI1NiI6IkZTcU90QjV2UHFaNGtqWXAwOUZqQnBrbVhIMFZxRURtLXdFY1Rjb3g2RUUiLCJhbGciOiJFUzI1NiJ9." +
            "eyJpc3MiOiJtZSIsImF1ZCI6InlvdSIsImV4cCI6MTQyMDI5OTUzOSwic3ViIjoiYWJvdXQifQ." +
            "9Nj3UG8N9u7Eyu0wupR-eVS4Mf0ItwwHBZzwLcY2KUCJeWoPRPT7zC4MqMbHfLj6PzFi09iC3q3PniSJwmWJTA";

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .build();
    JwtContext jwtContext = firstPassConsumer.process(jwt);


    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setVerificationKeyResolver(new X509VerificationKeyResolver(CERT_LIST))
            .setEvaluationTime(NumericDate.fromSeconds(1420299538))
            .setExpectedAudience("you")
            .build();

    JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
    Assert.assertThat("about", CoreMatchers.equalTo(jwtClaims.getSubject()));
    jwtConsumer.processContext(jwtContext);
    Assert.assertThat("about", CoreMatchers.equalTo(jwtContext.getJwtClaims().getSubject()));

    jwtConsumer = new JwtConsumerBuilder()
            .setVerificationKeyResolver(new X509VerificationKeyResolver(CERT_LIST.get(0),CERT_LIST.get(1), CERT_LIST.get(2), CERT_LIST.get(3)))
            .setEvaluationTime(NumericDate.fromSeconds(1420299538))
            .setExpectedAudience("you")
            .build();

    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, jwtContext, jwtConsumer);
}
 
Example #25
Source File: X509VerificationKeyResolverInJwtConsumerTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void bothX5headersStuff() throws Exception
{
    String jwt = "eyJ4NXQjUzI1NiI6InFTX2JYTlNfSklYQ3JuUmdha2I2b3RFS3Utd0xlb3R6N0tBWjN4UVVPcUUiLCJ4NXQiOiJpSFFLdVNHZVdVR1laQ2c0X1JHSlNJQzBORFEiLCJhbGciOiJFUzI1NiJ9." +
            "eyJpc3MiOiJtZSIsImF1ZCI6InlvdSIsImV4cCI6MTQyMDI5OTc2MSwic3ViIjoiYWJvdXQifQ." +
            "04qPYooLJN2G0q0LYVepaydszTuhY7jKjqi5IGkNBAWZ-IBlW_pWzkurR1MkO48SbJQK2swmy7Ogfihi1ClAlA";

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .build();
    JwtContext jwtContext = firstPassConsumer.process(jwt);


    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setVerificationKeyResolver(new X509VerificationKeyResolver(CERT_LIST))
            .setEvaluationTime(NumericDate.fromSeconds(1420299760))
            .setExpectedAudience("you")
            .build();

    JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
    Assert.assertThat("about", CoreMatchers.equalTo(jwtClaims.getSubject()));
    jwtConsumer.processContext(jwtContext);
    Assert.assertThat("about", CoreMatchers.equalTo(jwtContext.getJwtClaims().getSubject()));

    jwtConsumer = new JwtConsumerBuilder()
            .setVerificationKeyResolver(new X509VerificationKeyResolver(CERT_LIST.get(0),CERT_LIST.get(1), CERT_LIST.get(2), CERT_LIST.get(4)))
            .setEvaluationTime(NumericDate.fromSeconds(1420299760))
            .setExpectedAudience("you")
            .build();

    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, jwtContext, jwtConsumer);
}
 
Example #26
Source File: JwksDecryptionKeyResolverUsingJwtConsumerTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testSymmetricKeysWithAesWrap() throws Exception
{
    String json = "{\"keys\":[" +
            "{\"kty\":\"oct\",\"kid\":\"1one\",\"k\":\"_-cqzgJ-_aeZkppR2JCOlx\"}," +
            "{\"kty\":\"oct\",\"kid\":\"deux\",\"k\":\"mF2rZpj_Fbeal5FRz0c0Lw\"}," +
            "{\"kty\":\"oct\",\"kid\":\"tres\",\"k\":\"ad2-dGiApcezx9310j4o7W\"}]}";
    JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(json);

    String jwt = "eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2Iiwia2lkIjoiZGV1eCJ9" +
            ".UHa0kaUhz8QDHE_CVfpeC-ebzXapjJrQ5Lk4r8XvK1J5WD32UeZ3_A" +
            ".3pPAmmVX_elO_9lgfJJXiA" +
            ".8pNNdQ_BsTwFicdrCevByA4i7KAzb__qF6z6olEQ3M8HayMAwOJoeF0yhnkM0JcydcCiULRE_i8USvpXWiktBhIJ79nDlqHxK09JB6YGnkpBMZgAmWf1NJFmTlF4vRs6" +
            ".3_UixCVYQsUablSjTX8v2A";

    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setEvaluationTime(NumericDate.fromSeconds(1424026062))
            .setRequireExpirationTime()
            .setExpectedIssuer("from")
            .setExpectedAudience("to")
            .setDecryptionKeyResolver(new JwksDecryptionKeyResolver(jsonWebKeySet.getJsonWebKeys()))
            .setDisableRequireSignature()
            .build();

    JwtContext jwtCtx = jwtConsumer.process(jwt);
    Assert.assertThat(jwtCtx.getJoseObjects().size(), CoreMatchers.equalTo(1));
    Assert.assertThat(jwtCtx.getJwtClaims().getSubject(), CoreMatchers.equalTo("Scott Tomilson, not Tomlinson"));
}
 
Example #27
Source File: TokenHelperTest.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void invalidToken() {
  final User expected = User.create("foo", "bar", "[email protected]", null, UserType.Local, null);
  final String token = TokenHelper.createToken(createToken("big secret"), expected, NumericDate.fromMilliseconds(System.currentTimeMillis() + 2000));
  final User actual = TokenHelper.parseToken(createToken("small secret"), token, 0);
  Assert.assertNull(actual);
}
 
Example #28
Source File: TokenHelperTest.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void expiredToken() {
  final User expected = User.create("foo", "bar", "[email protected]", null, UserType.Local, null);
  final String token = TokenHelper.createToken(createToken("secret"), expected, NumericDate.fromMilliseconds(System.currentTimeMillis() - 2000));
  final User actual = TokenHelper.parseToken(createToken("secret"), token, 0);
  Assert.assertNull(actual);
}
 
Example #29
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void hmacWithResolver() throws Exception
{
    String jwt = "eyJraWQiOiJfMyIsImFsZyI6IkhTMjU2In0" +
            ".eyJpc3MiOiJmcm9tIiwiYXVkIjpbInRvIiwib3J5b3UiXSwiZXhwIjoxNDI0MDQxNTc0LCJzdWIiOiJhYm91dCJ9" +
            ".jgC4hWHd1C4kkYiVIbung4vg44bQOEv3JkGupnRrYDk";

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .build();
    JwtContext jwtContext = firstPassConsumer.process(jwt);


    String json = "{\"keys\":[" +
            "{\"kty\":\"oct\",\"kid\":\"_1\",  \"k\":\"9g99cnHIc3kMeR_JbwmAojgUlHIH0GoKz7COz9719x1\"}," +
            "{\"kty\":\"oct\",\"kid\":\"_2\",  \"k\":\"vvlp7BacRr-a9pOKK7BKxZo88u6cY2o9Lz6-P--_01p\"}," +
            "{\"kty\":\"oct\",\"kid\":\"_3\",\"k\":\"a991cccx6-7rP5p91nnHi3K-jcDjsFh1o34bIeWA081\"}]}";

    JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(json);

    JwtConsumer consumer = new JwtConsumerBuilder()
            .setEvaluationTime(NumericDate.fromSeconds(1424041569))
            .setExpectedAudience("to")
            .setExpectedIssuer("from")
            .setRequireSubject()
            .setVerificationKeyResolver(new JwksVerificationKeyResolver(jsonWebKeySet.getJsonWebKeys()))
            .setRequireExpirationTime()
            .build();

    JwtContext ctx = consumer.process(jwt);
    consumer.processContext(jwtContext);

    for (JwtContext context : new JwtContext[] {ctx, jwtContext})
    {
        assertThat(1, equalTo(context.getJoseObjects().size()));
        assertThat("about", equalTo(context.getJwtClaims().getSubject()));
    }
}
 
Example #30
Source File: OpenIDConnectAuthenticator.java    From java with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isExpired(Map<String, Object> config) {
  String idToken = (String) config.get(OIDC_ID_TOKEN);

  if (idToken == null) {
    return true;
  } else {
    JsonWebSignature jws = new JsonWebSignature();
    try {
      jws.setCompactSerialization(idToken);
      // we don't care if its valid or not cryptographicly as the only way to verify is to query
      // the remote identity provider's configuration url which is the same chanel as the token
      // request.  If there is a malicious proxy there's no way for the client to know.  Also,
      // the client doesn't need to trust the, token, only bear it to the server which will verify
      // it.

      String jwt = jws.getUnverifiedPayload();
      JwtClaims claims = JwtClaims.parse(jwt);

      // expired now is >= expiration AND exp is present
      return claims.getExpirationTime() == null
          || NumericDate.now().isOnOrAfter(claims.getExpirationTime());
    } catch (JoseException | InvalidJwtException | MalformedClaimException e) {
      throw new RuntimeException(e);
    }
  }
}