Search in sources :

Example 1 with Jwt

use of org.springframework.security.oauth2.jwt.Jwt in project spring-security-oauth by spring-projects.

the class JwkTokenStoreITest method readAccessTokenWhenJwtHasInvalidIssuerClaimThenVerificationFails.

// gh-1114 Issuer claim verification
@Test(expected = InvalidTokenException.class)
public void readAccessTokenWhenJwtHasInvalidIssuerClaimThenVerificationFails() throws Exception {
    String issuer = "http://localhost:8180/auth/realms/Demo-2";
    this.setUpResponses(issuer);
    ProviderDiscoveryClient discoveryClient = new ProviderDiscoveryClient(this.server.url("").toString());
    ProviderConfiguration providerConfiguration = discoveryClient.discover();
    List<JwtClaimsSetVerifier> jwtClaimsSetVerifiers = new ArrayList<JwtClaimsSetVerifier>();
    jwtClaimsSetVerifiers.add(new IssuerClaimVerifier(providerConfiguration.getIssuer()));
    JwkTokenStore jwkTokenStore = new JwkTokenStore(providerConfiguration.getJwkSetUri().toString(), new DelegatingJwtClaimsSetVerifier(jwtClaimsSetVerifiers));
    // NOTE: The 'iss' claim in this JWT is http://localhost:8180/auth/realms/Demo
    String jwt = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJfQ2kzLVZmVl9OMFlBRzIyTlFPZ09VcEZCRERjRGVfckp4cHU1Sks3MDJvIn0.eyJqdGkiOiIzOWQxMmU1NC00MjliLTRkZjUtOTM2OS01YWVlOTFkNzAwZjgiLCJleHAiOjE0ODg5MDk1NzMsIm5iZiI6MCwiaWF0IjoxNDg4OTA5MjczLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgxODAvYXV0aC9yZWFsbXMvRGVtbyIsImF1ZCI6ImJvb3QtYXBwIiwic3ViIjoiNGM5NjE5NDQtN2VkZC00ZDZiLTg2MGUtYmJiZGNhODk0MDU4IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiYm9vdC1hcHAiLCJhdXRoX3RpbWUiOjE0ODg5MDkyNzMsInNlc3Npb25fc3RhdGUiOiJiMjdjMDZlNi02ODgwLTQxZTEtOTM2MS1jZmEzYzY2ZjYyNjAiLCJhY3IiOiIxIiwiY2xpZW50X3Nlc3Npb24iOiIyYjA5NTFiOC1iMjdkLTRlYWMtYjUxOC1kZTQ5OTA5OTY2ZDgiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZXNvdXJjZV9hY2Nlc3MiOnsiYm9vdC1hcGkiOnsicm9sZXMiOlsiYm9vdC1hcGktcm9sZSJdfSwiYm9vdC1hcHAiOnsicm9sZXMiOlsiYm9vdC1yb2xlIl19fSwibmFtZSI6IkFsaWNlICIsInByZWZlcnJlZF91c2VybmFtZSI6ImFsaWNlIiwiZ2l2ZW5fbmFtZSI6IkFsaWNlIiwiZmFtaWx5X25hbWUiOiIiLCJlbWFpbCI6ImFsaWNlQGV4YW1wbGUubmV0In0.NfF5rPMabu8gaigUHZnX3gIzNGAxKpmPP206U5keNtexNqsmQEFO4KT2i1JYLwvNVFnRWCa8FmYokAtzeHgLvHk2B8CZXqL6GSMGQ26wPS5RIFTak9HjfHMhodqSIdy4wZTKmEcum_uYTaCdrVRSfWU8l94xAY6OzwElZX5ulkucvgWQnpFs0HB7X54kB07OqpN8L3i1jeQoEV0iJchtxZiEOSipqMNO7cujMqB_6lf9i78URPuyExfeLzAWyDbMWSJBp3zUoS7HakwE_4oC3eVEYTxDtMRL2yl2_8R0C0g2Dc0Qb9aezFxo3-SDNuy9aicDmibEEOpIoetlrIYbNA";
    OAuth2AccessToken accessToken = jwkTokenStore.readAccessToken(jwt);
    assertEquals(issuer, accessToken.getAdditionalInformation().get("iss"));
}
Also used : IssuerClaimVerifier(org.springframework.security.oauth2.provider.token.store.IssuerClaimVerifier) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) DelegatingJwtClaimsSetVerifier(org.springframework.security.oauth2.provider.token.store.DelegatingJwtClaimsSetVerifier) ProviderDiscoveryClient(org.springframework.security.oauth2.client.discovery.ProviderDiscoveryClient) JwtClaimsSetVerifier(org.springframework.security.oauth2.provider.token.store.JwtClaimsSetVerifier) DelegatingJwtClaimsSetVerifier(org.springframework.security.oauth2.provider.token.store.DelegatingJwtClaimsSetVerifier) ArrayList(java.util.ArrayList) ProviderConfiguration(org.springframework.security.oauth2.client.discovery.ProviderConfiguration) Test(org.junit.Test)

