com.nimbusds.jose.JWSSigner Java Examples

The following examples show how to use com.nimbusds.jose.JWSSigner. 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: ScooldUtils.java    From scoold with Apache License 2.0 7 votes vote down vote up
public SignedJWT generateJWToken(Map<String, Object> claims, long validitySeconds) {
	String secret = Config.getConfigParam("app_secret_key", "");
	if (!StringUtils.isBlank(secret)) {
		try {
			Date now = new Date();
			JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
			claimsSet.issueTime(now);
			if (validitySeconds > 0) {
				claimsSet.expirationTime(new Date(now.getTime() + (validitySeconds * 1000)));
			}
			claimsSet.notBeforeTime(now);
			claimsSet.claim(Config._APPID, Config.getConfigParam("access_key", "x"));
			claims.entrySet().forEach((claim) -> claimsSet.claim(claim.getKey(), claim.getValue()));
			JWSSigner signer = new MACSigner(secret);
			SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build());
			signedJWT.sign(signer);
			return signedJWT;
		} catch (JOSEException e) {
			logger.warn("Unable to sign JWT: {}.", e.getMessage());
		}
	}
	logger.error("Failed to generate JWT token - app_secret_key is blank.");
	return null;
}
 
Example #2
Source File: AbstractJWTFilterTest.java    From knox with Apache License 2.0 6 votes vote down vote up
protected SignedJWT getJWT(String issuer, String sub, String aud, Date expires, Date nbf, RSAPrivateKey privateKey,
                           String signatureAlgorithm)
    throws Exception {
  List<String> audiences = new ArrayList<>();
  if (aud != null) {
    audiences.add(aud);
  }

  JWTClaimsSet claims = new JWTClaimsSet.Builder()
  .issuer(issuer)
  .subject(sub)
  .audience(aud)
  .expirationTime(expires)
  .notBeforeTime(nbf)
  .claim("scope", "openid")
  .build();

  JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.parse(signatureAlgorithm)).build();

  SignedJWT signedJWT = new SignedJWT(header, claims);
  JWSSigner signer = new RSASSASigner(privateKey);

  signedJWT.sign(signer);

  return signedJWT;
}
 
Example #3
Source File: JwtAuthorizerTest.java    From outbackcdx with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    RSAKey rsaJWK = new RSAKeyGenerator(2048).generate();
    RSAKey rsaPublicJWK = rsaJWK.toPublicJWK();
    JWSSigner signer = new RSASSASigner(rsaJWK);
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
            .claim("permissions", Arrays.asList(RULES_EDIT.toString(), INDEX_EDIT.toString()))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(rsaJWK.getKeyID()).build(),
            claimsSet);
    signedJWT.sign(signer);
    String token = signedJWT.serialize();

    JwtAuthorizer authorizer = new JwtAuthorizer(new ImmutableJWKSet<>(new JWKSet(rsaPublicJWK)), "permissions");
    Set<Permission> permissions = authorizer.verify("beARer " + token).permissions;
    assertEquals(EnumSet.of(RULES_EDIT, INDEX_EDIT), permissions);
}
 
Example #4
Source File: UserRepository.java    From shiro-jwt with MIT License 6 votes vote down vote up
default String createToken(Object userId) {
    try {
        JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();

        builder.issuer(getIssuer());
        builder.subject(userId.toString());
        builder.issueTime(new Date());
        builder.notBeforeTime(new Date());
        builder.expirationTime(new Date(new Date().getTime() + getExpirationDate()));
        builder.jwtID(UUID.randomUUID().toString());

        JWTClaimsSet claimsSet = builder.build();
        JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

        Payload payload = new Payload(claimsSet.toJSONObject());

        JWSObject jwsObject = new JWSObject(header, payload);

        JWSSigner signer = new MACSigner(getSharedKey());
        jwsObject.sign(signer);
        return jwsObject.serialize();
    } catch (JOSEException ex) {
        return null;
    }
}
 
Example #5
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void validToken() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date(new Date().getTime() + 100000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertTrue("Must be valid", signed.verify(verifier));
}
 
