當前位置: 首頁>>代碼示例>>Java>>正文


Java JwtClaims.setExpirationTime方法代碼示例

本文整理匯總了Java中org.jose4j.jwt.JwtClaims.setExpirationTime方法的典型用法代碼示例。如果您正苦於以下問題:Java JwtClaims.setExpirationTime方法的具體用法?Java JwtClaims.setExpirationTime怎麽用?Java JwtClaims.setExpirationTime使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.jose4j.jwt.JwtClaims的用法示例。


在下文中一共展示了JwtClaims.setExpirationTime方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testPastEXPCLaim

import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
/**
 * Test proper signed token already expired.
 * @throws JoseException
 */
@Test(expected=SSOException.class)
public void testPastEXPCLaim() throws JoseException, SSOException  {

  RsaJsonWebKey jwk = this.generateRsaJwk();
  JwtClaims claims = this.createMalformedClaims();

  NumericDate exp = NumericDate.now();
  exp.addSeconds(-3600);

  claims.setExpirationTime(exp);
  claims.setIssuedAtToNow();
  claims.setNotBeforeMinutesInThePast(2);

  String jwt = this.createSignedTokenFromClaims(claims, jwk);

  final SSOFacade ssoFac = SSOFacade.create(jwk.getRsaPublicKey());
  ssoFac.verify(jwt);
 }
 
開發者ID:Staffbase,項目名稱:plugins-sdk-java,代碼行數:23,代碼來源:SSOFacadeTest.java

示例2: createToken

import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
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;
    }
 
開發者ID:polarsys,項目名稱:eplmp,代碼行數:22,代碼來源:JWTokenFactory.java

示例3: signToken

import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
/**
 * Signs an JWT authentication token, acting as simulated authentication
 * endpoint that issues auth tokens.
 *
 * @param tokenIssuer
 * @param signatureKeyPair
 * @param expirationTime
 *            Expiration time in minutes to set for {@code exp} claim. Can
 *            be <code>null</code>, in which case the header is left out.
 * @return
 * @throws JoseException
 */
private String signToken(String tokenIssuer, RsaJsonWebKey signatureKeyPair, DateTime expirationTime)
        throws JoseException {
    // Create the Claims, which will be the content of the JWT
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(tokenIssuer);
    if (expirationTime != null) {
        claims.setExpirationTime(NumericDate.fromMilliseconds(expirationTime.getMillis()));
    }
    claims.setGeneratedJwtId();
    NumericDate now = NumericDate.fromMilliseconds(UtcTime.now().getMillis());
    claims.setIssuedAt(now);
    // the subject/principal is whom the token is about
    claims.setSubject(TOKEN_SUBJECT);
    // additional claims
    claims.setClaim("role", TOKEN_ROLE);

    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(signatureKeyPair.getPrivateKey());
    jws.setKeyIdHeaderValue(signatureKeyPair.getKeyId());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    return jws.getCompactSerialization();
}
 
開發者ID:elastisys,項目名稱:scale.commons,代碼行數:36,代碼來源:TestAuthTokenHeaderValidator.java

示例4: signToken

import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
/**
 * Signs an JWT authentication token, acting as simulated authentication
 * endpoint that issues auth tokens.
 *
 * @param tokenIssuer
 * @param signatureKeyPair
 * @param expirationTime
 *            Expiration time in minutes to set for {@code exp} claim. Can
 *            be <code>null</code>, in which case the header is left out.
 * @return
 * @throws JoseException
 */
private String signToken(String tokenIssuer, RsaJsonWebKey signatureKeyPair, DateTime expirationTime)
        throws JoseException {
    // Create the Claims, which will be the content of the JWT
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(tokenIssuer);
    if (expirationTime != null) {
        claims.setExpirationTime(NumericDate.fromMilliseconds(expirationTime.getMillis()));
    }
    claims.setGeneratedJwtId();
    NumericDate now = NumericDate.fromMilliseconds(UtcTime.now().getMillis());
    claims.setIssuedAt(now);
    // the subject/principal is whom the token is about
    claims.setSubject("[email protected]");
    // additional claims
    claims.setClaim("role", "user");

    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(signatureKeyPair.getPrivateKey());
    jws.setKeyIdHeaderValue(signatureKeyPair.getKeyId());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    return jws.getCompactSerialization();
}
 
開發者ID:elastisys,項目名稱:scale.commons,代碼行數:36,代碼來源:TestAuthTokenRequestFilter.java