Example 2 with Jwt

use of org.springframework.security.oauth2.jwt.Jwt in project sw360portal by sw360.

the class Sw360AuthorizationServerConfiguration method jwtAccessTokenConverter.

@Bean
protected JwtAccessTokenConverter jwtAccessTokenConverter() {
    KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt-keystore.jks"), "sw360SecretKey".toCharArray());
    JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
    jwtAccessTokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
    return jwtAccessTokenConverter;
}
Also used : JwtAccessTokenConverter(org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter) ClassPathResource(org.springframework.core.io.ClassPathResource) KeyStoreKeyFactory(org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory) Bean(org.springframework.context.annotation.Bean)

Example 3 with Jwt

use of org.springframework.security.oauth2.jwt.Jwt in project sw360portal by sw360.

the class Sw360AuthorizationServerConfiguration method jwtAccessTokenConverter.

@Bean
protected JwtAccessTokenConverter jwtAccessTokenConverter() {
    KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt-keystore.jks"), "sw360SecretKey".toCharArray());
    JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
    jwtAccessTokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
    return jwtAccessTokenConverter;
}
Also used : JwtAccessTokenConverter(org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter) ClassPathResource(org.springframework.core.io.ClassPathResource) KeyStoreKeyFactory(org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory) Bean(org.springframework.context.annotation.Bean)

Example 4 with Jwt

use of org.springframework.security.oauth2.jwt.Jwt 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 5 with Jwt

use of org.springframework.security.oauth2.jwt.Jwt in project new-cloud by xie-summer.

the class OAuth2JWTAuthorizationConfig method jwtAccessTokenConverter.

/**
 * 使用JWT对称加密
 * @return
 */
// @Bean
// public JwtAccessTokenConverter jwtAccessTokenConverter() {
// JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
// jwtAccessTokenConverter.setSigningKey(CommonConstant.SIGN_KEY);
// return jwtAccessTokenConverter;
// }
/**
 * 使用JWT不对称加密  ,认证中加密,资源服务器验签解密
 * @return
 */
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
    final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("mytest.jks"), "mypass".toCharArray());
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("mytest"));
    converter.setAccessTokenConverter(new CustomerAccessTokenConverter());
    return converter;
}
Also used : CustomerAccessTokenConverter(com.framework.auth.config.support.CustomerAccessTokenConverter) JwtAccessTokenConverter(org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter) ClassPathResource(org.springframework.core.io.ClassPathResource) KeyStoreKeyFactory(org.springframework.security.rsa.crypto.KeyStoreKeyFactory) Bean(org.springframework.context.annotation.Bean)

Aggregations

Test (org.junit.jupiter.api.Test)139 Jwt (org.springframework.security.oauth2.jwt.Jwt)83 GrantedAuthority (org.springframework.security.core.GrantedAuthority)47 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)37 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)36 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)36 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)30 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)29 BeforeEach (org.junit.jupiter.api.BeforeEach)29 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)27 TestClientRegistrations (org.springframework.security.oauth2.client.registration.TestClientRegistrations)24 Instant (java.time.Instant)23 HttpHeaders (org.springframework.http.HttpHeaders)22 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)22 JwtDecoder (org.springframework.security.oauth2.jwt.JwtDecoder)22 Collections (java.util.Collections)21 MediaType (org.springframework.http.MediaType)21 NimbusJwtDecoder (org.springframework.security.oauth2.jwt.NimbusJwtDecoder)21 MockWebServer (okhttp3.mockwebserver.MockWebServer)20 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)20