Search in sources :

Example 6 with Builder

use of org.springframework.security.oauth2.client.registration.ClientRegistration.Builder in project spring-security by spring-projects.

the class JwtAuthenticationTokenTests method getNameWhenJwtHasNoSubjectThenReturnsNull.

@Test
public void getNameWhenJwtHasNoSubjectThenReturnsNull() {
    Jwt jwt = builder().claim("claim", "value").build();
    JwtAuthenticationToken token = new JwtAuthenticationToken(jwt);
    assertThat(token.getName()).isNull();
}
Also used : Jwt(org.springframework.security.oauth2.jwt.Jwt) Test(org.junit.jupiter.api.Test)

Example 7 with Builder

use of org.springframework.security.oauth2.client.registration.ClientRegistration.Builder in project spring-security by spring-projects.

the class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager method createAuthorizationContext.

private Mono<OAuth2AuthorizationContext> createAuthorizationContext(OAuth2AuthorizeRequest authorizeRequest) {
    String clientRegistrationId = authorizeRequest.getClientRegistrationId();
    Authentication principal = authorizeRequest.getPrincipal();
    return Mono.justOrEmpty(authorizeRequest.getAuthorizedClient()).map(OAuth2AuthorizationContext::withAuthorizedClient).switchIfEmpty(Mono.defer(() -> this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId).flatMap((clientRegistration) -> this.authorizedClientService.loadAuthorizedClient(clientRegistrationId, principal.getName()).map(OAuth2AuthorizationContext::withAuthorizedClient).switchIfEmpty(Mono.fromSupplier(() -> OAuth2AuthorizationContext.withClientRegistration(clientRegistration)))).switchIfEmpty(Mono.error(() -> new IllegalArgumentException("Could not find ClientRegistration with id '" + clientRegistrationId + "'"))))).flatMap((contextBuilder) -> this.contextAttributesMapper.apply(authorizeRequest).defaultIfEmpty(Collections.emptyMap()).map((contextAttributes) -> {
        OAuth2AuthorizationContext.Builder builder = contextBuilder.principal(principal);
        if (!contextAttributes.isEmpty()) {
            builder = builder.attributes((attributes) -> attributes.putAll(contextAttributes));
        }
        return builder.build();
    }));
}
Also used : DefaultReactiveOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) Map(java.util.Map) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) Mono(reactor.core.publisher.Mono) Authentication(org.springframework.security.core.Authentication) Collections(java.util.Collections) Function(java.util.function.Function) Assert(org.springframework.util.Assert) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Authentication(org.springframework.security.core.Authentication)

Example 8 with Builder

use of org.springframework.security.oauth2.client.registration.ClientRegistration.Builder in project midpoint by Evolveum.

the class OidcClientModuleWebSecurityConfiguration method buildInternal.

