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();
}
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();
}));
}
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;
}
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;
}
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();
}
Aggregations