use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project midpoint by Evolveum.
the class OidcResourceServerModuleAuthentication method getRealmFroHeader.
public String getRealmFroHeader(AuthenticationException authException) {
Map<String, String> parameters = new LinkedHashMap<>();
if (authException instanceof OAuth2AuthenticationException) {
OAuth2Error error = ((OAuth2AuthenticationException) authException).getError();
parameters.put("error", error.getErrorCode());
if (org.springframework.util.StringUtils.hasText(error.getDescription())) {
parameters.put("error_description", error.getDescription());
}
if (org.springframework.util.StringUtils.hasText(error.getUri())) {
parameters.put("error_uri", error.getUri());
}
if (error instanceof BearerTokenError) {
BearerTokenError bearerTokenError = (BearerTokenError) error;
if (StringUtils.hasText(bearerTokenError.getScope())) {
parameters.put("scope", bearerTokenError.getScope());
}
}
}
StringBuilder wwwAuthenticate = new StringBuilder(super.getRealmFroHeader(authException));
if (!parameters.isEmpty()) {
parameters.forEach((key, value) -> {
wwwAuthenticate.append(", ");
wwwAuthenticate.append(key).append("=\"").append(value).append("\"");
});
}
return wwwAuthenticate.toString();
}
use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project midpoint by Evolveum.
the class OidcLoginAuthenticationFilter method attemptAuthentication.
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
MultiValueMap<String, String> params = toMultiMap(request.getParameterMap());
if (!isAuthorizationResponse(params)) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_REQUEST_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, "web.security.provider.invalid");
} else {
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository.removeAuthorizationRequest(request, response);
if (authorizationRequest == null) {
OAuth2Error oauth2Error = new OAuth2Error(AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, "web.security.provider.invalid");
} else {
String registrationId = authorizationRequest.getAttribute("registration_id");
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
if (clientRegistration == null) {
OAuth2Error oauth2Error = new OAuth2Error(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE, "Client Registration not found with Id: " + registrationId, null);
throw new OAuth2AuthenticationException(oauth2Error, "web.security.provider.invalid");
} else {
String redirectUri = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)).replaceQuery(null).build().toUriString();
OAuth2AuthorizationResponse authorizationResponse = convert(params, redirectUri);
OAuth2LoginAuthenticationToken authenticationRequest = new OAuth2LoginAuthenticationToken(clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
MidpointAuthentication authenticationResult = (MidpointAuthentication) this.getAuthenticationManager().authenticate(authenticationRequest);
Assert.notNull(authenticationResult, "authentication result cannot be null");
return authenticationResult;
}
}
}
}
use of org.springframework.security.oauth2.core.OAuth2AuthenticationException 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.core.OAuth2AuthenticationException in project jhipster-registry by jhipster.
the class AuthorizationHeaderUtil method refreshTokenClient.
private OAuth2AccessTokenResponse refreshTokenClient(OAuth2AuthorizedClient currentClient) {
MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.REFRESH_TOKEN.getValue());
formParameters.add(OAuth2ParameterNames.REFRESH_TOKEN, currentClient.getRefreshToken().getTokenValue());
formParameters.add(OAuth2ParameterNames.CLIENT_ID, currentClient.getClientRegistration().getClientId());
RequestEntity requestEntity = RequestEntity.post(URI.create(currentClient.getClientRegistration().getProviderDetails().getTokenUri())).contentType(MediaType.APPLICATION_FORM_URLENCODED).body(formParameters);
try {
RestTemplate r = restTemplate(currentClient.getClientRegistration().getClientId(), currentClient.getClientRegistration().getClientSecret());
ResponseEntity<OAuthIdpTokenResponseDTO> responseEntity = r.exchange(requestEntity, OAuthIdpTokenResponseDTO.class);
return toOAuth2AccessTokenResponse(responseEntity.getBody());
} catch (OAuth2AuthorizationException e) {
log.error("Unable to refresh token", e);
throw new OAuth2AuthenticationException(e.getError(), e);
}
}
use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project jhipster-registry by jhipster.
the class UaaAuthorizationHeaderUtil method retrieveNewAccessToken.
private OAuth2AccessToken retrieveNewAccessToken(ClientRegistration clientRegistration) {
MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue());
RequestEntity requestEntity = RequestEntity.post(URI.create(clientRegistration.getProviderDetails().getTokenUri())).contentType(MediaType.APPLICATION_FORM_URLENCODED).body(formParameters);
try {
ResponseEntity<OAuth2AccessTokenResponse> responseEntity = this.uaaRestTemplate.exchange(requestEntity, OAuth2AccessTokenResponse.class);
return Objects.requireNonNull(responseEntity.getBody()).getAccessToken();
} catch (OAuth2AuthorizationException e) {
log.error("Unable to get access token", e);
throw new OAuth2AuthenticationException(e.getError(), e);
}
}
Aggregations