Example #6
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void invalidTokenNotBeforeTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(new Date().getTime() + 100000), new Date(new Date().getTime() + 200000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example #7
Source File: DefaultJwtSigningAndValidationService.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public void signJwt(SignedJWT jwt, JWSAlgorithm alg) {

	JWSSigner signer = null;

	for (JWSSigner s : signers.values()) {
		if (s.supportedJWSAlgorithms().contains(alg)) {
			signer = s;
			break;
		}
	}

	if (signer == null) {
		//If we can't find an algorithm that matches, we can't sign
		logger.error("No matching algirthm found for alg=" + alg);

	}

	try {
		jwt.sign(signer);
	} catch (JOSEException e) {

		logger.error("Failed to sign JWT, error was: ", e);
	}

}
 
Example #8
Source File: DefaultJwtSigningAndValidationService.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
/**
 * Sign a jwt in place using the configured default signer.
 */
@Override
public void signJwt(SignedJWT jwt) {
	if (getDefaultSignerKeyId() == null) {
		throw new IllegalStateException("Tried to call default signing with no default signer ID set");
	}

	JWSSigner signer = signers.get(getDefaultSignerKeyId());

	try {
		jwt.sign(signer);
	} catch (JOSEException e) {

		logger.error("Failed to sign JWT, error was: ", e);
	}

}
 
Example #9
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void invalidTokenExpirationTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date());

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example #10
Source File: WebSSOResourceTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public JWT issueToken(Principal p, List<String> audiences, String algorithm, long expires,
                      String signingKeystoreName, String signingKeystoreAlias, char[] signingKeystorePassphrase)
    throws TokenServiceException {
  String[] claimArray = new String[4];
  claimArray[0] = "KNOXSSO";
  claimArray[1] = p.getName();
  claimArray[2] = null;
  if (expires == -1) {
    claimArray[3] = null;
  } else {
    claimArray[3] = String.valueOf(expires);
  }

  JWT token = new JWTToken(algorithm, claimArray, audiences);
  RSAPrivateKey privateKey = getPrivateKey(signingKeystoreName, signingKeystoreAlias, signingKeystorePassphrase);
  JWSSigner signer = new RSASSASigner(privateKey);
  token.sign(signer);

  return token;
}
 
Example #11
Source File: TokenServiceResourceTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public JWT issueToken(Principal p, List<String> audiences, String algorithm, long expires) {
  String[] claimArray = new String[4];
  claimArray[0] = "KNOXSSO";
  claimArray[1] = p.getName();
  claimArray[2] = null;
  if (expires == -1) {
    claimArray[3] = null;
  } else {
    claimArray[3] = String.valueOf(expires);
  }

  JWT token = new JWTToken(algorithm, claimArray, audiences);
  JWSSigner signer = new RSASSASigner(privateKey);
  token.sign(signer);

  return token;
}
 
Example #12
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static String createTokenRSA( PrivateKey privateKey, String claimJson )
{
    try
    {
        JWSSigner signer = new RSASSASigner( ( RSAPrivateKey ) privateKey );

        Payload pl = new Payload( claimJson );
        JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl );

        jwsObject.sign( signer );

        return jwsObject.serialize();
    }
    catch ( Exception e )
    {
        LOG.error( "Error creating RSA token", e.getMessage() );

        return "";
    }
}
 
Example #13
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static String createToken( String headerJson, String claimJson, String sharedKey )
{
    try
    {
        JWSHeader header = JWSHeader.parse( headerJson );
        JWSSigner signer = new MACSigner( sharedKey.getBytes() );
        JWTClaimsSet claimsSet = JWTClaimsSet.parse( claimJson );

        SignedJWT signedJWT = new SignedJWT( header, claimsSet );
        signedJWT.sign( signer );

        return signedJWT.serialize();
    }
    catch ( Exception e )
    {
        LOG.error( "Error creating token", e.getMessage() );

        return "";
    }
}
 
Example #14
Source File: EncryptionUtility.java    From amex-api-java-client-core with Apache License 2.0 6 votes vote down vote up
public String sign(String algorithm, String kid, String keyStr, String dataToSign) {
    try {

        Key key = getKey(algorithm, keyStr);

        JWSHeader.Builder jwsBuilder = new JWSHeader.Builder("HS256".equals(algorithm) ? JWSAlgorithm.HS256 : JWSAlgorithm.RS256);
        jwsBuilder.keyID(kid);

        JWSHeader signingHeader = jwsBuilder.build();
        JWSSigner signer = "HS256".equals(algorithm) ? new MACSigner(key.getEncoded()) : new RSASSASigner((RSAPrivateKey) key);
        JWSObject jwsObject = new JWSObject(signingHeader, new Payload(dataToSign));
        jwsObject.sign(signer);
        checkObject(jwsObject);

        String parts[] = jwsObject.serialize().split("\\.");

        return "{\"protected\":\"" + parts[0] + "\", \"payload\":\"" + parts[1] + "\", \"signature\":\"" + parts[2] + "\"}";

    } catch (Exception e) {
        throw new CryptoException("Exception signing data: " + e.getMessage(), e);
    }
}
 
