Java Code Examples for com.nimbusds.jwt.JWTClaimsSet#setIssueTime()

The following examples show how to use com.nimbusds.jwt.JWTClaimsSet#setIssueTime() . 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: ZendeskRedirectServlet.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {

  if (shared_key == null || subdomain == null)
    throw new ServletException("Zendesk is not configured.");
  // Given a user instance
  // Compose the JWT claims set
  JWTClaimsSet jwtClaims = new JWTClaimsSet();
  jwtClaims.setIssueTime(new Date());
  jwtClaims.setJWTID(UUID.randomUUID().toString());
  Subject subject = EnvironmentContext.getCurrent().getSubject();
  jwtClaims.setCustomClaim("name", getName());
  jwtClaims.setCustomClaim("email", subject.getUserName());
  // Create JWS header with HS256 algorithm
  JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
  JWSObject jwsObject = new JWSObject(header, new Payload(jwtClaims.toJSONObject()));
  // Create HMAC signer
  JWSSigner signer = new MACSigner(shared_key.getBytes());
  try {
    jwsObject.sign(signer);
  } catch (JOSEException e) {
    String msg = String.format("Error signing JWT: %s", e.getMessage());
    LOG.warn(msg);
    response.sendError(500, msg);
  }
  // Serialise to JWT compact form
  String jwtString = jwsObject.serialize();
  String redirectUrl = "https://" + subdomain + ".zendesk.com/access/jwt?jwt=" + jwtString;
  response.sendRedirect(redirectUrl);
}
 
Example 2
Source File: JWTAccessTokenBuilder.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * To build id token from OauthToken request message context
 *
 * @param request Token request message context
 * @return Signed jwt string.
 * @throws IdentityOAuth2Exception
 */
protected String buildIDToken(OAuthTokenReqMessageContext request)
        throws IdentityOAuth2Exception {

    String issuer = OAuth2Util.getIDTokenIssuer();
    long lifetimeInMillis = OAuthServerConfiguration.getInstance().
            getApplicationAccessTokenValidityPeriodInSeconds() * 1000;
    long curTimeInMillis = Calendar.getInstance().getTimeInMillis();
    // setting subject
    String subject = request.getAuthorizedUser().getAuthenticatedSubjectIdentifier();
    if (!StringUtils.isNotBlank(subject)) {
        subject = request.getAuthorizedUser().getUserName();
    }
    // Set claims to jwt token.
    JWTClaimsSet jwtClaimsSet = new JWTClaimsSet();
    jwtClaimsSet.setIssuer(issuer);
    jwtClaimsSet.setSubject(subject);
    jwtClaimsSet.setAudience(Arrays.asList(request.getOauth2AccessTokenReqDTO().getClientId()));
    jwtClaimsSet.setClaim(Constants.AUTHORIZATION_PARTY, request.getOauth2AccessTokenReqDTO().getClientId());
    jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis));
    jwtClaimsSet.setIssueTime(new Date(curTimeInMillis));
    addUserClaims(jwtClaimsSet, request.getAuthorizedUser());

    if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) {
        return new PlainJWT(jwtClaimsSet).serialize();
    }
    return signJWT(jwtClaimsSet, request);
}
 
Example 3
Source File: JWTAccessTokenBuilder.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Build a signed jwt token from authorization request message context
 *
 * @param request Oauth authorization message context
 * @return Signed jwt string
 * @throws IdentityOAuth2Exception
 */
protected String buildIDToken(OAuthAuthzReqMessageContext request)
        throws IdentityOAuth2Exception {

    String issuer = OAuth2Util.getIDTokenIssuer();
    long lifetimeInMillis = OAuthServerConfiguration.getInstance().
            getApplicationAccessTokenValidityPeriodInSeconds() * 1000;
    long curTimeInMillis = Calendar.getInstance().getTimeInMillis();
    // setting subject
    String subject = request.getAuthorizationReqDTO().getUser().getAuthenticatedSubjectIdentifier();

    if (!StringUtils.isNotBlank(subject)) {
        subject = request.getAuthorizationReqDTO().getUser().getUserName();
    }

    JWTClaimsSet jwtClaimsSet = new JWTClaimsSet();
    jwtClaimsSet.setIssuer(issuer);
    jwtClaimsSet.setSubject(subject);
    jwtClaimsSet.setAudience(Arrays.asList(request.getAuthorizationReqDTO().getConsumerKey()));
    jwtClaimsSet.setClaim(Constants.AUTHORIZATION_PARTY, request.getAuthorizationReqDTO().getConsumerKey());
    jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis));
    jwtClaimsSet.setIssueTime(new Date(curTimeInMillis));
    addUserClaims(jwtClaimsSet, request.getAuthorizationReqDTO().getUser());

    if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) {
        return new PlainJWT(jwtClaimsSet).serialize();
    }
    return signJWT(jwtClaimsSet, request);
}
 
