Java Code Examples for org.jose4j.jwt.JwtClaims#setIssuer()

The following examples show how to use org.jose4j.jwt.JwtClaims#setIssuer() . 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: JwtAuthFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testJwtAuthWebidFilter() {
    final ContainerRequestContext mockContext = mock(ContainerRequestContext.class);
    assertNotNull(filter);
    assertNotNull(producer);

    final String webid = "https://people.apache.org/~acoburn/#i";
    final String iss = "https://example.com/idp/";
    final String sub = "acoburn";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);
    claims.setClaim("webid", webid);

    producer.setJsonWebToken(new DefaultJWTCallerPrincipal(claims));
    assertDoesNotThrow(() -> filter.filter(mockContext));
    verify(mockContext).setSecurityContext(securityArgument.capture());
    assertEquals(webid, securityArgument.getValue().getUserPrincipal().getName());
}
 
Example 2
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 3
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
private void littleJweRoundTrip(String alg, String enc, String b64uKey) throws Exception
{
    byte[] raw = Base64Url.decode(b64uKey);
    Key key = new FakeHsmNonExtractableSecretKeySpec(raw, "AES");
    JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(5);
    claims.setSubject("subject");
    claims.setIssuer("issuer");
    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setPayload(claims.toJson());
    jwe.setAlgorithmHeaderValue(alg);
    jwe.setEncryptionMethodHeaderParameter(enc);
    jwe.setKey(key);

    String jwt = jwe.getCompactSerialization();
    JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder();
    jwtConsumerBuilder.setAllowedClockSkewInSeconds(60);
    jwtConsumerBuilder.setRequireSubject();
    jwtConsumerBuilder.setExpectedIssuer("issuer");
    jwtConsumerBuilder.setDecryptionKey(key);
    jwtConsumerBuilder.setDisableRequireSignature();
    JwtConsumer jwtConsumer = jwtConsumerBuilder.build();
    JwtClaims processedClaims = jwtConsumer.processToClaims(jwt);
    Assert.assertThat(processedClaims.getSubject(), equalTo("subject"));
}
 
Example 4
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 5
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 6
Source File: WebIdPrincipalTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testIssNoSlashPrincipal() {
    final String iss = "http://idp.example.com";
    final String sub = "acoburn";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);
    final JsonWebToken principal = new WebIdPrincipal(new DefaultJWTCallerPrincipal(claims));
    assertTrue(principal.getClaimNames().contains("sub"));
    assertEquals(iss + "/" + sub, principal.getName());
    assertEquals(iss, principal.getIssuer());
    assertEquals(iss, principal.getClaim("iss"));
}
 
Example 7
Source File: WebIdPrincipalTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testWebIdPrincipal() {
    final String iss = "https://example.com/idp/";
    final String sub = "acoburn";
    final String webid = "https://example.com/profile#me";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);
    claims.setClaim("webid", webid);
    final JsonWebToken principal = new WebIdPrincipal(new DefaultJWTCallerPrincipal(claims));
    assertEquals(webid, principal.getName());
    assertEquals(iss, principal.getIssuer());
    assertEquals(iss, principal.getClaim("iss"));
    assertEquals(sub, principal.getClaim("sub"));
}
 
Example 8
Source File: WebIdPrincipalTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testWebIdSubPrincipal() {
    final String iss = "https://example.com/idp/";
    final String webid = "https://example.com/profile#me";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(webid);
    claims.setIssuer(iss);
    final JsonWebToken principal = new WebIdPrincipal(new DefaultJWTCallerPrincipal(claims));
    assertEquals(webid, principal.getName());
    assertEquals(iss, principal.getIssuer());
    assertEquals(iss, principal.getClaim("iss"));
}
 
Example 9
Source File: WebIdPrincipalTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testNoSubPrincipal() {
    final String iss = "https://example.com/idp/";
    final JwtClaims claims = new JwtClaims();
    claims.setIssuer(iss);
    final JsonWebToken principal = new WebIdPrincipal(new DefaultJWTCallerPrincipal(claims));
    assertNull(principal.getName());
}
 
Example 10
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 11
Source File: WebIdPrincipalTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testBasicPrincipal() {
    final String iss = "https://example.com/idp/";
    final String sub = "acoburn";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);
    final JsonWebToken principal = new WebIdPrincipal(new DefaultJWTCallerPrincipal(claims));
    assertTrue(principal.getClaimNames().contains("sub"));
    assertEquals(iss + sub, principal.getName());
    assertEquals(iss, principal.getIssuer());
    assertEquals(iss, principal.getClaim("iss"));
}
 
Example 12
Source File: WebIdSecurityContextTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testAdminRoles() {
    final SecurityContext mockDelegate = mock(SecurityContext.class);
    final String iss = "https://example.com/idp/";
    final String sub = "acoburn";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);
    final JsonWebToken principal = new DefaultJWTCallerPrincipal(claims);

    final SecurityContext ctx = new WebIdSecurityContext(mockDelegate, principal, singleton(iss + sub));
    assertTrue(ctx.isUserInRole(WebIdSecurityContext.ADMIN_ROLE));
    assertFalse(ctx.isUserInRole("other-role"));
}
 
Example 13
Source File: JwtIssuer.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a default JwtClaims
 *
 * @return JwtClaims
 */