Example #15
Source File: JWTTokenTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenSignature() throws Exception {
  String[] claims = new String[4];
  claims[0] = "KNOXSSO";
  claims[1] = "[email protected]";
  claims[2] = "https://login.example.com";
  claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
  JWT token = new JWTToken("RS256", claims);

  assertEquals("KNOXSSO", token.getIssuer());
  assertEquals("[email protected]", token.getSubject());
  assertEquals("https://login.example.com", token.getAudience());

  // Sign the token
  JWSSigner signer = new RSASSASigner(privateKey);
  token.sign(signer);
  assertTrue(token.getSignaturePayload().length > 0);

  // Verify the signature
  JWSVerifier verifier = new RSASSAVerifier(publicKey);
  assertTrue(token.verify(verifier));
}
 
Example #16
Source File: JWTTokenTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenSignatureRS512() throws Exception {
  String[] claims = new String[4];
  claims[0] = "KNOXSSO";
  claims[1] = "[email protected]";
  claims[2] = "https://login.example.com";
  claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
  JWT token = new JWTToken(JWSAlgorithm.RS512.getName(), claims);

  assertEquals("KNOXSSO", token.getIssuer());
  assertEquals("[email protected]", token.getSubject());
  assertEquals("https://login.example.com", token.getAudience());
  assertTrue(token.getHeader().contains(JWSAlgorithm.RS512.getName()));

  // Sign the token
  JWSSigner signer = new RSASSASigner(privateKey);
  token.sign(signer);
  assertTrue(token.getSignaturePayload().length > 0);

  // Verify the signature
  JWSVerifier verifier = new RSASSAVerifier(publicKey);
  assertTrue(token.verify(verifier));
}
 
Example #17
Source File: CellerySignedJWTBuilder.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
public String build() throws CelleryAuthException {

        // Build the JWT Header
        try {
            JWSHeader jwsHeader = buildJWSHeader();
            // Add mandatory claims
            addMandatoryClaims(claimSetBuilder);
            JWTClaimsSet claimsSet = this.claimSetBuilder.build();

            SignedJWT signedJWT = new SignedJWT(jwsHeader, claimsSet);
            JWSSigner signer = new RSASSASigner(getRSASigningKey());

            signedJWT.sign(signer);
            return signedJWT.serialize();
        } catch (IdentityOAuth2Exception | JOSEException e) {
            throw new CelleryAuthException("Error while generating the signed JWT.", e);
        }
    }
 
Example #18
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 #19
Source File: DefaultTokenAuthorityService.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public JWT issueToken(Principal p, List<String> audiences, String algorithm, long expires,
                      String signingKeystoreName, String signingKeystoreAlias, char[] signingKeystorePassphrase)
    throws TokenServiceException {
  String[] claimArray = new String[4];
  claimArray[0] = "KNOXSSO";
  claimArray[1] = p.getName();
  claimArray[2] = null;
  if (expires == -1) {
    claimArray[3] = null;
  }
  else {
    claimArray[3] = String.valueOf(expires);
  }

  JWT token;
  if (SUPPORTED_SIG_ALGS.contains(algorithm)) {
    token = new JWTToken(algorithm, claimArray, audiences);
    try {
      RSAPrivateKey key = getSigningKey(signingKeystoreName, signingKeystoreAlias, signingKeystorePassphrase);
      // allowWeakKey to not break existing 1024 bit certificates
      JWSSigner signer = new RSASSASigner(key, true);
      token.sign(signer);
    } catch (KeystoreServiceException e) {
      throw new TokenServiceException(e);
    }
  }
  else {
    throw new TokenServiceException("Cannot issue token - Unsupported algorithm");
  }

  return token;
}
 
