Java Code Examples for org.jose4j.jws.JsonWebSignature#setPayload()

The following examples show how to use org.jose4j.jws.JsonWebSignature#setPayload() . 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: JWTAuthPluginTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeAll() throws Exception {
  JwtClaims claims = generateClaims();
  JsonWebSignature jws = new JsonWebSignature();
  jws.setPayload(claims.toJson());
  jws.setKey(rsaJsonWebKey.getPrivateKey());
  jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
  jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

  String testJwt = jws.getCompactSerialization();
  testHeader = "Bearer" + " " + testJwt;

  claims.unsetClaim("iss");
  claims.unsetClaim("aud");
  claims.unsetClaim("exp");
  jws.setPayload(claims.toJson());
  String slimJwt = jws.getCompactSerialization();
  slimHeader = "Bearer" + " " + slimJwt;
}
 
Example 2
Source File: SecuredResource.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/generate-valid-token")
public Map<String, String> generateValidToken() {
    final JwtClaims claims = new JwtClaims();
    claims.setSubject("good-guy");
    claims.setExpirationTimeMinutesInTheFuture(30);

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(HMAC_SHA256);
    jws.setKey(new HmacKey(tokenSecret));

    try {
        return singletonMap("token", jws.getCompactSerialization());
    }
    catch (JoseException e) { throw Throwables.propagate(e); }
}
 
Example 3
Source File: JwtCachingAuthenticatorTest.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
private JwtContext tokenTwo() {
    final JwtClaims claims = new JwtClaims();
    claims.setSubject("good-guy-two");
    claims.setIssuer("Issuer");
    claims.setAudience("Audience");

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA512);
    jws.setKey(new HmacKey(SECRET.getBytes(UTF_8)));
    jws.setDoKeyValidation(false);

    try {
        return consumer.process(jws.getCompactSerialization());
    }
    catch (Exception e) { throw Throwables.propagate(e); }
}
 
Example 4
Source File: TokenGenerator.java    From rufus with MIT License 6 votes vote down vote up
public String generateToken(String subject) {
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(subject);
    claims.setExpirationTimeMinutesInTheFuture(TOKEN_EXPIRATION_IN_MINUTES);

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(HMAC_SHA256);
    jws.setKey(new HmacKey(tokenSecret));
    jws.setDoKeyValidation(false); //relaxes hmac key length restrictions

    try {
        return jws.getCompactSerialization();
    } catch (JoseException e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: SecuredResource.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/generate-expired-token")
public Map<String, String> generateExpiredToken() {
    final JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(-20);
    claims.setSubject("good-guy");

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(HMAC_SHA256);
    jws.setKey(new HmacKey(tokenSecret));

    try {
        return singletonMap("token", jws.getCompactSerialization());
    }
    catch (JoseException e) { throw Throwables.propagate(e); }
}
 
Example 6
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testNpeWithNonExtractableKeyDataHS256() throws Exception
{
    byte[] raw = Base64Url.decode("hup76LcA9B7pqrEtqyb4EBg6XCcr9r0iOCFF1FeZiJM");
    FakeHsmNonExtractableSecretKeySpec key = new FakeHsmNonExtractableSecretKeySpec(raw, "HmacSHA256");
    JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(5);
    claims.setSubject("subject");
    claims.setIssuer("issuer");
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setKey(key);
    String jwt = jws.getCompactSerialization();
    JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder();
    jwtConsumerBuilder.setAllowedClockSkewInSeconds(60);
    jwtConsumerBuilder.setRequireSubject();
    jwtConsumerBuilder.setExpectedIssuer("issuer");
    jwtConsumerBuilder.setVerificationKey(key);
    JwtConsumer jwtConsumer = jwtConsumerBuilder.build();
    JwtClaims processedClaims = jwtConsumer.processToClaims(jwt);
    System.out.println(processedClaims);
}
 
Example 7
Source File: JwtCachingAuthenticatorTest.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
private JwtContext tokenOne() {
    final JwtClaims claims = new JwtClaims();
    claims.setSubject("good-guy");
    claims.setIssuer("Issuer");
    claims.setAudience("Audience");

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA512);
    jws.setKey(new HmacKey(SECRET.getBytes(UTF_8)));
    jws.setDoKeyValidation(false);

    try {
        return consumer.process(jws.getCompactSerialization());
    }
    catch (Exception e) { throw Throwables.propagate(e); }
}
 
Example 8
Source File: JwtAuthProviderTest.java    From dropwizard-auth-jwt with Apache License 2.0 5 votes vote down vote up
private String toToken(byte[] key, JwtClaims claims) {
    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(HMAC_SHA512);
    jws.setKey(new HmacKey(key));
    jws.setDoKeyValidation(false);

    try {
        return jws.getCompactSerialization();
    }
    catch (JoseException e) { throw Throwables.propagate(e); }
}
 
Example 9
Source File: ExamplesTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void jwsSigningExample() throws JoseException
{
    //
    // An example of signing using JSON Web Signature (JWS)
    //

    // The content that will be signed
    String examplePayload = "This is some text that is to be signed.";

    // Create a new JsonWebSignature
    JsonWebSignature jws = new JsonWebSignature();

    // Set the payload, or signed content, on the JWS object
    jws.setPayload(examplePayload);

    // Set the signature algorithm on the JWS that will integrity protect the payload
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);

    // Set the signing key on the JWS
    // Note that your application will need to determine where/how to get the key
    // and here we just use an example from the JWS spec
    PrivateKey privateKey = ExampleEcKeysFromJws.PRIVATE_256;
    jws.setKey(privateKey);

    // Sign the JWS and produce the compact serialization or complete JWS representation, which
    // is a string consisting of three dot ('.') separated base64url-encoded
    // parts in the form Header.Payload.Signature
    String jwsCompactSerialization = jws.getCompactSerialization();

    // Do something useful with your JWS
    System.out.println(jwsCompactSerialization);
}
 
