Java Code Examples for org.jose4j.jwt.JwtClaims#setAudience()
The following examples show how to use
org.jose4j.jwt.JwtClaims#setAudience() .
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: JwtCachingAuthenticatorTest.java From dropwizard-auth-jwt with Apache License 2.0 | 6 votes |
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 2
Source File: JwtCachingAuthenticatorTest.java From dropwizard-auth-jwt with Apache License 2.0 | 6 votes |
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 3
Source File: Http2ClientIT.java From light-4j with Apache License 2.0 | 6 votes |
private static JwtClaims getTestClaims() { JwtClaims claims = new JwtClaims(); claims.setIssuer("urn:com:networknt:oauth2:v1"); claims.setAudience("urn:com.networknt"); claims.setExpirationTimeMinutesInTheFuture(10); 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", "1.0"); claims.setClaim("user_id", "steve"); claims.setClaim("user_type", "EMPLOYEE"); claims.setClaim("client_id", "aaaaaaaa-1234-1234-1234-bbbbbbbb"); List<String> scope = Arrays.asList("api.r", "api.w"); claims.setStringListClaim("scope", scope); // multi-valued claims work too and will end up as a JSON array return claims; }
Example 4
Source File: OauthHelperTest.java From light-4j with Apache License 2.0 | 6 votes |
private static JwtClaims getTestClaims() { JwtClaims claims = new JwtClaims(); claims.setIssuer("urn:com:networknt:oauth2:v1"); claims.setAudience("urn:com.networknt"); claims.setExpirationTimeMinutesInTheFuture(10); 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", "1.0"); claims.setClaim("user_id", "steve"); claims.setClaim("user_type", "EMPLOYEE"); claims.setClaim("client_id", "aaaaaaaa-1234-1234-1234-bbbbbbbb"); List<String> scope = Arrays.asList("api.r", "api.w"); claims.setStringListClaim("scope", scope); // multi-valued claims work too and will end up as a JSON array return claims; }
Example 5
Source File: Http2ClientTest.java From light-4j with Apache License 2.0 | 6 votes |
private static JwtClaims getTestClaims() { JwtClaims claims = new JwtClaims(); claims.setIssuer("urn:com:networknt:oauth2:v1"); claims.setAudience("urn:com.networknt"); claims.setExpirationTimeMinutesInTheFuture(10); 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", "1.0"); claims.setClaim("user_id", "steve"); claims.setClaim("user_type", "EMPLOYEE"); claims.setClaim("client_id", "aaaaaaaa-1234-1234-1234-bbbbbbbb"); List<String> scope = Arrays.asList("api.r", "api.w"); claims.setStringListClaim("scope", scope); // multi-valued claims work too and will end up as a JSON array return claims; }
Example 6
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 7
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 8
Source File: JwtGenerator.java From cloud-iot-core-androidthings with Apache License 2.0 | 5 votes |
@VisibleForTesting() JwtGenerator( @NonNull KeyPair keyPair, @NonNull String jwtAudience, @NonNull Duration tokenLifetime, @NonNull Clock clock) { checkNotNull(keyPair, "keypair"); checkNotNull(jwtAudience, "JWT audience"); checkNotNull(tokenLifetime, "Token lifetime"); checkNotNull(clock, "Clock"); String algorithm = keyPair.getPrivate().getAlgorithm(); if (!algorithm.equals(RSA_ALGORITHM) && !algorithm.equals(EC_ALGORITHM)) { throw new IllegalArgumentException("Keys use unsupported algorithm."); } mTokenLifetime = tokenLifetime; mClock = clock; mJws = new JsonWebSignature(); mJws.setAlgorithmHeaderValue(algorithm.equals("RSA") ? AlgorithmIdentifiers.RSA_USING_SHA256 : AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256); mJws.setHeader("typ", "JWT"); mJws.setKey(keyPair.getPrivate()); mClaims = new JwtClaims(); mClaims.setAudience(jwtAudience); }
Example 9
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 10
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 11
Source File: JwtHelper.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
/** * 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 12
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 13
Source File: JwtIssuer.java From light-4j with Apache License 2.0 | 5 votes |
/** * 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 14
Source File: JwtIssuer.java From light-4j with Apache License 2.0 | 5 votes |
/** * 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 15
Source File: Token.java From server_face_recognition with GNU General Public License v3.0 | 5 votes |
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 16
Source File: JwtConsumerTest.java From Jose4j with Apache License 2.0 | 4 votes |
@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 17
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); } }