Example #20
Source File: DefaultTokenStateServiceTest.java    From knox with Apache License 2.0 5 votes vote down vote up
protected JWT getJWTToken(final long expiry) {
  String[] claims = new String[4];
  claims[0] = "KNOXSSO";
  claims[1] = "[email protected]";
  claims[2] = "https://login.example.com";
  if(expiry > 0) {
    claims[3] = Long.toString(expiry);
  }

  JWT token = new JWTToken("RS256", claims);
  // Sign the token
  JWSSigner signer = new RSASSASigner(privateKey);
  token.sign(signer);
  return token;
}
 
Example #21
Source File: JWTToken.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void sign(JWSSigner signer) {
  try {
    jwt.sign(signer);
  } catch (JOSEException e) {
    log.unableToSignToken(e);
  }
}
 
Example #22
Source File: SecurityUtils.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a new JWT token.
 * @param user a User object belonging to the app
 * @param app the app object
 * @return a new JWT or null
 */
public static SignedJWT generateJWToken(User user, App app) {
	if (app != null) {
		try {
			Date now = new Date();
			JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
			String userSecret = "";
			claimsSet.issueTime(now);
			claimsSet.expirationTime(new Date(now.getTime() + (app.getTokenValiditySec() * 1000)));
			claimsSet.notBeforeTime(now);
			claimsSet.claim("refresh", getNextRefresh(app.getTokenValiditySec()));
			claimsSet.claim(Config._APPID, app.getId());
			if (user != null) {
				claimsSet.subject(user.getId());
				claimsSet.claim("idp", user.getIdentityProvider());
				userSecret = user.getTokenSecret();
			}
			JWSSigner signer = new MACSigner(app.getSecret() + userSecret);
			SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build());
			signedJWT.sign(signer);
			return signedJWT;
		} catch (JOSEException e) {
			logger.warn("Unable to sign JWT: {}.", e.getMessage());
		}
	}
	return null;
}
 
Example #23
Source File: JWTTokenGenerator.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Generate JWT Token with JWTTokenInfo object
 *
 * @param jwtToken JWT Token info object
 * @return Serialized JWT token
 * @throws JOSEException
 * @throws NoSuchAlgorithmException
 */
public String generateJWTToken(JWTTokenInfoDTO jwtToken) throws JOSEException, NoSuchAlgorithmException {

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(AuthConstants.TOKEN_STORE_KEY_ALGORITHM);
    keyPairGenerator.initialize(Integer.parseInt(JWTConfig.getInstance().getJwtConfigDto().getTokenSize()));
    RSAKey rsaJWK = generateRSAKey(jwtToken, keyPairGenerator); //Currently uses generated key pair

    SignedJWT signedJWT = populateSignedJWTToken(jwtToken, rsaJWK);

    JWSSigner signer = new RSASSASigner(rsaJWK);
    signedJWT.sign(signer);

    return signedJWT.serialize();
}
 
Example #24
Source File: JWTGenerator.java    From msf4j with Apache License 2.0 5 votes vote down vote up
protected String generateJWT(User user) throws Exception {

        RSAPrivateKey privateKey = getPrivateKey(keyStore, keyStorePassword, alias);
        // Create RSA-signer with the private key
        JWSSigner signer = new RSASSASigner(privateKey);

        // Prepare JWT with claims set
        JWTClaimsSet claimsSet = new JWTClaimsSet();
        claimsSet.setSubject(user.getName());
        claimsSet.setClaim("email", user.getEmail());
        claimsSet.setClaim("roles", user.getRoles());
        claimsSet.setIssuer("wso2.org/products/msf4j");
        claimsSet.setExpirationTime(new Date(new Date().getTime() + 60 * 60 * 1000)); //60 min

        SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);

        // Compute the RSA signature
        signedJWT.sign(signer);

        // To serialize to compact form, produces something like
        // eyJhbGciOiJSUzI1NiJ9.SW4gUlNBIHdlIHRydXN0IQ.IRMQENi4nJyp4er2L
        // mZq3ivwoAjqa1uUkSBKFIX7ATndFF5ivnt-m8uApHO4kfIFOrW7w2Ezmlg3Qd
        // maXlS9DhN0nUk_hGI3amEjkKd0BWYCB8vfUbUv0XGjQip78AI4z1PrFRNidm7
        // -jPDm5Iq0SZnjKjCNS5Q15fokXZc8u0A

        return signedJWT.serialize();
    }
 
