org.jose4j.jws.JsonWebSignature Java Examples

The following examples show how to use org.jose4j.jws.JsonWebSignature. 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: KeyLocationResolver.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Override
public Key resolveKey(JsonWebSignature jws, List<JsonWebStructure> nestingContext) throws UnresolvableKeyException {
    verifyKid(jws, authContextInfo.getTokenKeyId());

    // The verificationKey may have been calculated in the constructor from the local PEM, or,
    // if authContextInfo.getTokenKeyId() is not null - from the local JWK(S) content.
    if (verificationKey != null) {
        return verificationKey;
    }

    // At this point the key can be loaded from either the HTTPS or local JWK(s) content using
    // the current token kid to select the key.
    PublicKey key = tryAsJwk(jws);

    if (key == null) {
        if (authContextInfo.getPublicKeyContent() != null) {
            throw PrincipalMessages.msg.failedToLoadPublicKeyWhileResolving();
        } else {
            throw PrincipalMessages.msg
                    .failedToLoadPublicKeyFromLocationWhileResolving(authContextInfo.getPublicKeyLocation());
        }
    }
    return key;
}
 
Example #2
Source File: VerificationJwkSelectorTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void uniqueKidTestFRJwksEndpoint() throws JoseException
{
    // JSON content from https://demo.forgerock.com:8443/openam/oauth2/connect/jwk_uri on Jan 8, 2015
    String json = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"fb301b61-9b8a-4c34-9212-5d6fb9df1a57\",\"use\":\"sig\",\"alg\":\"RS256\",\"n\":\"AK0kHP1O-RgdgLSoWxkuaYoi5Jic6hLKeuKw8WzCfsQ68ntBDf6tVOTn_kZA7Gjf4oJAL1dXLlxIEy-kZWnxT3FF-0MQ4WQYbGBfaW8LTM4uAOLLvYZ8SIVEXmxhJsSlvaiTWCbNFaOfiII8bhFp4551YB07NfpquUGEwOxOmci_\",\"e\":\"AQAB\"}]}";

    JsonWebKeySet jwks = new JsonWebKeySet(json);

    VerificationJwkSelector verificationJwkSelector = new VerificationJwkSelector();
    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    jws.setKeyIdHeaderValue("fb301b61-9b8a-4c34-9212-5d6fb9df1a57");
    List<JsonWebKey> jsonWebKeys = jwks.getJsonWebKeys();
    List<JsonWebKey> selected = verificationJwkSelector.selectList(jws, jsonWebKeys);
    assertThat(1, equalTo(selected.size()));
    assertThat("fb301b61-9b8a-4c34-9212-5d6fb9df1a57", equalTo(selected.get(0).getKeyId()));
}
 
Example #3
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 #4
Source File: VerificationJwkSelectorTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void uniqueKidTestNriPhpJwksEndpoint() throws JoseException
{
    // JSON content from https://connect.openid4.us/connect4us.jwk on Jan 8, 2015
    String json = "{\n" +
            " \"keys\":[\n" +
            "  {\n" +
            "   \"kty\":\"RSA\",\n" +
            "   \"n\":\"tf_sB4M0sHearRLzz1q1JRgRdRnwk0lz-IcVDFlpp2dtDVyA-ZM8Tu1swp7upaTNykf7cp3Ne_6uW3JiKvRMDdNdvHWCzDHmbmZWGdnFF9Ve-D1cUxj4ETVpUM7AIXWbGs34fUNYl3Xzc4baSyvYbc3h6iz8AIdb_1bQLxJsHBi-ydg3NMJItgQJqBiwCmQYCOnJlekR-Ga2a5XlIx46Wsj3Pz0t0dzM8gVSU9fU3QrKKzDFCoFHTgig1YZNNW5W2H6QwANL5h-nbgre5sWmDmdnfiU6Pj5GOQDmp__rweinph8OAFNF6jVqrRZ3QJEmMnO42naWOsxV2FAUXafksQ\",\n" +
            "   \"e\":\"AQAB\",\n" +
            "   \"kid\":\"ABOP-00\"\n" +
            "  }\n" +
            " ]\n" +
            "}\n";

    JsonWebKeySet jwks = new JsonWebKeySet(json);

    VerificationJwkSelector verificationJwkSelector = new VerificationJwkSelector();
    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA384);
    jws.setKeyIdHeaderValue("ABOP-00");
    List<JsonWebKey> jsonWebKeys = jwks.getJsonWebKeys();
    List<JsonWebKey> selected = verificationJwkSelector.selectList(jws, jsonWebKeys);
    assertThat(1, equalTo(selected.size()));
    assertThat("ABOP-00", equalTo(selected.get(0).getKeyId()));
}
 