public static JwtClaims getDefaultJwtClaims() {

    JwtClaims claims = new JwtClaims();

    claims.setIssuer(jwtConfig.getIssuer());
    claims.setAudience(jwtConfig.getAudience());
    claims.setExpirationTimeMinutesInTheFuture(jwtConfig.getExpiredInMinutes());
    claims.setGeneratedJwtId(); // a unique identifier for the token
    claims.setIssuedAtToNow();  // when the token was issued/created (now)
    claims.setNotBeforeMinutesInThePast(2); // time before which the token is not yet valid (2 minutes ago)
    claims.setClaim("version", jwtConfig.getVersion());
    return claims;

}
 
Example 14
Source File: JwtIssuer.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a default JwtClaims
 * @param expiresIn expires in
 * @return JwtClaims
 */
public static JwtClaims getJwtClaimsWithExpiresIn(int expiresIn) {

    JwtClaims claims = new JwtClaims();

    claims.setIssuer(jwtConfig.getIssuer());
    claims.setAudience(jwtConfig.getAudience());
    claims.setExpirationTimeMinutesInTheFuture(expiresIn/60);
    claims.setGeneratedJwtId(); // a unique identifier for the token
    claims.setIssuedAtToNow();  // when the token was issued/created (now)
    claims.setNotBeforeMinutesInThePast(2); // time before which the token is not yet valid (2 minutes ago)
    claims.setClaim("version", jwtConfig.getVersion());
    return claims;
}
 
Example 15
Source File: JwtUtil.java    From light with Apache License 2.0 5 votes vote down vote up
public static String getJwt(Map<String, Object> userMap, Boolean rememberMe) throws JoseException {
    String jwt = null;
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(issuer);
    claims.setAudience(audience);
    claims.setExpirationTimeMinutesInTheFuture(rememberMe ? rememberMin : expireMin);
    claims.setGeneratedJwtId();
    claims.setIssuedAtToNow();
    claims.setNotBeforeMinutesInThePast(clockSkewMin);
    claims.setSubject(subject);

    claims.setClaim("userId", userMap.get("userId"));
    claims.setClaim("clientId", userMap.get("clientId"));
    claims.setStringListClaim("roles", (List<String>)userMap.get("roles"));
    if(userMap.get("host") != null) claims.setClaim("host", userMap.get("host"));
    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);

    // 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();
    //System.out.println("JWT: " + jwt);

    return jwt;
}
 
Example 16
Source File: JwtAuthProviderTest.java    From dropwizard-auth-jwt with Apache License 2.0 5 votes vote down vote up
private JwtClaims claimsForUser(String user) {
    final JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(5);
    claims.setSubject(user);
    claims.setIssuer("Issuer");
    claims.setAudience("Audience");
    return claims;
}
 
Example 17
Source File: TokenUtils.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public static String createToken(String subject, String groupName) throws Exception {
    JwtClaims claims = new JwtClaims();
    claims.setIssuer("http://testsuite-jwt-issuer.io");
    claims.setSubject(subject);
    if (groupName != null) {
        claims.setStringListClaim("groups", groupName);
    }
    claims.setClaim("upn", "[email protected]");
    claims.setExpirationTimeMinutesInTheFuture(1);

    return createTokenFromJson(claims.toJson());
}
 
Example 18
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 19
Source File: JWT_Encrypted_Creator_Callout.java    From iloveapis2015-jwt-jwe-jws with Apache License 2.0 4 votes vote down vote up
public ExecutionResult execute (MessageContext msgCtxt,
                                ExecutionContext exeCtxt) {

    String varName;
    try {
        //JWTClaimsSet claims = new JWTClaimsSet();
        JwtClaims claims = new JwtClaims();
        String ISSUER = getIssuer(msgCtxt);
        claims.setIssuer(ISSUER);
        Float expirationInMinutes = Float.valueOf(getExpirationInMinutes(msgCtxt));
        claims.setExpirationTimeMinutesInTheFuture(expirationInMinutes);
        String uniqueID = UUID.randomUUID().toString();
        claims.setJwtId(uniqueID);

        /***************************SENDER'S END ***********************************/
        claims.setSubject("users");
        claims.setClaim("email", "[email protected]");
        claims.setClaim("Country", "USA");
        claims.setClaim("active", "true");
        claims.setClaim("dealerId", "1234");
        claims.setClaim("url", "www.mycompany.com");

        RSAPublicKey publicKey = (RSAPublicKey) getPublicKey(msgCtxt);
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);
        SecretKey contentEncryptKey = keyGen.generateKey();

        JsonWebEncryption jwe = new JsonWebEncryption();
        jwe.setKey(publicKey);
        jwe.setPayload(claims.toJson());
        jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.RSA_OAEP_256);
        jwe.setContentEncryptionKey(contentEncryptKey.getEncoded());
        jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);
        SecureRandom iv = SecureRandom.getInstance("SHA1PRNG");
        jwe.setIv(iv.generateSeed(16));
        String encryptedJwt = jwe.getCompactSerialization();
        System.out.println("Encrypted ::" + encryptedJwt);
        varName = getVarname("encryptedJwt");
        msgCtxt.setVariable(varName, encryptedJwt);
    }

    catch (Exception e) {
        //e.printStackTrace();
        varName = getVarname( "error");
        msgCtxt.setVariable(varName, "Exception (A): " + e.toString());
        System.out.println("exception: " + e.toString());
        varName = getVarname("stacktrace");
        msgCtxt.setVariable(varName, "Stack (A): " + ExceptionUtils.getStackTrace(e));
        return ExecutionResult.ABORT;
    }
    return ExecutionResult.SUCCESS;

}
 
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();
}