private static OidcClientModuleWebSecurityConfiguration buildInternal(OidcAuthenticationModuleType modelType, String prefixOfSequence, String publicHttpUrlPattern, ServletRequest request) {
    OidcClientModuleWebSecurityConfiguration configuration = new OidcClientModuleWebSecurityConfiguration();
    build(configuration, modelType, prefixOfSequence);
    List<OidcClientAuthenticationModuleType> clients = modelType.getClient();
    List<ClientRegistration> registrations = new ArrayList<>();
    clients.forEach(client -> {
        OidcOpenIdProviderType openIdProvider = client.getOpenIdProvider();
        Assert.notNull(openIdProvider, "openIdProvider cannot be null");
        ClientRegistration.Builder builder = null;
        try {
            builder = ClientRegistrations.fromOidcIssuerLocation(openIdProvider.getIssuerUri());
        } catch (Exception e) {
            LOGGER.debug("Couldn't create oidc client builder by issuer uri.");
        }
        Assert.hasText(client.getRegistrationId(), "registrationId cannot be empty");
        if (builder == null) {
            builder = ClientRegistration.withRegistrationId(client.getRegistrationId());
        } else {
            builder.registrationId(client.getRegistrationId());
        }
        builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE);
        builder.userInfoAuthenticationMethod(AuthenticationMethod.HEADER);
        UriComponentsBuilder redirectUri = UriComponentsBuilder.fromUriString(StringUtils.isNotBlank(publicHttpUrlPattern) ? publicHttpUrlPattern : getBasePath((HttpServletRequest) request));
        redirectUri.pathSegment(DEFAULT_PREFIX_OF_MODULE, AuthUtil.stripSlashes(prefixOfSequence), AuthUtil.stripSlashes(modelType.getName()), AuthUtil.stripSlashes(RemoteModuleAuthenticationImpl.AUTHENTICATION_REQUEST_PROCESSING_URL_SUFFIX), client.getRegistrationId());
        builder.redirectUri(redirectUri.toUriString());
        Assert.hasText(client.getClientId(), "clientId cannot be empty");
        builder.clientId(client.getClientId());
        if (client.getNameOfUsernameAttribute() != null) {
            builder.userNameAttributeName(client.getNameOfUsernameAttribute());
        }
        if (!Objects.isNull(client.getClientSecret())) {
            try {
                String clientSecret = protector.decryptString(client.getClientSecret());
                builder.clientSecret(clientSecret);
            } catch (EncryptionException e) {
                LOGGER.error("Couldn't obtain clear string for client secret");
            }
        }
        getOptionalIfNotEmpty(client.getClientName()).ifPresent(builder::clientName);
        getOptionalIfNotEmpty(openIdProvider.getAuthorizationUri()).ifPresent(builder::authorizationUri);
        getOptionalIfNotEmpty(openIdProvider.getTokenUri()).ifPresent(builder::tokenUri);
        getOptionalIfNotEmpty(openIdProvider.getUserInfoUri()).ifPresent(builder::userInfoUri);
        getOptionalIfNotEmpty(openIdProvider.getIssuerUri()).ifPresent(builder::issuerUri);
        ClientRegistration clientRegistration = builder.build();
        if (clientRegistration.getScopes() == null || !clientRegistration.getScopes().contains("openid")) {
            List<String> scopes = new ArrayList<>();
            if (clientRegistration.getScopes() != null) {
                scopes.addAll(clientRegistration.getScopes());
            }
            scopes.add("openid");
            builder.scope(scopes);
        }
        if (StringUtils.isNotEmpty(openIdProvider.getEndSessionUri())) {
            Map<String, Object> configurationMetadata = new HashMap<>(clientRegistration.getProviderDetails().getConfigurationMetadata());
            configurationMetadata.remove("end_session_endpoint");
            configurationMetadata.put("end_session_endpoint", openIdProvider.getEndSessionUri());
            builder.providerConfigurationMetadata(configurationMetadata);
        }
        if (client.getClientAuthenticationMethod() != null) {
            builder.clientAuthenticationMethod(new ClientAuthenticationMethod(client.getClientAuthenticationMethod().name().toLowerCase()));
        }
        clientRegistration = builder.build();
        Assert.hasText(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri(), "UserInfoUri cannot be empty");
        registrations.add(clientRegistration);
        OidcAdditionalConfiguration.Builder additionalConfBuilder = OidcAdditionalConfiguration.builder().singingAlg(client.getClientSigningAlgorithm());
        if (client.getSimpleProofKey() != null) {
            initializeProofKey(client.getSimpleProofKey(), additionalConfBuilder);
        } else if (client.getKeyStoreProofKey() != null) {
            initializeProofKey(client.getKeyStoreProofKey(), additionalConfBuilder);
        }
        configuration.additionalConfiguration.put(client.getRegistrationId(), additionalConfBuilder.build());
    });
    configuration.clientRegistrationRepository = new InMemoryClientRegistrationRepository(registrations);
    return configuration;
}
Also used : InMemoryClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) Base64Exception(org.apache.cxf.common.util.Base64Exception) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException)

Example 9 with Builder

use of org.springframework.security.oauth2.client.registration.ClientRegistration.Builder in project midpoint by Evolveum.