Example 10
Source File: JWTVerificationkeyResolverTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public JsonWebSignature getJws() {
  JsonWebSignature jws = new JsonWebSignature();
  jws.setPayload(JWTAuthPluginTest.generateClaims().toJson());
  jws.setKey(getRsaKey().getPrivateKey());
  jws.setKeyIdHeaderValue(getRsaKey().getKeyId());
  jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
  return jws;
}
 
Example 11
Source File: TokenUtils.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public static String createToken(String groupName) throws Exception {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer("http://testsuite-jwt-issuer.io");
    claims.setSubject(SUBJECT);
    claims.setStringListClaim("groups", groupName);
    claims.setClaim("upn", "[email protected]");
    claims.setExpirationTimeMinutesInTheFuture(1);

    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    jws.setKey(getPrivateKey());
    return jws.getCompactSerialization();
}
 
Example 12
Source File: OauthHelperTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public static String getJwt(JwtClaims claims) throws JoseException {
    String jwt;

    RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
            "/config/primary.jks", "password", "selfsigned");

    // A JWT is a JWS and/or a JWE with JSON claims as the payload.
    // In this example it is a JWS nested inside a JWE
    // So we first create a JsonWebSignature object.
    JsonWebSignature jws = new JsonWebSignature();

    // The payload of the JWS is JSON content of the JWT Claims
    jws.setPayload(claims.toJson());

    // The JWT is signed using the sender's private key
    jws.setKey(privateKey);
    jws.setKeyIdHeaderValue("100");

    // Set the signature algorithm on the JWT/JWS that will integrity protect the claims
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    // Sign the JWS and produce the compact serialization, which will be the inner JWT/JWS
    // representation, which is a string consisting of three dot ('.') separated
    // base64url-encoded parts in the form Header.Payload.Signature
    jwt = jws.getCompactSerialization();
    return jwt;
}
 
Example 13
Source File: JwtSignatureImpl.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private String signInternal(Key signingKey) {
    JwtBuildUtils.setDefaultJwtClaims(claims);
    JsonWebSignature jws = new JsonWebSignature();
    for (Map.Entry<String, Object> entry : headers.entrySet()) {
        jws.setHeader(entry.getKey(), entry.getValue());
    }
    if (!headers.containsKey("typ")) {
        jws.setHeader("typ", "JWT");
    }
    String algorithm = (String) headers.get("alg");
    if (algorithm == null) {
        algorithm = keyAlgorithm(headers, signingKey);
        jws.setAlgorithmHeaderValue(algorithm);
    }
    if ("none".equals(algorithm)) {
        jws.setAlgorithmConstraints(AlgorithmConstraints.ALLOW_ONLY_NONE);
    }
    jws.setPayload(claims.toJson());
    if (signingKey instanceof RSAPrivateKey && algorithm.startsWith("RS")
            && ((RSAPrivateKey) signingKey).getModulus().bitLength() < 2048) {
        throw ImplMessages.msg.signKeySizeMustBeHigher(algorithm);
    }
    jws.setKey(signingKey);
    try {
        return jws.getCompactSerialization();
    } catch (Exception ex) {
        throw ImplMessages.msg.signJwtTokenFailed(ex.getMessage(), ex);
    }
}
 
