Search in sources :

Example 96 with OAuth2Request

use of org.springframework.security.oauth2.provider.OAuth2Request in project ORCID-Source by ORCID.

the class OrcidAuthorizationCodeServiceImpl method remove.

@Override
protected OAuth2Authentication remove(String code) {
    OrcidOauth2AuthoriziationCodeDetail detail = orcidOauth2AuthoriziationCodeDetailDao.removeAndReturn(code);
    if (detail == null) {
        LOGGER.info("No such authorization code to remove: code={}", new Object[] { code });
        return null;
    }
    OrcidOauth2AuthInfo authInfo = new OrcidOauth2AuthInfo(detail.getClientDetailsEntity().getId(), detail.getScopes(), detail.getProfileEntity().getId());
    LOGGER.info("Removed authorization code: code={}, clientId={}, scopes={}, userOrcid={}", new Object[] { code, authInfo.getClientId(), authInfo.getScopes(), authInfo.getUserOrcid() });
    OAuth2Request oAuth2Request = new OAuth2Request(Collections.<String, String>emptyMap(), authInfo.getClientId(), Collections.<GrantedAuthority>emptyList(), true, authInfo.getScopes(), detail.getResourceIds(), detail.getRedirectUri(), new HashSet<String>(Arrays.asList(detail.getResponseType())), Collections.<String, Serializable>emptyMap());
    Authentication userAuth = getUserAuthentication(detail);
    OAuth2Authentication result = new OAuth2Authentication(oAuth2Request, userAuth);
    return result;
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail) OrcidOauth2UserAuthentication(org.orcid.core.oauth.OrcidOauth2UserAuthentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidOauth2AuthInfo(org.orcid.core.oauth.OrcidOauth2AuthInfo)

Example 97 with OAuth2Request

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);
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail) Calendar(java.util.Calendar) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) Date(java.util.Date) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException)

Example 98 with OAuth2Request

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);
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Example 99 with OAuth2Request

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;
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) AccessControlException(java.security.AccessControlException) Visibility(org.orcid.jaxb.model.message.Visibility) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) HashSet(java.util.HashSet)

Example 100 with OAuth2Request

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.");
        }
    }
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OrcidIdentifier(org.orcid.jaxb.model.message.OrcidIdentifier) AccessControlException(java.security.AccessControlException)

Aggregations

OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)99 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)77 Authentication (org.springframework.security.core.Authentication)57 Test (org.junit.Test)56 HashMap (java.util.HashMap)21 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)15 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)15 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)14 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)13 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)12 Date (java.util.Date)11 HashSet (java.util.HashSet)11 Expression (org.springframework.expression.Expression)10 DBUnitTest (org.orcid.test.DBUnitTest)8 EvaluationContext (org.springframework.expression.EvaluationContext)8 MethodInvocation (org.aopalliance.intercept.MethodInvocation)7 OrcidOAuth2Authentication (org.orcid.core.oauth.OrcidOAuth2Authentication)7 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)7 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)7 SimpleMethodInvocation (org.springframework.security.util.SimpleMethodInvocation)7