the class OidcResourceServerModuleWebSecurityConfiguration method buildInternal.

private static OidcResourceServerModuleWebSecurityConfiguration buildInternal(OidcAuthenticationModuleType modelType, String prefixOfSequence) {
    OidcResourceServerModuleWebSecurityConfiguration configuration = new OidcResourceServerModuleWebSecurityConfiguration();
    build(configuration, modelType, prefixOfSequence);
    OidcResourceServerAuthenticationModuleType resourceServer = modelType.getResourceServer();
    if (resourceServer.getTrustingAsymmetricCertificate() != null || resourceServer.getKeyStoreTrustingAsymmetricKey() != null) {
        NimbusJwtDecoder.PublicKeyJwtDecoderBuilder builder;
        if (resourceServer.getKeyStoreTrustingAsymmetricKey() != null) {
            builder = initializePublicKeyDecoderFromKeyStore(resourceServer.getKeyStoreTrustingAsymmetricKey());
        } else {
            builder = initializePublicKeyDecoderFromCertificate(resourceServer.getTrustingAsymmetricCertificate());
        }
        if (resourceServer.getTrustedAlgorithm() != null) {
            builder.signatureAlgorithm(SignatureAlgorithm.from(resourceServer.getTrustedAlgorithm()));
        }
        configuration.decoder = builder.build();
    } else if (resourceServer.getSingleSymmetricKey() != null) {
        try {
            byte[] key;
            String clearValue = protector.decryptString(resourceServer.getSingleSymmetricKey());
            if (Base64.isBase64(clearValue)) {
                boolean isBase64Url = clearValue.contains("-") || clearValue.contains("_");
                key = Base64Utility.decode(clearValue, isBase64Url);
            } else {
                key = protector.decryptString(resourceServer.getSingleSymmetricKey()).getBytes();
            }
            String algorithm = MacAlgorithm.HS256.getName();
            if (resourceServer.getTrustedAlgorithm() != null) {
                algorithm = resourceServer.getTrustedAlgorithm();
            }
            NimbusJwtDecoder.SecretKeyJwtDecoderBuilder builder = NimbusJwtDecoder.withSecretKey(new SecretKeySpec(key, algorithm));
            builder.macAlgorithm(MacAlgorithm.from(algorithm));
            configuration.decoder = builder.build();
        } catch (EncryptionException e) {
            throw new OAuth2AuthenticationException(new OAuth2Error("missing_key"), "Unable get single symmetric key", e);
        } catch (Base64Exception e) {
            e.printStackTrace();
        }
    } else if (resourceServer.getJwkSetUri() != null) {
        if (resourceServer.getTrustedAlgorithm() != null) {
            configuration.decoder = NimbusJwtDecoder.withJwkSetUri(resourceServer.getJwkSetUri()).jwsAlgorithm(SignatureAlgorithm.from(resourceServer.getTrustedAlgorithm())).build();
        } else {
            try {
                JWSKeySelector<SecurityContext> jwsKeySelector = JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(new URL(resourceServer.getJwkSetUri()));
                DefaultJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
                jwtProcessor.setJWSKeySelector(jwsKeySelector);
                configuration.decoder = new NimbusJwtDecoder(jwtProcessor);
            } catch (KeySourceException | MalformedURLException e) {
                e.printStackTrace();
            }
        }
    } else if (resourceServer.getIssuerUri() != null) {
        configuration.decoder = JwtDecoders.fromIssuerLocation(resourceServer.getIssuerUri());
    }
    return configuration;
}
Also used : MalformedURLException(java.net.MalformedURLException) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) URL(java.net.URL) DefaultJWTProcessor(com.nimbusds.jwt.proc.DefaultJWTProcessor) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Base64Exception(org.apache.cxf.common.util.Base64Exception) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) SecurityContext(com.nimbusds.jose.proc.SecurityContext) KeySourceException(com.nimbusds.jose.KeySourceException)

Example 10 with Builder

use of org.springframework.security.oauth2.client.registration.ClientRegistration.Builder in project thingsboard by thingsboard.