Example 14
Source File: TokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to generate a JWT string from a JSON resource file that is signed by the private key
 * using either RS256 or ES256 algorithm, possibly with invalid fields.
 *
 * @param pk - the private key to sign the token with
 * @param kid - the kid claim to assign to the token
 * @param jsonResName   - name of test resources file
 * @param invalidClaims - the set of claims that should be added with invalid values to test failure modes
 * @param timeClaims - used to return the exp, iat, auth_time claims
 * @return the JWT string
 * @throws Exception on parse failure
 */
public static String signClaims(PrivateKey pk, String kid, String jsonResName,
    Set<InvalidClaims> invalidClaims, Map<String, Long> timeClaims) throws Exception {

    if (invalidClaims == null) {
        invalidClaims = Collections.emptySet();
    }
    JwtClaims claims = createJwtClaims(jsonResName, invalidClaims, timeClaims);
    
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    if (kid != null) {
        jws.setKeyIdHeaderValue(kid);
    }
    jws.setHeader("typ", "JWT");
    
    if (invalidClaims.contains(InvalidClaims.ALG)) {
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
        jws.setKey(KeyGenerator.getInstance("HMACSHA256").generateKey());
    }
    else {
        jws.setAlgorithmHeaderValue(pk instanceof RSAPrivateKey ? AlgorithmIdentifiers.RSA_USING_SHA256
            : AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);
        if (invalidClaims.contains(InvalidClaims.SIGNER)) {
            // Generate a new random private key to sign with to test invalid signatures
            pk = generateKeyPair(2048).getPrivate();
        }
        jws.setKey(pk);   
    }
    return jws.getCompactSerialization();
}
 
Example 15
Source File: KeyPairUtilTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void rsaPublicKeyEncodingDecodingAndSign() throws Exception
{
    PublicJsonWebKey publicJsonWebKey = ExampleRsaJwksFromJwe.APPENDIX_A_1;
    String pem = KeyPairUtil.pemEncode(publicJsonWebKey.getPublicKey());
    String expectedPem = "-----BEGIN PUBLIC KEY-----\r\n" +
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoahUIoWw0K0usKNuOR6H\r\n" +
            "4wkf4oBUXHTxRvgb48E+BVvxkeDNjbC4he8rUWcJoZmds2h7M70imEVhRU5djINX\r\n" +
            "tqllXI4DFqcI1DgjT9LewND8MW2Krf3Spsk/ZkoFnilakGygTwpZ3uesH+PFABNI\r\n" +
            "UYpOiN15dsQRkgr0vEhxN92i2asbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h+\r\n" +
            "QChLOln0/mtUZwfsRaMStPs6mS6XrgxnxbWhojf663tuEQueGC+FCMfra36C9knD\r\n" +
            "FGzKsNa7LZK2djYgyD3JR/MB/4NUJW/TqOQtwHYbxevoJArm+L5StowjzGy+/bq6\r\n" +
            "GwIDAQAB\r\n" +
            "-----END PUBLIC KEY-----";
    Assert.assertThat(pem, equalTo(expectedPem));


    RsaKeyUtil rsaKeyUtil = new RsaKeyUtil();
    PublicKey publicKey = rsaKeyUtil.fromPemEncoded(pem);
    Assert.assertThat(publicKey, equalTo(publicJsonWebKey.getPublicKey()));

    JwtClaims claims = new JwtClaims();
    claims.setSubject("meh");
    claims.setExpirationTimeMinutesInTheFuture(20);
    claims.setGeneratedJwtId();
    claims.setAudience("you");
    claims.setIssuer("me");
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(publicJsonWebKey.getPrivateKey());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    String jwt = jws.getCompactSerialization();

    Logger log = LoggerFactory.getLogger(this.getClass());
    log.debug("The following JWT and public key should be (and were on 11/11/15) usable and produce a valid " +
            "result at jwt.io (related to http://stackoverflow.com/questions/32744172):\n" + jwt + "\n" + pem);
}
 
Example 16
Source File: Token.java    From server_face_recognition with GNU General Public License v3.0 5 votes vote down vote up
public static Token cypherToken(String username, String password, int userId) {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer("Sanstorik");
    claims.setAudience("User");
    claims.setExpirationTimeMinutesInTheFuture(60);
    claims.setGeneratedJwtId();
    claims.setIssuedAtToNow();
    claims.setNotBeforeMinutesInThePast(0.05f);
    claims.setSubject("neuralnetwork");

    claims.setClaim(USERNAME_KEY, username);
    claims.setClaim(PASSWORD_KEY, password);
    claims.setClaim(USERID_KEY, userId);


    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(key.getPrivateKey());


    jws.setKeyIdHeaderValue(key.getKeyId());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    Token token = null;
    try {
        token = new Token(jws.getCompactSerialization(),
                username, password, userId);
    } catch (JoseException e) {
        e.printStackTrace();
    }

    return token;
}
 
