use of com.nimbusds.oauth2.sdk.Scope in project iaf by ibissource.
the class OAuthAccessTokenManager method createRequest.
private TokenRequest createRequest(Credentials credentials) throws HttpAuthenticationException {
AuthorizationGrant grant;
if (useClientCredentialsGrant) {
grant = new ClientCredentialsGrant();
} else {
String username = credentials.getUserPrincipal().getName();
Secret password = new Secret(credentials.getPassword());
grant = new ResourceOwnerPasswordCredentialsGrant(username, password);
}
// The credentials to authenticate the client at the token endpoint
ClientID clientID = new ClientID(client_cf.getUsername());
Secret clientSecret = new Secret(client_cf.getPassword());
ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);
try {
URI _tokenEndpoint = new URI(tokenEndpoint);
return new TokenRequest(_tokenEndpoint, clientAuth, grant, scope);
} catch (URISyntaxException e) {
throw new HttpAuthenticationException("illegal token endpoint", e);
}
}
use of com.nimbusds.oauth2.sdk.Scope in project iaf by ibissource.
the class OAuthAccessTokenManagerTest method scopeTest.
@Test
public void scopeTest() {
Scope scope1 = new Scope("read", "write");
Scope scope2 = Scope.parse("read write");
Scope scope3 = Scope.parse("read, write");
assertEquals("read write", scope1.toString());
assertEquals("read write", scope2.toString());
assertEquals("read write", scope3.toString());
}
use of com.nimbusds.oauth2.sdk.Scope in project spring-security by spring-projects.
the class DefaultReactiveOAuth2UserService method loadUser.
@Override
public Mono<OAuth2User> loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
return Mono.defer(() -> {
Assert.notNull(userRequest, "userRequest cannot be null");
String userInfoUri = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri();
if (!StringUtils.hasText(userInfoUri)) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_INFO_URI_ERROR_CODE, "Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
if (!StringUtils.hasText(userNameAttributeName)) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE, "Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
AuthenticationMethod authenticationMethod = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod();
WebClient.RequestHeadersSpec<?> requestHeadersSpec = getRequestHeaderSpec(userRequest, userInfoUri, authenticationMethod);
// @formatter:off
Mono<Map<String, Object>> userAttributes = requestHeadersSpec.retrieve().onStatus(HttpStatus::isError, (response) -> parse(response).map((userInfoErrorResponse) -> {
String description = userInfoErrorResponse.getErrorObject().getDescription();
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, description, null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
})).bodyToMono(DefaultReactiveOAuth2UserService.STRING_OBJECT_MAP);
return userAttributes.map((attrs) -> {
GrantedAuthority authority = new OAuth2UserAuthority(attrs);
Set<GrantedAuthority> authorities = new HashSet<>();
authorities.add(authority);
OAuth2AccessToken token = userRequest.getAccessToken();
for (String scope : token.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope));
}
return new DefaultOAuth2User(authorities, attrs, userNameAttributeName);
}).onErrorMap((ex) -> (ex instanceof UnsupportedMediaTypeException || ex.getCause() instanceof UnsupportedMediaTypeException), (ex) -> {
String contentType = (ex instanceof UnsupportedMediaTypeException) ? ((UnsupportedMediaTypeException) ex).getContentType().toString() : ((UnsupportedMediaTypeException) ex.getCause()).getContentType().toString();
String errorMessage = "An error occurred while attempting to retrieve the UserInfo Resource from '" + userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri() + "': response contains invalid content type '" + contentType + "'. " + "The UserInfo Response should return a JSON object (content type 'application/json') " + "that contains a collection of name and value pairs of the claims about the authenticated End-User. " + "Please ensure the UserInfo Uri in UserInfoEndpoint for Client Registration '" + userRequest.getClientRegistration().getRegistrationId() + "' conforms to the UserInfo Endpoint, " + "as defined in OpenID Connect 1.0: 'https://openid.net/specs/openid-connect-core-1_0.html#UserInfo'";
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, errorMessage, null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
}).onErrorMap((ex) -> {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, "An error occurred reading the UserInfo response: " + ex.getMessage(), null);
return new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
});
});
// @formatter:on
}
use of com.nimbusds.oauth2.sdk.Scope in project spring-security by spring-projects.
the class NimbusAuthorizationCodeTokenResponseClient method getTokenResponse.
@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizationCodeGrantRequest authorizationGrantRequest) {
ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
// Build the authorization code grant request for the token endpoint
AuthorizationCode authorizationCode = new AuthorizationCode(authorizationGrantRequest.getAuthorizationExchange().getAuthorizationResponse().getCode());
URI redirectUri = toURI(authorizationGrantRequest.getAuthorizationExchange().getAuthorizationRequest().getRedirectUri());
AuthorizationGrant authorizationCodeGrant = new AuthorizationCodeGrant(authorizationCode, redirectUri);
URI tokenUri = toURI(clientRegistration.getProviderDetails().getTokenUri());
// Set the credentials to authenticate the client at the token endpoint
ClientID clientId = new ClientID(clientRegistration.getClientId());
Secret clientSecret = new Secret(clientRegistration.getClientSecret());
boolean isPost = ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod()) || ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod());
ClientAuthentication clientAuthentication = isPost ? new ClientSecretPost(clientId, clientSecret) : new ClientSecretBasic(clientId, clientSecret);
com.nimbusds.oauth2.sdk.TokenResponse tokenResponse = getTokenResponse(authorizationCodeGrant, tokenUri, clientAuthentication);
if (!tokenResponse.indicatesSuccess()) {
TokenErrorResponse tokenErrorResponse = (TokenErrorResponse) tokenResponse;
ErrorObject errorObject = tokenErrorResponse.getErrorObject();
throw new OAuth2AuthorizationException(getOAuthError(errorObject));
}
AccessTokenResponse accessTokenResponse = (AccessTokenResponse) tokenResponse;
String accessToken = accessTokenResponse.getTokens().getAccessToken().getValue();
OAuth2AccessToken.TokenType accessTokenType = null;
if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(accessTokenResponse.getTokens().getAccessToken().getType().getValue())) {
accessTokenType = OAuth2AccessToken.TokenType.BEARER;
}
long expiresIn = accessTokenResponse.getTokens().getAccessToken().getLifetime();
// As per spec, in section 5.1 Successful Access Token Response
// https://tools.ietf.org/html/rfc6749#section-5.1
// If AccessTokenResponse.scope is empty, then default to the scope
// originally requested by the client in the Authorization Request
Set<String> scopes = getScopes(authorizationGrantRequest, accessTokenResponse);
String refreshToken = null;
if (accessTokenResponse.getTokens().getRefreshToken() != null) {
refreshToken = accessTokenResponse.getTokens().getRefreshToken().getValue();
}
Map<String, Object> additionalParameters = new LinkedHashMap<>(accessTokenResponse.getCustomParameters());
// @formatter:off
return OAuth2AccessTokenResponse.withToken(accessToken).tokenType(accessTokenType).expiresIn(expiresIn).scopes(scopes).refreshToken(refreshToken).additionalParameters(additionalParameters).build();
// @formatter:on
}
use of com.nimbusds.oauth2.sdk.Scope in project spring-security by spring-projects.
the class NimbusReactiveOpaqueTokenIntrospector method convertClaimsSet.
private OAuth2AuthenticatedPrincipal convertClaimsSet(TokenIntrospectionSuccessResponse response) {
Map<String, Object> claims = response.toJSONObject();
Collection<GrantedAuthority> authorities = new ArrayList<>();
if (response.getAudience() != null) {
List<String> audiences = new ArrayList<>();
for (Audience audience : response.getAudience()) {
audiences.add(audience.getValue());
}
claims.put(OAuth2TokenIntrospectionClaimNames.AUD, Collections.unmodifiableList(audiences));
}
if (response.getClientID() != null) {
claims.put(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, response.getClientID().getValue());
}
if (response.getExpirationTime() != null) {
Instant exp = response.getExpirationTime().toInstant();
claims.put(OAuth2TokenIntrospectionClaimNames.EXP, exp);
}
if (response.getIssueTime() != null) {
Instant iat = response.getIssueTime().toInstant();
claims.put(OAuth2TokenIntrospectionClaimNames.IAT, iat);
}
if (response.getIssuer() != null) {
// RFC-7662 page 7 directs users to RFC-7519 for defining the values of these
// issuer fields.
// https://datatracker.ietf.org/doc/html/rfc7662#page-7
//
// RFC-7519 page 9 defines issuer fields as being 'case-sensitive' strings
// containing
// a 'StringOrURI', which is defined on page 5 as being any string, but
// strings containing ':'
// should be treated as valid URIs.
// https://datatracker.ietf.org/doc/html/rfc7519#section-2
//
// It is not defined however as to whether-or-not normalized URIs should be
// treated as the same literal
// value. It only defines validation itself, so to avoid potential ambiguity
// or unwanted side effects that
// may be awkward to debug, we do not want to manipulate this value. Previous
// versions of Spring Security
// would *only* allow valid URLs, which is not what we wish to achieve here.
claims.put(OAuth2TokenIntrospectionClaimNames.ISS, response.getIssuer().getValue());
}
if (response.getNotBeforeTime() != null) {
claims.put(OAuth2TokenIntrospectionClaimNames.NBF, response.getNotBeforeTime().toInstant());
}
if (response.getScope() != null) {
List<String> scopes = Collections.unmodifiableList(response.getScope().toStringList());
claims.put(OAuth2TokenIntrospectionClaimNames.SCOPE, scopes);
for (String scope : scopes) {
authorities.add(new SimpleGrantedAuthority(AUTHORITY_PREFIX + scope));
}
}
return new OAuth2IntrospectionAuthenticatedPrincipal(claims, authorities);
}
Aggregations