Example #5
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 #6
Source File: DefaultCipherExecutor.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Verify signature.
 *
 * @param value the value
 * @return the value associated with the signature, which may have to
 * be decoded, or null.
 */
private String verifySignature(@NotNull final String value) {
    try {
        final JsonWebSignature jws = new JsonWebSignature();
        jws.setCompactSerialization(value);
        jws.setKey(this.secretKeySigningKey);
        final boolean verified = jws.verifySignature();
        if (verified) {
            logger.debug("Signature successfully verified. Payload is [{}]", jws.getPayload());
            return jws.getPayload();
        }
        return null;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: JwtBuilder.java    From boost with Eclipse Public License 1.0 6 votes vote down vote up
public static String buildJwt(String subject, String issuer, String[] claims)
        throws JoseException, MalformedClaimException {
    me = new JwtBuilder();
    init();
    me.claims = new JwtClaims();
    me.jws = new JsonWebSignature();

    me.jws.setKeyIdHeaderValue(rsajwk.getKeyId());
    me.jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    // The JWT is signed using the private key, get the key we'll use every time.
    me.jws.setKey(rsajwk.getPrivateKey());
    if (subject != null) {
        me.claims.setClaim("sub", subject);
        me.claims.setClaim("upn", subject);
    }
    me.claims.setIssuer(issuer);
    me.claims.setExpirationTimeMinutesInTheFuture(60);
    setClaims(claims);
    if (me.claims.getIssuedAt() == null) {
        me.claims.setIssuedAtToNow();
    }
    me.jws.setPayload(me.claims.toJson());
    return me.jws.getCompactSerialization();
}
 
Example #8
Source File: X509VerificationKeyResolver.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
private Key attemptAll(JsonWebSignature jws) throws UnresolvableKeyException
{
    for (X509Certificate certificate : x5tMap.values())
    {
        PublicKey publicKey = certificate.getPublicKey();
        jws.setKey(publicKey);

        try
        {
            if (jws.verifySignature())
            {
                return publicKey;
            }
        }
        catch (JoseException e)
        {
            log.debug("Verify signature didn't work: {}", ExceptionHelp.toStringWithCauses(e));
        }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("Unable to verify the signature with any of the provided keys - SHA-1 thumbs of provided certificates: ");
    sb.append(x5tMap.keySet());
    sb.append(".");
    throw new UnresolvableKeyException(sb.toString());
}
 
Example #9
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 #10
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 #11
Source File: VerificationJwkSelector.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
public List<JsonWebKey> selectList(JsonWebSignature jws, Collection<JsonWebKey> keys) throws JoseException
{
    SimpleJwkFilter filter = SelectorSupport.commonFilterForInbound(jws);
    List<JsonWebKey> filtered = filter.filter(keys);

    if (hasMoreThanOne(filtered))
    {
        filter.setAlg(jws.getAlgorithmHeaderValue(), SimpleJwkFilter.OMITTED_OKAY);
        filtered = filter.filter(filtered);
    }

    if (hasMoreThanOne(filtered) && EllipticCurveJsonWebKey.KEY_TYPE.equals(jws.getKeyType()))
    {
        JsonWebSignatureAlgorithm algorithm = jws.getAlgorithm();
        EcdsaUsingShaAlgorithm ecdsaAlgorithm = (EcdsaUsingShaAlgorithm) algorithm;
        filter.setCrv(ecdsaAlgorithm.getCurveName(), SimpleJwkFilter.OMITTED_OKAY);
        filtered = filter.filter(filtered);
    }

    return filtered;

    // todo -> if >1, try even harder... maybe. But are there actually realistic cases where this will happen?
}
 
Example #12
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 #13
Source File: HttpsJwksVerificationKeyResolverTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnEx() throws Exception
{
    String location = "https://www.example.org/";

    Get mockGet = mock(Get.class);
    when(mockGet.get(location)).thenThrow(new IOException(location + "says 'no GET for you!'"));
    HttpsJwks httpsJkws = new HttpsJwks(location);
    httpsJkws.setSimpleHttpGet(mockGet);
    HttpsJwksVerificationKeyResolver resolver = new HttpsJwksVerificationKeyResolver(httpsJkws);

    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);
    jws.setKeyIdHeaderValue("nope");
    try
    {
        Key key = resolver.resolveKey(jws, Collections.<JsonWebStructure>emptyList());
        fail("shouldn't have resolved a key but got " + key);

    }
    catch (UnresolvableKeyException e)
    {
        log.debug("this was expected and is okay: {}", e.toString());
    }
}
 
Example #14
Source File: JwtBuilder.java    From microshed-testing with Apache License 2.0 6 votes vote down vote up
public static String buildJwt(String subject, String issuer, String[] claims) throws JoseException, MalformedClaimException {
    JwtBuilder builder = new JwtBuilder();
    init();
    builder.claims = new JwtClaims();
    builder.jws = new JsonWebSignature();

    builder.jws.setKeyIdHeaderValue(rsajwk.getKeyId());
    builder.jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    // The JWT is signed using the private key, get the key we'll use every time.
    builder.jws.setKey(rsajwk.getPrivateKey());
    if (subject != null) {
        builder.claims.setClaim("sub", subject);
        builder.claims.setClaim("upn", subject);
    }
    builder.claims.setIssuer(issuer == null ? JwtConfig.DEFAULT_ISSUER : issuer);
    builder.claims.setExpirationTimeMinutesInTheFuture(60);
    setClaims(builder, claims);
    if (builder.claims.getIssuedAt() == null) {
        builder.claims.setIssuedAtToNow();
    }
    builder.jws.setPayload(builder.claims.toJson());
    return builder.jws.getCompactSerialization();
}
 
Example #15
Source File: DefaultCipherExecutor.java    From nano-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Verify signature.
 *
 * @param value the value
 * @return the value associated with the signature, which may have to
 * be decoded, or null.
 */
private String verifySignature(@NotNull final String value) {
    try {
        final JsonWebSignature jws = new JsonWebSignature();
        jws.setCompactSerialization(value);
        jws.setKey(this.secretKeySigningKey);
        final boolean verified = jws.verifySignature();
        if (verified) {
            LOGGER.debug("Signature successfully verified. Payload is [{}]", jws.getPayload());
            return jws.getPayload();
        }
        return null;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
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 #17
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
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 #18
Source File: JsonWebToken.java    From datamill with ISC License 6 votes vote down vote up
public String encoded() {
    JsonWebSignature signature = new JsonWebSignature();

    signature.setPayload(claims.toJson());
    signature.setKeyIdHeaderValue(key.getId());

    switch (key.getType()) {
        case SYMMETRIC:
            signature.setKey(key.getKey());
            signature.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
            break;
        case RSA:
            signature.setKey(((JsonKeyPair) key).getPrivateKey());
            signature.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
            break;
    }

    try {
        return signature.getCompactSerialization();
    } catch (JoseException e) {
        throw new SecurityException(e);
    }
}
 
Example #19
Source File: Jose4jJoseImpl.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public String sign(SignatureInput input) {
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(input.getData());
    for (Map.Entry<String, Object> entry : input.getHeaders().entrySet()) {
        jws.getHeaders().setObjectHeaderValue(entry.getKey(), entry.getValue());
    }
    jws.setAlgorithmHeaderValue(config.signatureAlgorithm());
    if (!config.signatureDataEncoding()) {
        jws.getHeaders().setObjectHeaderValue(HeaderParameterNames.BASE64URL_ENCODE_PAYLOAD, false);
        jws.setCriticalHeaderNames(HeaderParameterNames.BASE64URL_ENCODE_PAYLOAD);
    }
    if (config.includeSignatureKeyAlias()) {
        jws.setKeyIdHeaderValue(signatureKeyAlias());
    }
    jws.setKey(getSignatureKey(jws, JoseOperation.SIGN));
    try {
        return config.signatureDataDetached()
                ? jws.getDetachedContentCompactSerialization() : jws.getCompactSerialization();
    } catch (org.jose4j.lang.JoseException ex) {
        throw new JoseException(ex.getMessage(), ex);
    }
}
 
Example #20
Source File: JwtSignTest.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
private void doTestSignedExistingClaims(String jwt) throws Exception {

        JsonWebSignature jws = getVerifiedJws(jwt);
        JwtClaims claims = JwtClaims.parse(jws.getPayload());

        Assert.assertEquals(9, claims.getClaimsMap().size());
        checkDefaultClaimsAndHeaders(getJwsHeaders(jwt, 2), claims, "RS256", 1000);

        Assert.assertEquals("https://server.example.com", claims.getIssuer());
        Assert.assertEquals("a-123", claims.getClaimValue("jti"));
        Assert.assertEquals("24400320", claims.getSubject());
        Assert.assertEquals("[email protected]", claims.getClaimValue("upn"));
        Assert.assertEquals("jdoe", claims.getClaimValue("preferred_username"));
        Assert.assertEquals("s6BhdRkqt3", claims.getAudience().get(0));
        Assert.assertEquals(1311281970L, claims.getExpirationTime().getValue());
        Assert.assertEquals(1311280970L, claims.getIssuedAt().getValue());
        Assert.assertEquals(1311280969, claims.getClaimValue("auth_time", Long.class).longValue());
    }
 
Example #21
Source File: SelectorSupport.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
public static SimpleJwkFilter commonFilterForInbound(JsonWebStructure jwx) throws JoseException
{
    SimpleJwkFilter filter = new SimpleJwkFilter();
    String kid = jwx.getKeyIdHeaderValue();
    if (kid != null)
    {
        filter.setKid(kid, SimpleJwkFilter.VALUE_REQUIRED);
    }

    String x5t = jwx.getX509CertSha1ThumbprintHeaderValue();
    String x5tS256 = jwx.getX509CertSha256ThumbprintHeaderValue();
    filter.setAllowFallbackDeriveFromX5cForX5Thumbs(true);
    if (x5t != null)
    {
        filter.setX5t(x5t, SimpleJwkFilter.OMITTED_OKAY);
    }
    if (x5tS256 != null)
    {
        filter.setX5tS256(x5tS256, SimpleJwkFilter.OMITTED_OKAY);
    }

    String keyType = jwx.getAlgorithm().getKeyType();
    filter.setKty(keyType);
    String use = (jwx instanceof JsonWebSignature) ? Use.SIGNATURE : Use.ENCRYPTION;
    filter.setUse(use, SimpleJwkFilter.OMITTED_OKAY);
    return filter;
}
 
Example #22
Source File: Http2ClientTest.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 #23
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 #24
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 #25
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 #26
Source File: Jose4jJoseImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private String verificationKeyAlias(JsonWebSignature jws) {

        if (config.acceptSignatureAlias()) {
            return jws.getKeyIdHeaderValue();
        }

        if (config.signatureKeyAliasIn() == null) {
            return config.signatureKeyAlias();
        }
        return config.signatureKeyAliasIn();
    }
 
Example #27
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 #28
Source File: Jose4jJoseImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private Key getSignatureKey(JsonWebSignature jws, JoseOperation operation) {
    if ("jwk".equals(this.config.keystoreType())) {
        return getJwkKey((operation.equals(JoseOperation.SIGN) ? signatureKeyAlias() : verificationKeyAlias(jws)),
                config.signatureAlgorithm());

    } else if (operation.equals(JoseOperation.SIGN)) {
        return getJavaStorePrivateKey(signatureKeyAlias(), config.signatureKeyPassword());

    } else {
        return getJavaStorePublicKey(verificationKeyAlias(jws));
    }
}
 
Example #29
Source File: JsonWebStructureTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test (expected = IntegrityException.class)
public void integrityCheckFailsJws() throws JoseException
{
    String cs = "eyJhbGciOiJIUzI1NiIsImtpZCI6IjllciJ9." +
            "RGFubnksIEknbSBoYXZpbmcgYSBwYXJ0eSB0aGlzIHdlZWtlbmQuLi4gSG93IHdvdWxkIHlvdSBsaWtlIHRvIGNvbWUgb3ZlciBhbmQgbW93IG15IGxhd24_." +
            "45s_xV_ol7JBwVcTPbWbaYT5i4mb7j27lEhi_bxpExw";
    JsonWebStructure jwx = JsonWebStructure.fromCompactSerialization(cs);
    Assert.assertTrue(cs + " should give a JWS " + jwx, jwx instanceof JsonWebSignature);
    Assert.assertEquals(AlgorithmIdentifiers.HMAC_SHA256, jwx.getAlgorithmHeaderValue());
    jwx.setKey(oct256bitJwk.getKey());
    Assert.assertEquals(oct256bitJwk.getKeyId(), jwx.getKeyIdHeaderValue());
    jwx.getPayload();
}
 
Example #30
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();
}