Search in sources :

Example 1 with MacSigner

use of org.springframework.security.jwt.crypto.sign.MacSigner in project spring-security-oauth by spring-projects.

the class JwtAccessTokenConverter method setSigningKey.

/**
	 * 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>.
	 *
	 * @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 (isPublic(key)) {
        signer = new RsaSigner(key);
        logger.info("Configured with RSA signing key");
    } else {
        // Assume it's a MAC key
        this.verifierKey = key;
        signer = new MacSigner(key);
    }
}
Also used : RsaSigner(org.springframework.security.jwt.crypto.sign.RsaSigner) MacSigner(org.springframework.security.jwt.crypto.sign.MacSigner)

Example 2 with MacSigner

use of org.springframework.security.jwt.crypto.sign.MacSigner in project cloudbreak by hortonworks.

the class CachedRemoteTokenService method getSSOAuthentication.

private OAuth2Authentication getSSOAuthentication(String accessToken) {
    try {
        SignatureVerifier verifier = isAssymetricKey(jwtSignKey) ? new RsaVerifier(jwtSignKey) : new MacSigner(jwtSignKey);
        Jwt jwt = JwtHelper.decodeAndVerify(accessToken, verifier);
        Map<String, Object> claims = objectMapper.readValue(jwt.getClaims(), new MapTypeReference());
        Object userClaim = claims.get("user");
        Map<String, Object> tokenMap = new HashMap<>();
        Map<String, Object> userMap = objectMapper.readValue(userClaim.toString(), new MapTypeReference());
        String exp = claims.get("exp").toString();
        tokenMap.put("exp", Long.valueOf(exp));
        Object email = userMap.get("email");
        tokenMap.put("user_id", email);
        tokenMap.put("user_name", email);
        tokenMap.put("scope", Arrays.asList("cloudbreak.networks.read", "periscope.cluster", "cloudbreak.usages.user", "cloudbreak.recipes", "openid", "cloudbreak.templates.read", "cloudbreak.usages.account", "cloudbreak.events", "cloudbreak.stacks.read", "cloudbreak.blueprints", "cloudbreak.networks", "cloudbreak.templates", "cloudbreak.credentials.read", "cloudbreak.securitygroups.read", "cloudbreak.securitygroups", "cloudbreak.stacks", "cloudbreak.credentials", "cloudbreak.recipes.read", "cloudbreak.blueprints.read"));
        OAuth2AccessToken oAuth2AccessToken = jwtAccessTokenConverter.extractAccessToken(accessToken, tokenMap);
        if (oAuth2AccessToken.isExpired()) {
            throw new InvalidTokenException("The token has expired");
        }
        OAuth2Authentication oAuth2Authentication = jwtAccessTokenConverter.extractAuthentication(tokenMap);
        if (oAuth2Authentication != null) {
            LOGGER.info("JWT token verified for: {}", oAuth2Authentication.getPrincipal());
        }
        return oAuth2Authentication;
    } catch (IOException e) {
        LOGGER.error("Failed to parse the JWT token", e);
        throw new InvalidTokenException("The specified JWT token is invalid", e);
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) HashMap(java.util.HashMap) Jwt(org.springframework.security.jwt.Jwt) IOException(java.io.IOException) RsaVerifier(org.springframework.security.jwt.crypto.sign.RsaVerifier) MacSigner(org.springframework.security.jwt.crypto.sign.MacSigner) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) SignatureVerifier(org.springframework.security.jwt.crypto.sign.SignatureVerifier)

Example 3 with MacSigner

use of org.springframework.security.jwt.crypto.sign.MacSigner in project CzechIdMng by bcvsolutions.

the class JwtAuthenticationMapper method writeToken.

/**
 * Writes authentication dto to token
 *
 * @param dto
 * @return
 * @throws IOException
 */
public String writeToken(IdmJwtAuthenticationDto dto) {
    try {
        Assert.notNull(dto, "Authentication is required to write token");
        // 
        String authenticationJson = mapper.writeValueAsString(dto);
        return JwtHelper.encode(authenticationJson, new MacSigner(getSecret().asString())).getEncoded();
    } catch (IOException ex) {
        throw new CoreException(String.format("Creating JWT token [%s] failed.", dto.getId()), ex);
    }
}
Also used : MacSigner(org.springframework.security.jwt.crypto.sign.MacSigner) CoreException(eu.bcvsolutions.idm.core.api.exception.CoreException) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) IOException(java.io.IOException)

Example 4 with MacSigner

