org.jose4j.jws.AlgorithmIdentifiers Java Examples

The following examples show how to use org.jose4j.jws.AlgorithmIdentifiers. 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: Jose4jVerifierTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@Override
protected void validateToken(String token, RSAPublicKey publicKey, String issuer, int expGracePeriodSecs) throws Exception {
    JwtConsumerBuilder builder = new JwtConsumerBuilder()
        .setRequireExpirationTime()
        .setRequireSubject()
        .setSkipDefaultAudienceValidation()
        .setExpectedIssuer(issuer)
        .setJwsAlgorithmConstraints(
            new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST,
                                     AlgorithmIdentifiers.RSA_USING_SHA256));

    builder.setVerificationKey(publicKey);

    if (expGracePeriodSecs > 0) {
        builder.setAllowedClockSkewInSeconds(expGracePeriodSecs);
    }
    else {
        builder.setEvaluationTime(NumericDate.fromSeconds(0));
    }

    JwtConsumer jwtConsumer = builder.build();
    JwtContext jwtContext = jwtConsumer.process(token);
    String type = jwtContext.getJoseObjects().get(0).getHeader("typ");
    //  Validate the JWT and process it to the Claims
    jwtConsumer.processContext(jwtContext);
}
 
Example #2
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 #3
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 #4
Source File: VerificationJwkSelectorTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void uniqueKidTestMiterJwksEndpoint() throws JoseException
{
    // JSON content from https://mitreid.org/jwk on Jan 8, 2015
    String json = "{\"keys\":[{\"alg\":\"RS256\",\"e\":\"AQAB\",\"n\":\"23zs5r8PQKpsKeoUd2Bjz3TJkUljWqMD8X98SaIb1LE7dCQzi9jwO58FGL0ieY1Dfnr9-g1iiY8sNzV-byawK98W9yFiopaghfoKtxXgUD8pi0fLPeWmAkntjn28Z_WZvvA265ELbBhphPXEJcFhdzUfgESHVuqFMEqp1pB-CP0\"," +
            "\"kty\":\"RSA\",\"kid\":\"rsa1\"}]}";

    JsonWebKeySet jwks = new JsonWebKeySet(json);

    VerificationJwkSelector verificationJwkSelector = new VerificationJwkSelector();
    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    jws.setKeyIdHeaderValue("rsa1");
    List<JsonWebKey> jsonWebKeys = jwks.getJsonWebKeys();
    List<JsonWebKey> selected = verificationJwkSelector.selectList(jws, jsonWebKeys);
    assertThat(1, equalTo(selected.size()));
    assertThat("rsa1", equalTo(selected.get(0).getKeyId()));
}
 
Example #5
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 #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: JoseCookbookTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void Octet_Key_MAC_3_5() throws JoseException
{
    String jwkJson =
            "   {\n" +
            "     \"kty\": \"oct\",\n" +
            "     \"kid\": \"018c0ae5-4d9b-471b-bfd6-eef314bc7037\",\n" +
            "     \"use\": \"sig\",\n" +
            "     \"alg\": \"HS256\",\n" +
            "     \"k\": \"hJtXIZ2uSN5kbQfbtTNWbpdmhkV8FJG-Onbc6mxCcYg\"\n" +
            "   }";
    JsonWebKey jwk = JsonWebKey.Factory.newJwk(jwkJson);
    assertThat(jwk.getKeyId(), is(equalTo("018c0ae5-4d9b-471b-bfd6-eef314bc7037")));
    assertThat(jwk.getUse(), is(equalTo(Use.SIGNATURE)));
    assertThat(jwk.getAlgorithm(), is(equalTo(AlgorithmIdentifiers.HMAC_SHA256)));
    OctetSequenceJsonWebKey octJwk = (OctetSequenceJsonWebKey) jwk;
    byte[] octetSequence = octJwk.getOctetSequence();
    assertThat(octetSequence.length, is(equalTo(32)));

    jwk = JsonWebKey.Factory.newJwk(jwk.getKey());
    String jsonOutput = jwk.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
    assertThat(jsonOutput, containsString("\"hJtXIZ2uSN5kbQfbtTNWbpdmhkV8FJG-Onbc6mxCcYg\""));
}
 
Example #8
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 #9
Source File: JwtHelper.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Performs verifications on a JWT token, then parses it into a {@link AuthenticationException} instance
 *
 * @param jwt the base64-encoded JWT token from the request
 * @return the {@link Authentication} derived from the information in the token
 * @throws AuthenticationException
 */
public Authentication verifyAndParseJwtAccessToken(String jwt) throws AuthenticationException {
    JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(30)
            .setRequireSubject().setExpectedIssuer(ISSUER_NAME).setExpectedAudience(AUDIENCE)
            .setVerificationKey(jwtWebKey.getKey())
            .setJwsAlgorithmConstraints(ConstraintType.WHITELIST, AlgorithmIdentifiers.RSA_USING_SHA256).build();

    try {
        JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
        String username = jwtClaims.getSubject();
        List<String> roles = jwtClaims.getStringListClaimValue("role");
        Authentication auth = new Authentication(username, roles.toArray(new String[roles.size()]));
        return auth;
    } catch (Exception e) {
        logger.error("Error while processing JWT token", e);
        throw new AuthenticationException(e.getMessage());
    }
}
 