Example 4
Source File: AuthUtils.java    From blog with MIT License 5 votes vote down vote up
public static Token createToken(String host, long sub) throws JOSEException {
  JWTClaimsSet claim = new JWTClaimsSet();
  claim.setSubject(Long.toString(sub));
  claim.setIssuer(host);
  claim.setIssueTime(DateTime.now().toDate());
  claim.setExpirationTime(DateTime.now().plusDays(14).toDate());

  JWSSigner signer = new MACSigner(TOKEN_SECRET);
  SignedJWT jwt = new SignedJWT(JWT_HEADER, claim);
  jwt.sign(signer);

  return new Token(jwt.serialize());
}
 
Example 5
Source File: DefaultIDTokenBuilder.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public String buildIDToken(OAuthAuthzReqMessageContext request, OAuth2AuthorizeRespDTO tokenRespDTO)
        throws IdentityOAuth2Exception {

    String issuer = OAuth2Util.getIDTokenIssuer();
    long lifetimeInMillis = Integer.parseInt(config.getOpenIDConnectIDTokenExpiration()) * 1000;
    long curTimeInMillis = Calendar.getInstance().getTimeInMillis();
    // setting subject
    String subject = request.getAuthorizationReqDTO().getUser().getAuthenticatedSubjectIdentifier();

    String nonceValue = request.getAuthorizationReqDTO().getNonce();

    // Get access token issued time
    long accessTokenIssuedTime = getAccessTokenIssuedTime(tokenRespDTO.getAccessToken(), request) / 1000;

    String atHash = null;
    String responseType = request.getAuthorizationReqDTO().getResponseType();
    //at_hash is generated on access token. Hence the check on response type to be id_token token or code
    if (!JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName()) &&
            !OAuthConstants.ID_TOKEN.equalsIgnoreCase(responseType) &&
            !OAuthConstants.NONE.equalsIgnoreCase(responseType)) {
        String digAlg = mapDigestAlgorithm(signatureAlgorithm);
        MessageDigest md;
        try {
            md = MessageDigest.getInstance(digAlg);
        } catch (NoSuchAlgorithmException e) {
            throw new IdentityOAuth2Exception("Invalid Algorithm : " + digAlg);
        }
        md.update(tokenRespDTO.getAccessToken().getBytes(Charsets.UTF_8));
        byte[] digest = md.digest();
        int leftHalfBytes = 16;
        if (SHA384.equals(digAlg)) {
            leftHalfBytes = 24;
        } else if (SHA512.equals(digAlg)) {
            leftHalfBytes = 32;
        }
        byte[] leftmost = new byte[leftHalfBytes];
        for (int i = 0; i < leftHalfBytes; i++) {
            leftmost[i] = digest[i];
        }
        atHash = new String(Base64.encodeBase64URLSafe(leftmost), Charsets.UTF_8);
    }


    if (log.isDebugEnabled()) {
        StringBuilder stringBuilder = (new StringBuilder())
                .append("Using issuer ").append(issuer).append("\n")
                .append("Subject ").append(subject).append("\n")
                .append("ID Token life time ").append(lifetimeInMillis / 1000).append("\n")
                .append("Current time ").append(curTimeInMillis / 1000).append("\n")
                .append("Nonce Value ").append(nonceValue).append("\n")
                .append("Signature Algorithm ").append(signatureAlgorithm).append("\n");
        if (log.isDebugEnabled()) {
            log.debug(stringBuilder.toString());
        }
    }

    JWTClaimsSet jwtClaimsSet = new JWTClaimsSet();
    jwtClaimsSet.setIssuer(issuer);
    jwtClaimsSet.setSubject(subject);
    jwtClaimsSet.setAudience(Arrays.asList(request.getAuthorizationReqDTO().getConsumerKey()));
    jwtClaimsSet.setClaim("azp", request.getAuthorizationReqDTO().getConsumerKey());
    jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis));
    jwtClaimsSet.setIssueTime(new Date(curTimeInMillis));
    jwtClaimsSet.setClaim("auth_time", accessTokenIssuedTime);
    if(atHash != null){
        jwtClaimsSet.setClaim("at_hash", atHash);
    }
    if (nonceValue != null) {
        jwtClaimsSet.setClaim("nonce", nonceValue);
    }

    request.addProperty(OAuthConstants.ACCESS_TOKEN, tokenRespDTO.getAccessToken());
    CustomClaimsCallbackHandler claimsCallBackHandler =
            OAuthServerConfiguration.getInstance().getOpenIDConnectCustomClaimsCallbackHandler();
    claimsCallBackHandler.handleCustomClaims(jwtClaimsSet, request);
    if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) {
        return new PlainJWT(jwtClaimsSet).serialize();
    }
    return signJWT(jwtClaimsSet, request);
}