Example 17
Source File: JwtHelper.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Builds a new access token.
 *
 * @param user the user (subject) to build the token, it will also add the roles as claims
 * @param clientId the client ID the token is for
 * @param scope the scope the token is valid for
 * @param tokenLifetime the lifetime of the token in minutes before it expires
 *
 * @return a base64-encoded signed JWT token to be passed as a bearer token in API requests
 */
public String getJwtAccessToken(User user, String clientId, String scope, int tokenLifetime) {
    try {
        JwtClaims jwtClaims = new JwtClaims();
        jwtClaims.setIssuer(ISSUER_NAME);
        jwtClaims.setAudience(AUDIENCE);
        jwtClaims.setExpirationTimeMinutesInTheFuture(tokenLifetime);
        jwtClaims.setGeneratedJwtId();
        jwtClaims.setIssuedAtToNow();
        jwtClaims.setNotBeforeMinutesInThePast(2);
        jwtClaims.setSubject(user.getName());
        jwtClaims.setClaim("client_id", clientId);
        jwtClaims.setClaim("scope", scope);
        jwtClaims.setStringListClaim("role",
                new ArrayList<>(user.getRoles() != null ? user.getRoles() : Collections.emptySet()));

        JsonWebSignature jws = new JsonWebSignature();
        jws.setPayload(jwtClaims.toJson());
        jws.setKey(jwtWebKey.getPrivateKey());
        jws.setKeyIdHeaderValue(jwtWebKey.getKeyId());
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
        String jwt = jws.getCompactSerialization();

        return jwt;
    } catch (Exception e) {
        logger.error("Error while writing JWT token", e);
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 18
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void ctyRoundTrip() throws JoseException, InvalidJwtException, MalformedClaimException
{
    JsonWebKeySet jwks = new JsonWebKeySet("{\"keys\":[" +
            "{\"kty\":\"oct\",\"kid\":\"hk1\",\"alg\":\"HS256\",\"k\":\"RYCCH0Qai_7Clk_GnfBElTFIa5VJP3pJUDd8g5H0PKs\"}," +
            "{\"kty\":\"oct\",\"kid\":\"ek1\",\"alg\":\"A128KW\",\"k\":\"Qi38jqNMENlgKaVRbhKWnQ\"}]}");

    SimpleJwkFilter filter = new SimpleJwkFilter();
    filter.setKid("hk1", false);
    JsonWebKey hmacKey = filter.filter(jwks.getJsonWebKeys()).iterator().next();

    filter = new SimpleJwkFilter();
    filter.setKid("ek1", false);
    JsonWebKey encKey = filter.filter(jwks.getJsonWebKeys()).iterator().next();

    JwtClaims claims = new JwtClaims();
    claims.setSubject("subject");
    claims.setAudience("audience");
    claims.setIssuer("issuer");
    claims.setExpirationTimeMinutesInTheFuture(10);
    claims.setNotBeforeMinutesInThePast(5);
    claims.setGeneratedJwtId();

    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setPayload(claims.toJson());
    jws.setKey(hmacKey.getKey());
    jws.setKeyIdHeaderValue(hmacKey.getKeyId());
    String innerJwt = jws.getCompactSerialization();

    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.A128KW);
    jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);
    jwe.setKey(encKey.getKey());
    jwe.setKeyIdHeaderValue(encKey.getKeyId());
    jwe.setContentTypeHeaderValue("JWT");
    jwe.setPayload(innerJwt);
    String jwt = jwe.getCompactSerialization();

    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setExpectedIssuer("issuer")
            .setExpectedAudience("audience")
            .setRequireSubject()
            .setRequireExpirationTime()
            .setDecryptionKey(encKey.getKey())
            .setVerificationKey(hmacKey.getKey())
            .build();

    JwtContext jwtContext = jwtConsumer.process(jwt);
    Assert.assertThat("subject", equalTo(jwtContext.getJwtClaims().getSubject()));
    List<JsonWebStructure> joseObjects = jwtContext.getJoseObjects();
    JsonWebStructure outerJsonWebObject = joseObjects.get(joseObjects.size() - 1);
    Assert.assertTrue(outerJsonWebObject instanceof JsonWebEncryption);
    Assert.assertThat("JWT", equalTo(outerJsonWebObject.getContentTypeHeaderValue()));
    Assert.assertThat("JWT", equalTo(outerJsonWebObject.getHeader(HeaderParameterNames.CONTENT_TYPE)));
    Assert.assertThat("JWT", equalTo(outerJsonWebObject.getHeaders().getStringHeaderValue(HeaderParameterNames.CONTENT_TYPE)));
    JsonWebStructure innerJsonWebObject = joseObjects.get(0);
    Assert.assertTrue(innerJsonWebObject instanceof JsonWebSignature);
}
 