Example #10
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 #11
Source File: BoxDeveloperEditionAPIConnection.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
private String getAlgorithmIdentifier() {
    String algorithmId = AlgorithmIdentifiers.RSA_USING_SHA256;
    switch (this.encryptionAlgorithm) {
        case RSA_SHA_384:
            algorithmId = AlgorithmIdentifiers.RSA_USING_SHA384;
            break;
        case RSA_SHA_512:
            algorithmId = AlgorithmIdentifiers.RSA_USING_SHA512;
            break;
        case RSA_SHA_256:
        default:
            break;
    }

    return algorithmId;
}
 
Example #12
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 #13
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 #14
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 #15
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 #16
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 #17
Source File: TokenUtils.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public static String createTokenFromJson(String json) throws Exception {
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(json);
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    jws.setKey(getPrivateKey());
    return jws.getCompactSerialization();
}
 
Example #18
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 #19
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 #20
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 #21
Source File: Operation.java    From pingid-api-playground with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private String buildRequestToken(JSONObject requestBody) {
	
	JSONObject requestHeader = buildRequestHeader();
	
	JSONObject payload = new JSONObject();
	payload.put("reqHeader", requestHeader);
	payload.put("reqBody", requestBody);
	
	JsonWebSignature jws = new JsonWebSignature();

	jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
	jws.setHeader("orgAlias", this.orgAlias);
	jws.setHeader("token", this.token);
	
	jws.setPayload(payload.toJSONString());
	
    // Set the verification key
    HmacKey key = new HmacKey(Base64.decode(this.useBase64Key));
    jws.setKey(key);
	
	String jwsCompactSerialization = null;
	try {
		jwsCompactSerialization = jws.getCompactSerialization();
	} catch (JoseException e) {
		e.printStackTrace();
	}
	
	this.requestToken = jwsCompactSerialization;
			
	return jwsCompactSerialization;
}
 
Example #22
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 #23
Source File: JsonWebStructureTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void jws1() throws JoseException
{
    String cs = "eyJhbGciOiJIUzI1NiIsImtpZCI6IjllciJ9." +
            "WW91J2xsIGdldCBub3RoaW5nLCBhbmQgbGlrZSBpdCE." +
            "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());
    String payload = jwx.getPayload();
    Assert.assertEquals(YOU_LL_GET_NOTHING_AND_LIKE_IT, payload);
    Assert.assertEquals(oct256bitJwk.getKeyId(), jwx.getKeyIdHeaderValue());
}
 
Example #24
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 #25
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 #26
Source File: JwtSignatureImpl.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public JwtEncryptionBuilder innerSign() throws JwtSignatureException {

    if (!signingKeyConfigured()) {
        if (headers.containsKey("alg") && !"none".equals(headers.get("alg"))) {
            throw ImplMessages.msg.signKeyPropertyRequired(headers.get("alg").toString());
        }
        if (headers.containsKey("kid")) {
            throw ImplMessages.msg.signAlgorithmRequired();
        }
        headers.put("alg", AlgorithmIdentifiers.NONE);
    }
    return new JwtEncryptionImpl(sign(), true);
}
 
Example #27
Source File: JwtGenerator.java    From cloud-iot-core-androidthings with Apache License 2.0 5 votes vote down vote up
@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 #28
Source File: TokenBuilder.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return a download token with the current builder parameters.
 * @throws JoseException if there is an error generating the token
 */
public String getToken() throws JoseException {
    JwtClaims claims = getClaims();

    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setKey(getKeyForSecret(
            this.secret.orElseThrow(
                () -> new IllegalArgumentException("No secret has been set"))));

    return jws.getCompactSerialization();
}
 
Example #29
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 #30
Source File: Token.java    From server_face_recognition with GNU General Public License v3.0 5 votes vote down vote up
public static Token decypherToken(String token) {
    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setRequireExpirationTime()
            .setAllowedClockSkewInSeconds(30)
            .setRequireSubject()
            .setExpectedIssuer("Sanstorik")
            .setExpectedAudience("User")
            .setVerificationKey(key.getKey())
            .setJwsAlgorithmConstraints(
                    new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST,
                            AlgorithmIdentifiers.RSA_USING_SHA256))
            .build();

    Token decypheredToken = null;
    try
    {
        JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
        decypheredToken = new Token(token,
             jwtClaims.getClaimValue(USERNAME_KEY).toString(),
             jwtClaims.getClaimValue(PASSWORD_KEY).toString(),
             Integer.valueOf(jwtClaims.getClaimValue(USERID_KEY).toString())
        );
    } catch (InvalidJwtException e) {
        e.printStackTrace();
    }

    return decypheredToken;
}