Java Code Examples for org.jose4j.jwt.JwtClaims#setSubject()
The following examples show how to use
org.jose4j.jwt.JwtClaims#setSubject() .
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: JwtConsumerTest.java From Jose4j with Apache License 2.0 | 6 votes |
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 2
Source File: SecuredResource.java From dropwizard-auth-jwt with Apache License 2.0 | 6 votes |
@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 3
Source File: JWTAuthPluginTest.java From lucene-solr with Apache License 2.0 | 6 votes |
protected static JwtClaims generateClaims() { JwtClaims claims = new JwtClaims(); claims.setIssuer("IDServer"); // who creates the token and signs it claims.setAudience("Solr"); // to whom the token is intended to be sent claims.setExpirationTimeMinutesInTheFuture(10); // time when the token will expire (10 minutes from now) 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.setSubject("solruser"); // the subject/principal is whom the token is about claims.setStringClaim("scope", "solr:read"); claims.setClaim("name", "Solr User"); // additional claims/attributes about the subject can be added claims.setClaim("customPrincipal", "custom"); // additional claims/attributes about the subject can be added claims.setClaim("claim1", "foo"); // additional claims/attributes about the subject can be added claims.setClaim("claim2", "bar"); // additional claims/attributes about the subject can be added claims.setClaim("claim3", "foo"); // additional claims/attributes about the subject can be added List<String> roles = Arrays.asList("group-one", "other-group", "group-three"); claims.setStringListClaim("roles", roles); // multi-valued claims work too and will end up as a JSON array return claims; }
Example 4
Source File: JWTokenFactory.java From eplmp with Eclipse Public License 1.0 | 6 votes |
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; }
Example 5
Source File: JwtAuthFilterTest.java From trellis with Apache License 2.0 | 6 votes |
@Test void testJwtAuthFilter() { final ContainerRequestContext mockContext = mock(ContainerRequestContext.class); assertNotNull(filter); assertNotNull(producer); final String iss = "https://example.com/idp/"; final String sub = "acoburn"; final JwtClaims claims = new JwtClaims(); claims.setSubject(sub); claims.setIssuer(iss); producer.setJsonWebToken(new DefaultJWTCallerPrincipal(claims)); assertDoesNotThrow(() -> filter.filter(mockContext)); verify(mockContext).setSecurityContext(securityArgument.capture()); assertEquals(iss + sub, securityArgument.getValue().getUserPrincipal().getName()); }
Example 6
Source File: TokenHelper.java From git-as-svn with GNU General Public License v2.0 | 6 votes |
@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()); setClaim(claims, "type", user.getType().name()); } jwe.setPayload(claims.toJson()); return jwe.getCompactSerialization(); } catch (JoseException e) { throw new IllegalStateException(e); } }
Example 7
Source File: SecuredResource.java From dropwizard-auth-jwt with Apache License 2.0 | 6 votes |
@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 8
Source File: JwtUtil.java From light with Apache License 2.0 | 5 votes |
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 9
Source File: TokenUtils.java From thorntail with Apache License 2.0 | 5 votes |
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 10
Source File: TokenUtils.java From thorntail with Apache License 2.0 | 5 votes |
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 11
Source File: KeyPairUtilTest.java From Jose4j with Apache License 2.0 | 5 votes |
@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 12
Source File: BoxDeveloperEditionAPIConnection.java From box-java-sdk with Apache License 2.0 | 5 votes |
private String constructJWTAssertion(NumericDate now) { JwtClaims claims = new JwtClaims(); claims.setIssuer(this.getClientID()); claims.setAudience(JWT_AUDIENCE); if (now == null) { claims.setExpirationTimeMinutesInTheFuture(0.5f); } else { now.addSeconds(30L); 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; }
Example 13
Source File: WebIdPrincipalTest.java From trellis with Apache License 2.0 | 5 votes |
@Test void testNoIssuerPrincipal() { final String sub = "acoburn"; final JwtClaims claims = new JwtClaims(); claims.setSubject(sub); final JsonWebToken principal = new WebIdPrincipal(new DefaultJWTCallerPrincipal(claims)); assertNull(principal.getName()); }
Example 14
Source File: WebIdPrincipalTest.java From trellis with Apache License 2.0 | 5 votes |
@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 15
Source File: WebIdPrincipalTest.java From trellis with Apache License 2.0 | 5 votes |
@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 16
Source File: WebIdPrincipalTest.java From trellis with Apache License 2.0 | 5 votes |
@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 17
Source File: WebIdPrincipalTest.java From trellis with Apache License 2.0 | 5 votes |
@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 18
Source File: JwtAuthProviderTest.java From dropwizard-auth-jwt with Apache License 2.0 | 5 votes |
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 19
Source File: PushService.java From org.openhab.ui.habot with Eclipse Public License 1.0 | 4 votes |
/** * Send a notification and wait for the response. * * @param notification * @return * @throws GeneralSecurityException * @throws IOException * @throws JoseException * @throws ExecutionException * @throws InterruptedException */ public Future<Response> send(Notification notification) throws GeneralSecurityException, IOException, JoseException, ExecutionException, InterruptedException { assert (verifyKeyPair()); BaseEncoding base64url = BaseEncoding.base64Url(); Encrypted encrypted = encrypt(notification.getPayload(), notification.getUserPublicKey(), notification.getUserAuth(), notification.getPadSize()); byte[] dh = Utils.savePublicKey((ECPublicKey) encrypted.getPublicKey()); byte[] salt = encrypted.getSalt(); Invocation.Builder invocationBuilder = ClientBuilder.newClient().target(notification.getEndpoint()).request(); MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>(); headers.add("TTL", String.valueOf(notification.getTTL())); if (notification.hasPayload()) { headers.add("Content-Type", "application/octet-stream"); headers.add("Content-Encoding", "aesgcm"); headers.add("Encryption", "salt=" + base64url.omitPadding().encode(salt)); headers.add("Crypto-Key", "dh=" + base64url.encode(dh)); } if (notification.isGcm()) { if (gcmApiKey == null) { throw new IllegalStateException( "An GCM API key is needed to send a push notification to a GCM endpoint."); } headers.add("Authorization", "key=" + gcmApiKey); } if (vapidEnabled() && !notification.isGcm()) { JwtClaims claims = new JwtClaims(); claims.setAudience(notification.getOrigin()); claims.setExpirationTimeMinutesInTheFuture(12 * 60); claims.setSubject(subject); JsonWebSignature jws = new JsonWebSignature(); jws.setHeader("typ", "JWT"); jws.setHeader("alg", "ES256"); jws.setPayload(claims.toJson()); jws.setKey(privateKey); jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256); headers.add("Authorization", "WebPush " + jws.getCompactSerialization()); byte[] pk = Utils.savePublicKey((ECPublicKey) publicKey); if (headers.containsKey("Crypto-Key")) { headers.putSingle("Crypto-Key", headers.getFirst("Crypto-Key") + ";p256ecdsa=" + base64url.omitPadding().encode(pk)); } else { headers.add("Crypto-Key", "p256ecdsa=" + base64url.encode(pk)); } } invocationBuilder.headers(headers); if (notification.hasPayload()) { return invocationBuilder.async().post(Entity.entity(encrypted.getCiphertext(), new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, (String) null, "aesgcm"))); } else { return invocationBuilder.async().post(null); } }
Example 20
Source File: TestUtils.java From java with Apache License 2.0 | 4 votes |
/** * 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(); }