Example usage for org.springframework.security.jwt.crypto.sign RsaSigner RsaSigner

List of usage examples for org.springframework.security.jwt.crypto.sign RsaSigner RsaSigner

Introduction

In this page you can find the example usage for org.springframework.security.jwt.crypto.sign RsaSigner RsaSigner.

Prototype

public RsaSigner(String sshKey) 

Source Link

Usage

From source file:org.cloudfoundry.identity.uaa.oauth.JwtTokenEnhancer.java

/**
 * The key used for verifying signatures produced by this class. This is not used but is returned from the endpoint
 * to allow resource servers to obtain the key.
 * //from w ww.jav  a 2 s  . c  om
 * For an HMAC key it will be the same value as the signing key and does not need to be set. For and RSA key, it
 * should be set to the String representation of the public key, in a standard format (e.g. OpenSSH keys)
 * 
 * @param key the signature verification key (typically an RSA public key)
 */
public void setVerifierKey(String key) {
    this.verifierKey = key;
    try {
        new RsaSigner(verifierKey);
        throw new IllegalArgumentException("Private key cannot be set as verifierKey property");
    } catch (Exception expected) {
        // Expected
    }
}

From source file:com.ge.predix.uaa.token.lib.TestTokenUtil.java

public TestTokenUtil() {

    this.signer = new RsaSigner(TOKEN_SIGNING_KEY);
}

From source file:org.cloudfoundry.identity.uaa.oauth.JwtTokenEnhancer.java

/**
 * Sets the JWT signing key. It can be either a simple MAC key or an RSA key. RSA keys should be in OpenSSH format,
 * as produced by <tt>ssh-keygen</tt>.
 * /*  w w w . j  a  v a2 s  . c  o m*/
 * @param key the key to be used for signing JWTs.
 */