示例5: createToken

import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
@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());
    }
    jwe.setPayload(claims.toJson());
    return jwe.getCompactSerialization();
  } catch (JoseException e) {
    throw new IllegalStateException(e);
  }
}
 
開發者ID:bozaro,項目名稱:git-as-svn,代碼行數:21,代碼來源:TokenHelper.java

示例6: generateAuthToken

import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
/**
 * Generate an auth token with the given claims and sign the token with the
 * private key in the provided {@link RsaJsonWebKey}.
 */
public static String generateAuthToken(
    Optional<Collection<String>> audiences,
    Optional<String> email,
    NumericDate expirationTime,
    Optional<String> issuer,
    NumericDate notBefore,
    Optional<String> subject,
    RsaJsonWebKey rsaJsonWebKey) {
  JwtClaims claims = new JwtClaims();
  if (audiences.isPresent()) {
    claims.setAudience(ImmutableList.copyOf(audiences.get()));
  }
  if (email.isPresent()) {
    claims.setClaim("email", email.get());
  }
  if (issuer.isPresent()) {
    claims.setIssuer(issuer.get());
  }
  if (subject.isPresent()) {
    claims.setSubject(subject.get());
  }
  claims.setExpirationTime(expirationTime);
  claims.setNotBefore(notBefore);

  JsonWebSignature jsonWebSignature = new JsonWebSignature();
  jsonWebSignature.setPayload(claims.toJson());
  jsonWebSignature.setKey(rsaJsonWebKey.getPrivateKey());
  jsonWebSignature.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
  jsonWebSignature.setAlgorithmHeaderValue(rsaJsonWebKey.getAlgorithm());

  try {
    return jsonWebSignature.getCompactSerialization();
  } catch (JoseException exception) {
    throw new RuntimeException("failed to generate JWT", exception);
  }
}
 
開發者ID:cloudendpoints,項目名稱:endpoints-management-java,代碼行數:41,代碼來源:TestUtils.java

示例7: getToken

import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
public String getToken(TokenDTO data) {

	try {

	    ZonedDateTime expiration = ZonedDateTime.now(ZoneOffset.UTC).plus(daysOfValidity, ChronoUnit.DAYS);

	    Key key = new HmacKey(secret.getBytes("UTF-8"));

	    JwtClaims claims = new JwtClaims();
	    claims.setExpirationTime(NumericDate.fromMilliseconds(expiration.toInstant().toEpochMilli()));
	    claims.setGeneratedJwtId();
	    claims.setIssuedAtToNow();
	    claims.setNotBeforeMinutesInThePast(2);
	    claims.setSubject(data.getSubject());
	    claims.setIssuer(data.getIssuer());
	    claims.setClaim(EMAIL_KEY, data.getEmail());

	    JsonWebSignature jws = new JsonWebSignature();
	    jws.setPayload(claims.toJson());
	    jws.setKey(key);
	    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);

	    return jws.getCompactSerialization();

	} catch (JoseException | UnsupportedEncodingException e) {
	    throw new RuntimeException("An error occured while building a token", e);
	}

    }
 
開發者ID:tomacla,項目名稱:auth-token,代碼行數:30,代碼來源:TokenManager.java

示例8: constructJWTAssertion