Example 19
Source File: JwtIssuer.java    From light-4j with Apache License 2.0 4 votes vote down vote up
/**
 * A static method that generate JWT token from JWT claims object
 *
 * @param claims JwtClaims object
 * @return A string represents jwt token
 * @throws JoseException JoseException
 */
public static String getJwt(JwtClaims claims) throws JoseException {
    String jwt;
    RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
            jwtConfig.getKey().getFilename(), (String)secretConfig.get(JWT_PRIVATE_KEY_PASSWORD), jwtConfig.getKey().getKeyName());

    // A JWT is a JWS and/or a JWE with JSON claims as the payload.
    // In this example it is a JWS nested inside a JWE
    // So we first create a JsonWebSignature object.
    JsonWebSignature jws = new JsonWebSignature();

    // The payload of the JWS is JSON content of the JWT Claims
    jws.setPayload(claims.toJson());

    // The JWT is signed using the sender's private key
    jws.setKey(privateKey);

    // Get provider from security config file, it should be two digit
    // And the provider id will set as prefix for keyid in the token header, for example: 05100
    // if there is no provider id, we use "00" for the default value
    String provider_id = "";
    if (jwtConfig.getProviderId() != null) {
        provider_id = jwtConfig.getProviderId();
        if (provider_id.length() == 1) {
            provider_id = "0" + provider_id;
        } else if (provider_id.length() > 2) {
            logger.error("provider_id defined in the security.yml file is invalid; the length should be 2");
            provider_id = provider_id.substring(0, 2);
        }
    }
    jws.setKeyIdHeaderValue(provider_id + jwtConfig.getKey().getKid());

    // Set the signature algorithm on the JWT/JWS that will integrity protect the claims
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    // Sign the JWS and produce the compact serialization, which will be the inner JWT/JWS
    // representation, which is a string consisting of three dot ('.') separated
    // base64url-encoded parts in the form Header.Payload.Signature
    jwt = jws.getCompactSerialization();
    return jwt;
}
 
Example 20
Source File: TestUtils.java    From java with Apache License 2.0 4 votes vote down vote up
/**
 * Utility for generating JWTs
 *
 * @param uid Maps to the sub claim
 * @param issuer URL of the issuer
 * @param signing Private key to sign the JWT
 * @param dos Determines at what time point the JWT should be generated
 * @return
 * @throws Exception
 */
public static String generateJWT(String uid, String issuer, PrivateKey signing, DateOptions dos)
    throws Exception {
  JwtClaims claims = new JwtClaims();
  claims.setIssuer(issuer);
  ArrayList<String> audiences = new ArrayList<String>();

  claims.setSubject(uid);

  claims.setGeneratedJwtId();

  claims.setGeneratedJwtId(); // a unique identifier for the token

  if (dos == DateOptions.Now) {
    claims.setIssuedAtToNow(); // when the token was issued/created (now)
    claims.setNotBeforeMinutesInThePast(
        60000 / 1000 / 60); // time before which the token is not yet valid (2 minutes ago)
    claims.setExpirationTimeMinutesInTheFuture(
        60000 / 1000 / 60); // time before which the token is not yet valid (2 minutes ago)
  }

  if (dos == DateOptions.Past) {
    claims.setIssuedAt(NumericDate.fromMilliseconds(System.currentTimeMillis() - 120000L));
    claims.setNotBeforeMinutesInThePast(
        4); // time before which the token is not yet valid (2 minutes ago)
    claims.setExpirationTimeMinutesInTheFuture(
        -1); // time before which the token is not yet valid (2 minutes ago)
  }

  if (dos == DateOptions.Future) {
    claims.setIssuedAt(NumericDate.fromMilliseconds(System.currentTimeMillis() + 120000L));
    claims.setNotBeforeMinutesInThePast(
        -1); // time before which the token is not yet valid (2 minutes ago)
    claims.setExpirationTimeMinutesInTheFuture(
        4); // time before which the token is not yet valid (2 minutes ago)
  }

  JsonWebSignature jws = new JsonWebSignature();
  jws.setPayload(claims.toJson());
  jws.setKey(signing);

  jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
  return jws.getCompactSerialization();
}