public void setSigningKey(String key) {
    Assert.hasText(key);
    key = key.trim();

    this.signingKey = key;

    if (key.startsWith("-----BEGIN")) {
        signer = new RsaSigner(key);
        logger.info("Configured with RSA signing key");
    } else {
        // Assume it's an HMAC key
        verifierKey = key;
        signer = new MacSigner(key);
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.SignerProvider.java

/**
 * Sets the JWT signing key and corresponding key for verifying siugnatures produced by this class.
 *
 * The signing key can be either a simple MAC key or an RSA
 * key. RSA keys should be in OpenSSH format,
 * as produced by <tt>ssh-keygen</tt>.
 *
 * @param signingKey the key to be used for signing JWTs.
 *//* w w  w. j a  va  2 s. com*/
public void setSigningKey(String signingKey) {
    Assert.hasText(signingKey);
    signingKey = signingKey.trim();

    this.signingKey = signingKey;

    if (isAssymetricKey(signingKey)) {
        KeyPair keyPair = parseKeyPair(signingKey);
        signer = new RsaSigner(signingKey);

        pemEncodePublicKey(keyPair);

        logger.debug("Configured with RSA signing key");
        try {
            verifier = new RsaVerifier(verifierKey);
        } catch (Exception e) {
            throw new RuntimeException("Unable to create an RSA verifier from verifierKey", e);
        }

        byte[] test = "test".getBytes();
        try {
            verifier.verify(test, signer.sign(test));
            logger.debug("Signing and verification RSA keys match");
        } catch (InvalidSignatureException e) {
            throw new RuntimeException("Signing and verification RSA keys do not match", e);
        }
        type = "RSA";
    } else {
        // Assume it's an HMAC key
        this.verifierKey = signingKey;
        MacSigner macSigner = new MacSigner(signingKey);
        signer = macSigner;
        verifier = macSigner;

        Assert.state(this.verifierKey == null || this.signingKey == this.verifierKey,
                "For MAC signing you do not need to specify the verifier key separately, and if you do it must match the signing key");
        type = "MAC";
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.token.SignerProvider.java

/**
 * Sets the JWT signing key. It can be either a simple MAC key or an RSA
 * key. RSA keys should be in OpenSSH format,
 * as produced by <tt>ssh-keygen</tt>.
 * /*from   w  w  w.  ja  v a 2s  . co m*/
 * @param key the key to be used for signing JWTs.
 */
public void setSigningKey(String key) {
    Assert.hasText(key);
    key = key.trim();

    this.signingKey = key;

    if (isAssymetricKey(key)) {
        signer = new RsaSigner(key);
        logger.debug("Configured with RSA signing key");
    } else {
        // Assume it's an HMAC key
        this.verifierKey = key;
        signer = new MacSigner(key);
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.token.SignerProvider.java

/**
 * The key used for verifying signatures produced by this class. This is not
 * used but is returned from the endpoint
 * to allow resource servers to obtain the key.
 * //  w  w  w . jav  a2s  . c o  m
 * For an HMAC key it will be the same value as the signing key and does not
 * need to be set. For and RSA key, it
 * should be set to the String representation of the public key, in a
 * standard format (e.g. OpenSSH keys)
 * 
 * @param verifierKey the signature verification key (typically an RSA
 *            public key)
 */
public void setVerifierKey(String verifierKey) {
    boolean valid = false;
    try {
        new RsaSigner(verifierKey);
    } catch (Exception expected) {
        // Expected
        valid = true;
    }
    if (!valid) {
        throw new IllegalArgumentException("Private key cannot be set as verifierKey property");
    }
    this.verifierKey = verifierKey;
}

From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManagerIT.java

@BeforeEach
public void setUp() throws Exception {
    RestTemplateConfig restTemplateConfig = new RestTemplateConfig();
    RestTemplate nonTrustingRestTemplate = restTemplateConfig.nonTrustingRestTemplate();
    RestTemplate trustingRestTemplate = restTemplateConfig.trustingRestTemplate();
    SecurityContextHolder.clearContext();
    IdentityZoneHolder.clear();//from   w w  w.j  a  va 2  s .c  o  m
    String keyName = "testKey";
    header = map(entry("alg", "HS256"), entry("kid", keyName), entry("typ", "JWT"));
    signer = new RsaSigner(PRIVATE_KEY);
    IdentityZoneHolder.get().getConfig().getTokenPolicy()
            .setKeys(Collections.singletonMap(keyName, PRIVATE_KEY));

    provisioning = mock(IdentityProviderProvisioning.class);
    ScimGroupExternalMembershipManager externalMembershipManager = mock(
            ScimGroupExternalMembershipManager.class);

    for (String scope : SCOPES_LIST) {
        ScimGroupExternalMember member = new ScimGroupExternalMember();
        member.setDisplayName(scope);
        when(externalMembershipManager.getExternalGroupMapsByExternalGroup(eq(scope), anyString(), anyString()))
                .thenReturn(Collections.singletonList(member));
    }

    userDatabase = new InMemoryUaaUserDatabase(Collections.emptySet());
    publisher = mock(ApplicationEventPublisher.class);
    tokenEndpointBuilder = mock(TokenEndpointBuilder.class);
    when(tokenEndpointBuilder.getTokenEndpoint()).thenReturn(UAA_ISSUER_URL);
    OidcMetadataFetcher oidcMetadataFetcher = new OidcMetadataFetcher(
            new ExpiringUrlCache(Duration.ofMinutes(2), new TimeServiceImpl(), 10), trustingRestTemplate,
            nonTrustingRestTemplate);
    xoAuthProviderConfigurator = spy(new XOAuthProviderConfigurator(provisioning, oidcMetadataFetcher));
    xoAuthAuthenticationManager = spy(
            new XOAuthAuthenticationManager(xoAuthProviderConfigurator, trustingRestTemplate,
                    nonTrustingRestTemplate, tokenEndpointBuilder, new KeyInfoService(UAA_ISSUER_URL)));
    xoAuthAuthenticationManager.setUserDatabase(userDatabase);
    xoAuthAuthenticationManager.setExternalMembershipManager(externalMembershipManager);
    xoAuthAuthenticationManager.setApplicationEventPublisher(publisher);
    xoAuthAuthenticationManager.setTokenEndpointBuilder(tokenEndpointBuilder);
    xCodeToken = new XOAuthCodeToken(CODE, ORIGIN, "http://localhost/callback/the_origin");
    claims = map(entry("sub", "12345"), entry("preferred_username", "marissa"), entry("origin", UAA_ORIGIN),
            entry("iss", "http://localhost/oauth/token"), entry("given_name", "Marissa"),
            entry("client_id", "client"), entry("aud", Arrays.asList("identity", "another_trusted_client")),
            entry("zid", "uaa"), entry("user_id", "12345"), entry("azp", "client"),
            entry("scope", Collections.singletonList("openid")), entry("auth_time", 1458603913),
            entry("phone_number", "1234567890"), entry("exp", Instant.now().getEpochSecond() + 3600),
            entry("iat", 1458603913), entry("family_name", "Bloggs"),
            entry("jti", "b23fe183-158d-4adc-8aff-65c440bbbee1"), entry("email", "marissa@bloggs.com"),
            entry("rev_sig", "3314dc98"), entry("cid", "client"), entry("email_verified", true),
            entry(ClaimConstants.ACR, JsonUtils.readValue(
                    "{\"values\": [\"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\"] }", Map.class)));

    attributeMappings = new HashMap<>();

    config = new OIDCIdentityProviderDefinition().setAuthUrl(new URL("http://localhost/oauth/authorize"))
            .setTokenUrl(new URL("http://localhost/oauth/token")).setIssuer("http://localhost/oauth/token")
            .setShowLinkText(true).setLinkText("My OIDC Provider").setRelyingPartyId("identity")
            .setRelyingPartySecret("identitysecret").setUserInfoUrl(new URL("http://localhost/userinfo"))
            .setTokenKey(PUBLIC_KEY);
    config.setExternalGroupsWhitelist(Collections.singletonList("*"));

    mockUaaServer = MockRestServiceServer.createServer(nonTrustingRestTemplate);

    invalidRsaSigningKey = "-----BEGIN RSA PRIVATE KEY-----\n"
            + "MIIBOgIBAAJBAJnlBG4lLmUiHslsKDODfd0MqmGZRNUOhn7eO3cKobsFljUKzRQe\n"
            + "GB7LYMjPavnKccm6+jWSXutpzfAc9A9wXG8CAwEAAQJADwwdiseH6cuURw2UQLUy\n"
            + "sVJztmdOG6b375+7IMChX6/cgoF0roCPP0Xr70y1J4TXvFhjcwTgm4RI+AUiIDKw\n"
            + "gQIhAPQHwHzdYG1639Qz/TCHzuai0ItwVC1wlqKpat+CaqdZAiEAoXFyS7249mRu\n"
            + "xtwRAvxKMe+eshHvG2le+ZDrM/pz8QcCIQCzmCDpxGL7L7sbCUgFN23l/11Lwdex\n"
            + "uXKjM9wbsnebwQIgeZIbVovUp74zaQ44xT3EhVwC7ebxXnv3qAkIBMk526sCIDVg\n"
            + "z1jr3KEcaq9zjNJd9sKBkqpkVSqj8Mv+Amq+YjBA\n" + "-----END RSA PRIVATE KEY-----";
}

From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManagerTest.java

@Before
public void setUp() throws Exception {
    rsaSigningKey = "-----BEGIN RSA PRIVATE KEY-----\n"
            + "MIIBOQIBAAJAcjAgsHEfrUxeTFwQPb17AkZ2Im4SfZdpY8Ada9pZfxXz1PZSqv9T\n"
            + "PTMAzNx+EkzMk2IMYN+uNm1bfDzaxVdz+QIDAQABAkBoR39y4rw0/QsY3PKQD5xo\n"
            + "hYSZCMCmJUI/sFCuECevIFY4h6q9KBP+4Set96f7Bgs9wJWVvCMx/nJ6guHAjsIB\n"
            + "AiEAywVOoCGIZ2YzARXWYcMRYZ89hxoHh8kZ+QMthRSZieECIQCP/GWQYgyofAQA\n"
            + "BtM8YwThXEV+S3KtuCn4IAQ89gqdGQIgULBASpZpPyc4OEM0nFBKFTGT46EtwwLj\n"
            + "RrvDmLPSPiECICQi9FqIQSUH+vkGvX0qXM8ymT5ZMS7oSaA8aNPj7EYBAiEAx5V3\n"
            + "2JGEulMY3bK1PVGYmtsXF1gq6zbRMoollMCRSMg=\n" + "-----END RSA PRIVATE KEY-----";
    signer = new RsaSigner(rsaSigningKey);

    provisioning = mock(IdentityProviderProvisioning.class);

    userDatabase = new InMemoryUaaUserDatabase(Collections.emptySet());
    publisher = mock(ApplicationEventPublisher.class);
    RestTemplateFactory restTemplateFactory = mock(RestTemplateFactory.class);
    when(restTemplateFactory.getRestTemplate(anyBoolean())).thenReturn(new RestTemplate());
    xoAuthProviderConfigurator = spy(new XOAuthProviderConfigurator(provisioning,
            new ExpiringUrlCache(10000, new TimeServiceImpl(), 10), restTemplateFactory));
    xoAuthAuthenticationManager = spy(/*from   w  w  w. j  a v  a 2 s .  c  o  m*/
            new XOAuthAuthenticationManager(xoAuthProviderConfigurator, restTemplateFactory));
    xoAuthAuthenticationManager.setUserDatabase(userDatabase);
    xoAuthAuthenticationManager.setApplicationEventPublisher(publisher);
    xCodeToken = new XOAuthCodeToken(CODE, ORIGIN, "http://localhost/callback/the_origin");
    claims = map(entry("sub", "12345"), entry("preferred_username", "marissa"), entry("origin", "uaa"),
            entry("iss", "http://oidc10.identity.cf-app.com/oauth/token"), entry("given_name", "Marissa"),
            entry("client_id", "client"), entry("aud", Arrays.asList("identity", "another_trusted_client")),
            entry("zid", "uaa"), entry("user_id", "12345"), entry("azp", "client"),
            entry("scope", Arrays.asList("openid")), entry("auth_time", 1458603913),
            entry("phone_number", "1234567890"), entry("exp", Instant.now().getEpochSecond() + 3600),
            entry("iat", 1458603913), entry("family_name", "Bloggs"),
            entry("jti", "b23fe183-158d-4adc-8aff-65c440bbbee1"), entry("email", "marissa@bloggs.com"),
            entry("rev_sig", "3314dc98"), entry("cid", "client"), entry(ClaimConstants.ACR, JsonUtils.readValue(
                    "{\"values\": [\"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\"] }", Map.class)));

    attributeMappings = new HashMap<>();

    config = new OIDCIdentityProviderDefinition()
            .setAuthUrl(new URL("http://oidc10.identity.cf-app.com/oauth/authorize"))
            .setTokenUrl(new URL("http://oidc10.identity.cf-app.com/oauth/token"))
            .setIssuer("http://oidc10.identity.cf-app.com/oauth/token").setShowLinkText(true)
            .setLinkText("My OIDC Provider").setRelyingPartyId("identity")
            .setRelyingPartySecret("identitysecret")
            .setUserInfoUrl(new URL("http://oidc10.identity.cf-app.com/userinfo"))
            .setTokenKey("-----BEGIN PUBLIC KEY-----\n"
                    + "MFswDQYJKoZIhvcNAQEBBQADSgAwRwJAcjAgsHEfrUxeTFwQPb17AkZ2Im4SfZdp\n"
                    + "Y8Ada9pZfxXz1PZSqv9TPTMAzNx+EkzMk2IMYN+uNm1bfDzaxVdz+QIDAQAB\n"
                    + "-----END PUBLIC KEY-----");
    config.setExternalGroupsWhitelist(Arrays.asList("*"));

    mockUaaServer = MockRestServiceServer
            .createServer(restTemplateFactory.getRestTemplate(config.isSkipSslValidation()));
    reset(xoAuthAuthenticationManager);

    invalidRsaSigningKey = "-----BEGIN RSA PRIVATE KEY-----\n"
            + "MIIBOgIBAAJBAJnlBG4lLmUiHslsKDODfd0MqmGZRNUOhn7eO3cKobsFljUKzRQe\n"
            + "GB7LYMjPavnKccm6+jWSXutpzfAc9A9wXG8CAwEAAQJADwwdiseH6cuURw2UQLUy\n"
            + "sVJztmdOG6b375+7IMChX6/cgoF0roCPP0Xr70y1J4TXvFhjcwTgm4RI+AUiIDKw\n"
            + "gQIhAPQHwHzdYG1639Qz/TCHzuai0ItwVC1wlqKpat+CaqdZAiEAoXFyS7249mRu\n"
            + "xtwRAvxKMe+eshHvG2le+ZDrM/pz8QcCIQCzmCDpxGL7L7sbCUgFN23l/11Lwdex\n"
            + "uXKjM9wbsnebwQIgeZIbVovUp74zaQ44xT3EhVwC7ebxXnv3qAkIBMk526sCIDVg\n"
            + "z1jr3KEcaq9zjNJd9sKBkqpkVSqj8Mv+Amq+YjBA\n" + "-----END RSA PRIVATE KEY-----";
}