use of org.springframework.security.jwt.crypto.sign.MacSigner in project spring-security-oauth by spring-projects.

the class JwtAccessTokenConverter method afterPropertiesSet.

public void afterPropertiesSet() throws Exception {
    if (verifier != null) {
        // Assume signer also set independently if needed
        return;
    }
    SignatureVerifier verifier = new MacSigner(verifierKey);
    try {
        verifier = new RsaVerifier(verifierKey);
    } catch (Exception e) {
        logger.warn("Unable to create an RSA verifier from verifierKey (ignoreable if using MAC)");
    }
    // Check the signing and verification keys match
    if (signer instanceof RsaSigner) {
        byte[] test = "test".getBytes();
        try {
            verifier.verify(test, signer.sign(test));
            logger.info("Signing and verification RSA keys match");
        } catch (InvalidSignatureException e) {
            logger.error("Signing and verification RSA keys do not match");
        }
    } else if (verifier instanceof MacSigner) {
        // Avoid a race condition where setters are called in the wrong order. Use of
        // == is intentional.
        Assert.state(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");
    }
    this.verifier = verifier;
}
Also used : RsaVerifier(org.springframework.security.jwt.crypto.sign.RsaVerifier) InvalidSignatureException(org.springframework.security.jwt.crypto.sign.InvalidSignatureException) MacSigner(org.springframework.security.jwt.crypto.sign.MacSigner) RsaSigner(org.springframework.security.jwt.crypto.sign.RsaSigner) SignatureVerifier(org.springframework.security.jwt.crypto.sign.SignatureVerifier) InvalidSignatureException(org.springframework.security.jwt.crypto.sign.InvalidSignatureException) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException)

Example 5 with MacSigner

use of org.springframework.security.jwt.crypto.sign.MacSigner in project faf-java-server by FAForever.

the class CustomIceServersProviderTest method getIceServerList.

@Test
@SuppressWarnings("unchecked")
public void getIceServerList() throws Exception {
    String claim = "{\"expiresAt\": \"ff\"}";
    when(objectMapper.writeValueAsString(any())).thenReturn(claim);
    properties.getIce().setServers(Arrays.asList(new Server().setUrl("http://localhost:1234"), new Server().setUrl("http://localhost:2345")));
    IceServerList result = instance.getIceServerList();
    ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass((Class) Map.class);
    verify(objectMapper, times(2)).writeValueAsString(captor.capture());
    Map<String, Object> map = captor.getValue();
    assertThat(map.get("expiresAt"), is(notNullValue()));
    List<IceServer> servers = result.getServers();
    assertThat(servers, hasSize(2));
    assertThat(servers.get(0).getUrl(), is(URI.create("http://localhost:1234")));
    assertThat(servers.get(0).getCredential(), is(notNullValue()));
    assertThat(servers.get(0).getUsername(), is(notNullValue()));
    assertThat(servers.get(1).getUrl(), is(URI.create("http://localhost:2345")));
    assertThat(servers.get(1).getCredential(), is(notNullValue()));
    assertThat(servers.get(1).getUsername(), is(notNullValue()));
    MacSigner macSigner = new MacSigner(properties.getJwt().getSecret());
    Jwt jwt = JwtHelper.decodeAndVerify(servers.get(0).getCredential(), macSigner);
    assertThat(jwt.getClaims(), is(claim));
}
Also used : MacSigner(org.springframework.security.jwt.crypto.sign.MacSigner) Server(com.faforever.server.config.ServerProperties.Ice.Server) Jwt(org.springframework.security.jwt.Jwt) Map(java.util.Map) Test(org.junit.Test)

Aggregations

MacSigner (org.springframework.security.jwt.crypto.sign.MacSigner)6 IOException (java.io.IOException)2 Jwt (org.springframework.security.jwt.Jwt)2 RsaSigner (org.springframework.security.jwt.crypto.sign.RsaSigner)2 RsaVerifier (org.springframework.security.jwt.crypto.sign.RsaVerifier)2 SignatureVerifier (org.springframework.security.jwt.crypto.sign.SignatureVerifier)2 InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)2 Server (com.faforever.server.config.ServerProperties.Ice.Server)1 CoreException (eu.bcvsolutions.idm.core.api.exception.CoreException)1 GuardedString (eu.bcvsolutions.idm.core.security.api.domain.GuardedString)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 ValidationException (javax.validation.ValidationException)1 Test (org.junit.Test)1 InvalidSignatureException (org.springframework.security.jwt.crypto.sign.InvalidSignatureException)1 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)1 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)1