use of org.springframework.security.oauth2.provider.OAuth2Request in project ORCID-Source by ORCID.
the class OrcidAuthorizationCodeTokenGranter method getOAuth2Authentication.
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> parameters = tokenRequest.getRequestParameters();
String authorizationCode = parameters.get("code");
String redirectUri = parameters.get(OAuth2Utils.REDIRECT_URI);
LOGGER.info("Getting OAuth2 authentication: code={}, redirectUri={}, clientId={}, scope={}", new Object[] { authorizationCode, redirectUri, tokenRequest.getClientId(), tokenRequest.getScope() });
if (authorizationCode == null) {
throw new OAuth2Exception("An authorization code must be supplied.");
}
//Validate the client is active
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(tokenRequest.getClientId());
orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
//Validate scopes
OrcidOauth2AuthoriziationCodeDetail codeDetails = orcidOauth2AuthoriziationCodeDetailDao.find(authorizationCode);
if (codeDetails == null) {
throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
} else {
// Check auth code expiration
Date tokenCreationDate = codeDetails.getDateCreated();
Calendar calendar = Calendar.getInstance();
calendar.setTime(tokenCreationDate);
calendar.add(Calendar.MINUTE, authorizationCodeExpiration);
Date tokenExpirationDate = calendar.getTime();
if (tokenExpirationDate.before(new Date())) {
throw new IllegalArgumentException("Authorization code has expired");
}
// Check granted scopes
Set<String> grantedScopes = codeDetails.getScopes();
Set<String> requestScopes = tokenRequest.getScope();
for (String requestScope : requestScopes) {
if (!grantedScopes.contains(requestScope)) {
throw new InvalidScopeException("Invalid scopes: " + requestScope + " available scopes for this code are: " + grantedScopes);
}
}
}
//Consume code
OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
if (storedAuth == null) {
throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
}
OAuth2Request pendingAuthorizationRequest = storedAuth.getOAuth2Request();
//Regenerate the authorization request but now with the request parameters
pendingAuthorizationRequest = pendingAuthorizationRequest.createOAuth2Request(parameters);
LOGGER.info("Found pending authorization request: redirectUri={}, clientId={}, scope={}, is_approved={}", new Object[] { pendingAuthorizationRequest.getRedirectUri(), pendingAuthorizationRequest.getClientId(), pendingAuthorizationRequest.getScope(), pendingAuthorizationRequest.isApproved() });
// https://jira.springsource.org/browse/SECOAUTH-333
// This might be null, if the authorization was done without the
// redirect_uri parameter
String redirectUriApprovalParameter = pendingAuthorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
if ((redirectUri != null || redirectUriApprovalParameter != null) && !pendingAuthorizationRequest.getRedirectUri().equals(redirectUri)) {
throw new RedirectMismatchException("Redirect URI mismatch.");
}
String pendingClientId = pendingAuthorizationRequest.getClientId();
String clientId = client.getClientId();
LOGGER.info("Comparing client ids: pendingClientId={}, authorizationRequest.clientId={}", pendingClientId, clientId);
if (clientId != null && !clientId.equals(pendingClientId)) {
// just a sanity check.
throw new InvalidClientException("Client ID mismatch");
}
Authentication userAuth = storedAuth.getUserAuthentication();
return new OAuth2Authentication(pendingAuthorizationRequest, userAuth);
}
use of org.springframework.security.oauth2.provider.OAuth2Request in project ORCID-Source by ORCID.
the class OrcidClientCredentialsChecker method validateCredentials.
public OAuth2Request validateCredentials(String grantType, TokenRequest tokenRequest) {
String clientId = tokenRequest.getClientId();
String scopesString = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.SCOPE_PARAM);
Set<String> scopes = new HashSet<String>();
if (!PojoUtil.isEmpty(scopesString)) {
scopes = OAuth2Utils.parseParameterList(scopesString);
}
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
validateGrantType(grantType, clientDetails);
if (scopes != null) {
validateScope(clientDetails, scopes);
}
Map<String, String> authorizationParams = new HashMap<String, String>();
authorizationParams.putAll(tokenRequest.getRequestParameters());
authorizationParams.put(OrcidOauth2Constants.GRANT_TYPE, grantType);
authorizationParams.put(OAuth2Utils.SCOPE, StringUtils.join(scopes, ' '));
authorizationParams.put(OAuth2Utils.CLIENT_ID, clientId);
AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(authorizationParams);
authorizationRequest.setAuthorities(clientDetails.getAuthorities());
authorizationRequest.setResourceIds(clientDetails.getResourceIds());
authorizationRequest.setApproved(true);
return oAuth2RequestFactory.createOAuth2Request(authorizationRequest);
}
use of org.springframework.security.oauth2.provider.OAuth2Request in project ORCID-Source by ORCID.
the class DefaultPermissionChecker method getVisibilitiesForOauth2Authentication.
private Set<Visibility> getVisibilitiesForOauth2Authentication(OAuth2Authentication oAuth2Authentication, OrcidMessage orcidMessage, ScopePathType requiredScope) {
Set<Visibility> visibilities = new HashSet<Visibility>();
visibilities.add(Visibility.PUBLIC);
String orcid = orcidMessage.getOrcidProfile().getOrcidIdentifier().getPath();
// effectively means that the user can only see the public data
try {
checkScopes(oAuth2Authentication, requiredScope);
} catch (AccessControlException e) {
return visibilities;
}
// we can allow for access of protected data
if (!oAuth2Authentication.isClientOnly() && oAuth2Authentication.getPrincipal() != null && ProfileEntity.class.isAssignableFrom(oAuth2Authentication.getPrincipal().getClass())) {
ProfileEntity principal = (ProfileEntity) oAuth2Authentication.getPrincipal();
visibilities.add(Visibility.REGISTERED_ONLY);
if (principal != null && principal.getId().equals(orcid)) {
Set<String> requestedScopes = oAuth2Authentication.getOAuth2Request().getScope();
for (String scope : requestedScopes) {
if (ScopePathType.hasStringScope(scope, requiredScope)) {
visibilities.add(Visibility.LIMITED);
break;
}
}
}
// This is a client credential authenticated client. If the profile
// was created using this client and it
// hasn't been claimed, it's theirs to read
} else if (oAuth2Authentication.isClientOnly()) {
OAuth2Request authorizationRequest = oAuth2Authentication.getOAuth2Request();
String clientId = authorizationRequest.getClientId();
String sponsorOrcid = getSponsorOrcid(orcidMessage);
if (StringUtils.isNotBlank(sponsorOrcid) && clientId.equals(sponsorOrcid) && !orcidMessage.getOrcidProfile().getOrcidHistory().isClaimed()) {
visibilities.add(Visibility.LIMITED);
visibilities.add(Visibility.PRIVATE);
}
}
return visibilities;
}
use of org.springframework.security.oauth2.provider.OAuth2Request in project ORCID-Source by ORCID.
the class DefaultPermissionChecker method performClientChecks.
private void performClientChecks(OAuth2Authentication oAuth2Authentication, ScopePathType requiredScope, OrcidMessage orcidMessage, String orcid) {
OAuth2Request authorizationRequest = oAuth2Authentication.getOAuth2Request();
// as an update
if (orcidMessage != null && orcidMessage.getOrcidProfile() != null && StringUtils.isNotBlank(orcid)) {
OrcidIdentifier orcidOb = orcidMessage.getOrcidProfile().getOrcidIdentifier();
String messageOrcid = orcidOb != null ? orcidOb.getPath() : orcid;
if (StringUtils.isNotBlank(messageOrcid) && !orcid.equals(messageOrcid)) {
throw new IllegalArgumentException("The ORCID in the body and the URI do NOT match. Body ORCID: " + messageOrcid + " URI ORCID: " + orcid + " do NOT match.");
}
profileEntityCacheManager.retrieve(messageOrcid);
if (!profileEntityManager.existsAndNotClaimedAndBelongsTo(messageOrcid, authorizationRequest.getClientId())) {
throw new AccessControlException("You cannot update this profile as it has been claimed, or you are not the owner.");
}
}
}
use of org.springframework.security.oauth2.provider.OAuth2Request in project ORCID-Source by ORCID.
the class OrcidTokenStoreServiceImpl method populatePropertiesFromTokenAndAuthentication.
private OrcidOauth2TokenDetail populatePropertiesFromTokenAndAuthentication(OAuth2AccessToken token, OAuth2Authentication authentication, OrcidOauth2TokenDetail detail) {
OAuth2Request authorizationRequest = authentication.getOAuth2Request();
if (detail == null) {
detail = new OrcidOauth2TokenDetail();
}
String clientId = authorizationRequest.getClientId();
String authKey = authenticationKeyGenerator.extractKey(authentication);
detail.setAuthenticationKey(authKey);
detail.setClientDetailsId(clientId);
OAuth2RefreshToken refreshToken = token.getRefreshToken();
if (refreshToken != null && StringUtils.isNotBlank(refreshToken.getValue())) {
if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
// Override the refresh token expiration from the client
// details, and make it the same as the token itself
detail.setRefreshTokenExpiration(token.getExpiration());
}
detail.setRefreshTokenValue(refreshToken.getValue());
}
if (!authentication.isClientOnly()) {
Object principal = authentication.getPrincipal();
if (principal instanceof ProfileEntity) {
ProfileEntity profileEntity = (ProfileEntity) authentication.getPrincipal();
profileEntity = profileEntityCacheManager.retrieve(profileEntity.getId());
detail.setProfile(profileEntity);
}
}
detail.setTokenValue(token.getValue());
detail.setTokenType(token.getTokenType());
detail.setTokenExpiration(token.getExpiration());
detail.setApproved(authorizationRequest.isApproved());
detail.setRedirectUri(authorizationRequest.getRedirectUri());
Set<String> resourceIds = authorizationRequest.getResourceIds();
if (resourceIds == null || resourceIds.isEmpty()) {
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
resourceIds = clientDetails.getResourceIds();
}
detail.setResourceId(OAuth2Utils.formatParameterList(resourceIds));
detail.setResponseType(OAuth2Utils.formatParameterList(authorizationRequest.getResponseTypes()));
detail.setScope(OAuth2Utils.formatParameterList(authorizationRequest.getScope()));
Map<String, Object> additionalInfo = token.getAdditionalInformation();
if (additionalInfo != null) {
if (additionalInfo.containsKey(OrcidOauth2Constants.TOKEN_VERSION)) {
String sVersion = String.valueOf(additionalInfo.get(OrcidOauth2Constants.TOKEN_VERSION));
detail.setVersion(Long.valueOf(sVersion));
} else {
// TODO: As of Jan 2015 all tokens will be new tokens, so, we
// will have to remove the token version code and
// treat all tokens as new tokens
detail.setVersion(Long.valueOf(OrcidOauth2Constants.PERSISTENT_TOKEN));
}
if (additionalInfo.containsKey(OrcidOauth2Constants.PERSISTENT)) {
boolean isPersistentKey = (Boolean) additionalInfo.get(OrcidOauth2Constants.PERSISTENT);
detail.setPersistent(isPersistentKey);
} else {
detail.setPersistent(false);
}
} else {
detail.setPersistent(false);
}
return detail;
}
Aggregations