import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
private String constructJWTAssertion(NumericDate now) {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(this.getClientID());
    claims.setAudience(JWT_AUDIENCE);
    if (now == null) {
        claims.setExpirationTimeMinutesInTheFuture(1.0f);
    } else {
        now.addSeconds(60L);
        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;
}
 
開發者ID:box,項目名稱:box-java-sdk,代碼行數:34,代碼來源:BoxDeveloperEditionAPIConnection.java

示例9: handleJwtAssertionGrant

import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
/**
 * Takes an assertion and converts it using an {@link InternalClaimsBuilder} to
 * a JWT used internally
 *
 * @param assertion
 *            an external JWT assertion
 * @param clientId
 *            client ID
 * @return OAuth response
 */
private OAuthTokenResponse handleJwtAssertionGrant(final String assertion,
    final String clientId,
    final String audience) {

    if (assertion == null) {
        throw ErrorResponses.badRequest(ErrorCodes.INVALID_REQUEST, "Missing assertion");
    }
    if (clientId == null) {
        throw ErrorResponses.badRequest(ErrorCodes.INVALID_REQUEST, "Missing client_id");
    }

    try {
        final URI jwksUri = clientValidator.getJwksUri(clientId);
        LOG.debug("jwksUri={}", jwksUri);
        HttpsJwks httpsJwks = null;
        if (jwksUri != null) {
            httpsJwks = jwksMap.computeIfAbsent(jwksUri, uri -> new HttpsJwks(uri.toASCIIString()));
        }

        final JwtConsumerBuilder builder = new JwtConsumerBuilder();

        if (httpsJwks == null) {
            builder.setDisableRequireSignature()
                .setSkipSignatureVerification();
        } else {
            builder.setVerificationKeyResolver(new HttpsJwksVerificationKeyResolver(httpsJwks));
        }
        if (audience == null) {
            builder.setExpectedAudience(clientId);
        } else {
            builder.setExpectedAudience(clientId, audience);
        }
        final JwtConsumer jwtConsumer = builder
            .build();

        final JwtClaims internalClaims = internalClaimsBuilder.buildInternalJWTClaimsSet(jwtConsumer.processToClaims(assertion));

        if (internalClaims.getSubject() == null) {
            LOG.error("Subject is missing from {}", internalClaims);
            throw ErrorResponses.internalServerError("Subject is missing from the resulting claims set.");
        }

        internalClaims.setGeneratedJwtId();
        internalClaims.setIssuer(issuer.toASCIIString());
        if (audience == null) {
            internalClaims.setAudience(clientId);
        } else {
            internalClaims.setAudience(clientId, audience);
        }
        internalClaims.setIssuedAtToNow();

        final Instant expirationTime = Instant.now().plus(jwtMaximumLifetimeInSeconds, ChronoUnit.SECONDS);
        internalClaims.setExpirationTime(NumericDate.fromMilliseconds(expirationTime.toEpochMilli()));

        return tokenCache.store(cryptoOps.sign(internalClaims), internalClaims.getAudience(), expirationTime);

    } catch (final MalformedClaimException
        | InvalidJwtException e) {
        LOG.error("Unable to parse assertion", e);
        throw ErrorResponses.badRequest(ErrorCodes.INVALID_REQUEST, "Unable to parse assertion");
    }
}
 
開發者ID:trajano,項目名稱:app-ms,代碼行數:73,代碼來源:TokenResource.java

示例10: getJwt

import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
private static String getJwt(int expiredInSeconds) throws Exception {
    JwtClaims claims = getTestClaims();
    claims.setExpirationTime(NumericDate.fromMilliseconds(System.currentTimeMillis() + expiredInSeconds * 1000));
    return getJwt(claims);
}
 
開發者ID:networknt,項目名稱:light-4j,代碼行數:6,代碼來源:Http2ClientIT.java

示例11: encode

import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
@Override
public String encode(
        String jti, String issuer, String subject, Date currentTime, String method, String path, String contentHashAlgorithm, String contentHash
) throws JWTError {
    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setJwtId(jti);
    jwtClaims.setIssuer(issuer);
    jwtClaims.setSubject(subject);
    jwtClaims.setAudience(apiIdentifier);

    NumericDate now = NumericDate.fromMilliseconds(currentTime.getTime());
    jwtClaims.setIssuedAt(now);
    jwtClaims.setNotBefore(now);

    NumericDate exp = NumericDate.fromMilliseconds(currentTime.getTime());
    exp.addSeconds((long) requestExpireSeconds);
    jwtClaims.setExpirationTime(exp);

    Map<String, String> request = new HashMap<>();
    //noinspection SpellCheckingInspection
    request.put("meth", method);
    request.put("path", path);
    if (contentHashAlgorithm != null) {
        request.put("func", contentHashAlgorithm);
        request.put("hash", contentHash);
    }
    jwtClaims.setClaim("request", request);

    JsonWebSignature jws = new JsonWebSignature();
    jws.setKeyIdHeaderValue(currentPrivateKeyId);
    jws.setKey(privateKeys.get(currentPrivateKeyId));
    jws.setPayload(jwtClaims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    String jwt;
    try {
        jwt = jws.getCompactSerialization();
    } catch (JoseException e) {
        throw new JWTError("An error occurred encoding the JWT", e);
    }
    return jwt;
}
 
開發者ID:iovation,項目名稱:launchkey-java,代碼行數:43,代碼來源:Jose4jJWTService.java


注:本文中的org.jose4j.jwt.JwtClaims.setExpirationTime方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。