the class CustomOAuth2AuthorizationRequestResolver method resolve.

@SuppressWarnings("deprecation")
private OAuth2AuthorizationRequest resolve(HttpServletRequest request, String registrationId, String redirectUriAction, String appPackage, String appToken) {
    if (registrationId == null) {
        return null;
    }
    ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
    if (clientRegistration == null) {
        throw new IllegalArgumentException("Invalid Client Registration with Id: " + registrationId);
    }
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId());
    if (!StringUtils.isEmpty(appPackage)) {
        if (StringUtils.isEmpty(appToken)) {
            throw new IllegalArgumentException("Invalid application token.");
        } else {
            String appSecret = this.oAuth2Service.findAppSecret(UUID.fromString(registrationId), appPackage);
            if (StringUtils.isEmpty(appSecret)) {
                throw new IllegalArgumentException("Invalid package: " + appPackage + ". No application secret found for Client Registration with given application package.");
            }
            String callbackUrlScheme = this.oAuth2AppTokenFactory.validateTokenAndGetCallbackUrlScheme(appPackage, appToken, appSecret);
            attributes.put(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME, callbackUrlScheme);
        }
    }
    OAuth2AuthorizationRequest.Builder builder;
    if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(clientRegistration.getAuthorizationGrantType())) {
        builder = OAuth2AuthorizationRequest.authorizationCode();
        Map<String, Object> additionalParameters = new HashMap<>();
        if (!CollectionUtils.isEmpty(clientRegistration.getScopes()) && clientRegistration.getScopes().contains(OidcScopes.OPENID)) {
            // Section 3.1.2.1 Authentication Request - https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
            // scope
            // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
            addNonceParameters(attributes, additionalParameters);
        }
        if (ClientAuthenticationMethod.NONE.equals(clientRegistration.getClientAuthenticationMethod())) {
            addPkceParameters(attributes, additionalParameters);
        }
        builder.additionalParameters(additionalParameters);
    } else if (AuthorizationGrantType.IMPLICIT.equals(clientRegistration.getAuthorizationGrantType())) {
        builder = OAuth2AuthorizationRequest.implicit();
    } else {
        throw new IllegalArgumentException("Invalid Authorization Grant Type (" + clientRegistration.getAuthorizationGrantType().getValue() + ") for Client Registration with Id: " + clientRegistration.getRegistrationId());
    }
    String redirectUriStr = expandRedirectUri(request, clientRegistration, redirectUriAction);
    return builder.clientId(clientRegistration.getClientId()).authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri()).redirectUri(redirectUriStr).scopes(clientRegistration.getScopes()).state(this.stateGenerator.generateKey()).attributes(attributes).build();
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) HashMap(java.util.HashMap) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Aggregations

Test (org.junit.jupiter.api.Test)9 Jwt (org.springframework.security.oauth2.jwt.Jwt)8 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)5 Authentication (org.springframework.security.core.Authentication)3 Builder (org.springframework.security.oauth2.client.registration.ClientRegistration.Builder)3 ClientRegistrationException (org.springframework.security.oauth2.provider.ClientRegistrationException)3 EncryptionException (com.evolveum.midpoint.prism.crypto.EncryptionException)2 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)2 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)2 HashMap (java.util.HashMap)2 Base64Exception (org.apache.cxf.common.util.Base64Exception)2 CommonOAuth2Provider (org.springframework.security.config.oauth2.client.CommonOAuth2Provider)2 AuthenticationException (org.springframework.security.core.AuthenticationException)2 OAuth2AuthorizeRequest (org.springframework.security.oauth2.client.OAuth2AuthorizeRequest)2 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)2 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)2 DefaultExceptionMessageBuilder (com.epam.ta.reportportal.commons.exception.message.DefaultExceptionMessageBuilder)1 DefaultErrorResolver (com.epam.ta.reportportal.commons.exception.rest.DefaultErrorResolver)1 ReportPortalExceptionResolver (com.epam.ta.reportportal.commons.exception.rest.ReportPortalExceptionResolver)1