Example #25
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 #26
Source File: MobiTokenVerifier.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a JWT Token String for the user with the provided username using the Mobi token key and the provided
 * issuer, scope, tokenDuration, and additional claims.
 *
 * @param username The sub of the token
 * @param issuer The issuer of the token
 * @param scope The scope of the token
 * @param tokenDuration The duration for the new token
 * @param claims An optional map of custom claims to add to the token
 * @return The String representing the encoded and compact JWT Token
 * @throws JOSEException if there is a problem creating the token
 */
SignedJWT generateToken(String username, String issuer, String scope, long tokenDuration,
                        @Nullable Map<String, Object> claims) throws JOSEException {
    // Create HMAC signer
    JWSSigner signer = new MACSigner(padKey(KEY));

    Date now = new Date();
    Date expirationDate = new Date(now.getTime() + tokenDuration);

    // Prepare JWT Builder with claims set
    JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder()
            .subject(username)
            .issuer(issuer)
            .expirationTime(expirationDate)
            .claim("scope", scope);

    if (claims != null) {
        claims.forEach(builder::claim);
    }

    SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), builder.build());

    // Apply the HMAC protection
    signedJWT.sign(signer);

    return signedJWT;
}
 
Example #27
Source File: SessionUtilKeyPair.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
public String issueJwtToken() throws SFException
{
  JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
  String sub = String.format(SUBJECT_FMT, this.accountName, this.userName);
  String iss = String.format(ISSUER_FMT, this.accountName, this.userName,
                             this.calculatePublicKeyFingerprint(this.publicKey));

  // iat is now
  Date iat = new Date(System.currentTimeMillis());

  // expiration is 60 seconds later
  Date exp = new Date(iat.getTime() + 60L * 1000);

  JWTClaimsSet claimsSet = builder.issuer(iss)
      .subject(sub)
      .issueTime(iat)
      .expirationTime(exp)
      .build();

  SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256),
                                      claimsSet);
  JWSSigner signer = new RSASSASigner(this.privateKey);

  try
  {
    signedJWT.sign(signer);
  }
  catch (JOSEException e)
  {
    throw new SFException(e, ErrorCode.FAILED_TO_GENERATE_JWT);
  }

  return signedJWT.serialize();
}
 
Example #28
Source File: TokenHelperImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
protected String generate( final String issuer, final String subject, final Date issueTime, final Date expireTime,
                           final String secret ) throws JOSEException
{
    JWSHeader jwtHeader = new JWSHeader( JWSAlgorithm.HS256 );
    JWTClaimsSet claimset =
            new JWTClaimsSet.Builder().expirationTime( expireTime ).issuer( issuer ).issueTime( issueTime )
                                      .subject( subject ).build();
    SignedJWT jwt = new SignedJWT( jwtHeader, claimset );

    JWSSigner signer = new MACSigner( secret );
    jwt.sign( signer );
    return jwt.serialize();
}
 
Example #29
Source File: ClientAssertionServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private String generateJWT(JWSSigner jwsSigner) throws JOSEException {
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.HS256).keyID(KID).build(),
            new JWTClaimsSet.Builder()
                    .issuer(ISSUER)
                    .subject(CLIENT_ID)
                    .audience(AUDIENCE)
                    .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
                    .build()
    );

    signedJWT.sign(jwsSigner);

    return signedJWT.serialize();
}
 
Example #30
Source File: ClientAssertionServiceTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void testHmacJwt_invalidClientAuthMethod() throws NoSuchAlgorithmException, JOSEException {
    // Generate random 256-bit (32-byte) shared secret
    SecureRandom random = new SecureRandom();
    byte[] sharedSecret = new byte[32];
    random.nextBytes(sharedSecret);

    String clientSecret = new String(sharedSecret, StandardCharsets.UTF_8);

    JWSSigner signer = new MACSigner(clientSecret);

    Client client = new Client();
    client.setClientId(CLIENT_ID);
    client.setClientSecret(new String(sharedSecret));
    client.setTokenEndpointAuthMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT);
    String assertion = generateJWT(signer);
    OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class);
    String basePath="/";

    when(clientSyncService.findByClientId(any())).thenReturn(Maybe.just(client));
    when(openIDProviderMetadata.getTokenEndpoint()).thenReturn(AUDIENCE);
    when(openIDDiscoveryService.getConfiguration(basePath)).thenReturn(openIDProviderMetadata);

    TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,basePath).test();

    testObserver.assertError(InvalidClientException.class);
    testObserver.assertNotComplete();
}