Search in sources :

Example 41 with OAuth2Request

use of org.springframework.security.oauth2.provider.OAuth2Request in project spring-security-oauth by spring-projects.

the class ResourceOwnerPasswordTokenGranter method getOAuth2Authentication.

@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
    Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
    String username = parameters.get("username");
    String password = parameters.get("password");
    // Protect from downstream leaks of password
    parameters.remove("password");
    Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
    ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
    try {
        userAuth = authenticationManager.authenticate(userAuth);
    } catch (AccountStatusException ase) {
        //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
        throw new InvalidGrantException(ase.getMessage());
    } catch (BadCredentialsException e) {
        // If the username/password are wrong the spec says we should send 400/invalid grant
        throw new InvalidGrantException(e.getMessage());
    }
    if (userAuth == null || !userAuth.isAuthenticated()) {
        throw new InvalidGrantException("Could not authenticate user: " + username);
    }
    OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
    return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
Also used : AccountStatusException(org.springframework.security.authentication.AccountStatusException) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) 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) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) LinkedHashMap(java.util.LinkedHashMap)

Example 42 with OAuth2Request

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

the class T2OrcidApiServiceDelegatorImpl method addExternalIdentifiers.

/**
     * Add new external identifiers to the profile. As with all calls, if the
     * message contains any other elements, a 400 Bad Request will be returned.
     * 
     * @param orcidMessage
     *            the message congtaining the external ids
     * @return If successful, returns a 200 OK with the updated content.
     */
@Override
@AccessControl(requiredScope = ScopePathType.ORCID_BIO_EXTERNAL_IDENTIFIERS_CREATE)
public Response addExternalIdentifiers(UriInfo uriInfo, String orcid, OrcidMessage orcidMessage) {
    OrcidProfile orcidProfile = orcidMessage.getOrcidProfile();
    try {
        ExternalIdentifiers updatedExternalIdentifiers = orcidProfile.getOrcidBio().getExternalIdentifiers();
        // Get the client profile information
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String clientId = null;
        if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
            OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request();
            clientId = authorizationRequest.getClientId();
        }
        for (ExternalIdentifier ei : updatedExternalIdentifiers.getExternalIdentifier()) {
            // Set the client profile to each external identifier
            if (ei.getSource() == null) {
                Source source = new Source();
                source.setSourceClientId(new SourceClientId(clientId));
                ei.setSource(source);
            } else {
                // Check if the provided external orcid exists
                Source source = ei.getSource();
                String sourceOrcid = source.retrieveSourcePath();
                if (sourceOrcid != null) {
                    if (StringUtils.isBlank(sourceOrcid) || (!profileEntityManager.orcidExists(sourceOrcid) && !clientDetailsManager.exists(sourceOrcid))) {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("orcid", sourceOrcid);
                        throw new OrcidNotFoundException(params);
                    }
                }
            }
        }
        orcidProfile = orcidProfileManager.addExternalIdentifiers(orcidProfile);
        return getOrcidMessageResponse(orcidProfile, orcid);
    } catch (DataAccessException e) {
        throw new OrcidBadRequestException(localeManager.resolveMessage("apiError.badrequest_createorcid.exception"));
    }
}
Also used : ExternalIdentifier(org.orcid.jaxb.model.message.ExternalIdentifier) HashMap(java.util.HashMap) SourceClientId(org.orcid.jaxb.model.message.SourceClientId) Source(org.orcid.jaxb.model.message.Source) OrcidProfile(org.orcid.jaxb.model.message.OrcidProfile) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OrcidBadRequestException(org.orcid.core.exception.OrcidBadRequestException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidNotFoundException(org.orcid.core.exception.OrcidNotFoundException) ExternalIdentifiers(org.orcid.jaxb.model.message.ExternalIdentifiers) DataAccessException(org.springframework.dao.DataAccessException) AccessControl(org.orcid.core.security.visibility.aop.AccessControl)

Example 43 with OAuth2Request

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

the class T2OrcidApiServiceDelegatorImpl method registerWebhook.

/**
     * Register a new webhook to the profile. As with all calls, if the message
     * contains any other elements, a 400 Bad Request will be returned.
     * 
     * @param orcid
     *            the identifier of the profile to add the webhook
     * @param uriInfo
     *            an uri object containing the webhook
     * @return If successful, returns a 2xx.
     * */
@Override
@AccessControl(requiredScope = ScopePathType.WEBHOOK)
public Response registerWebhook(UriInfo uriInfo, String orcid, String webhookUri) {
    @SuppressWarnings("unused") URI validatedWebhookUri = null;
    try {
        validatedWebhookUri = new URI(webhookUri);
    } catch (URISyntaxException e) {
        Object[] params = { webhookUri };
        throw new OrcidBadRequestException(localeManager.resolveMessage("apiError.badrequest_incorrect_webhook.exception", params));
    }
    ProfileEntity profile = profileEntityCacheManager.retrieve(orcid);
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    ClientDetailsEntity clientDetails = null;
    String clientId = null;
    if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
        OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request();
        clientId = authorizationRequest.getClientId();
        clientDetails = clientDetailsManager.findByClientId(clientId);
    }
    if (profile != null && clientDetails != null) {
        WebhookEntityPk webhookPk = new WebhookEntityPk(profile, webhookUri);
        WebhookEntity webhook = webhookManager.find(webhookPk);
        boolean isNew = webhook == null;
        if (isNew) {
            webhook = new WebhookEntity();
            webhook.setProfile(profile);
            webhook.setDateCreated(new Date());
            webhook.setEnabled(true);
            webhook.setUri(webhookUri);
            webhook.setClientDetails(clientDetails);
        }
        webhookManager.update(webhook);
        return isNew ? Response.created(uriInfo.getAbsolutePath()).build() : Response.noContent().build();
    } else if (profile == null) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("orcid", orcid);
        throw new OrcidNotFoundException(params);
    } else {
        Map<String, String> params = new HashMap<String, String>();
        params.put("client", clientId);
        throw new OrcidClientNotFoundException(params);
    }
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) WebhookEntityPk(org.orcid.persistence.jpa.entities.keys.WebhookEntityPk) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) Date(java.util.Date) SubmissionDate(org.orcid.jaxb.model.message.SubmissionDate) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OrcidBadRequestException(org.orcid.core.exception.OrcidBadRequestException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) WebhookEntity(org.orcid.persistence.jpa.entities.WebhookEntity) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidNotFoundException(org.orcid.core.exception.OrcidNotFoundException) Map(java.util.Map) HashMap(java.util.HashMap) OrcidClientNotFoundException(org.orcid.core.exception.OrcidClientNotFoundException) AccessControl(org.orcid.core.security.visibility.aop.AccessControl)

Example 44 with OAuth2Request

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

the class T2OrcidApiServiceDelegatorImpl method unregisterWebhook.

/**
     * Unregister a webhook from a profile. As with all calls, if the message
     * contains any other elements, a 400 Bad Request will be returned.
     * 
     * @param orcid
     *            the identifier of the profile to unregister the webhook
     * @param uriInfo
     *            an uri object containing the webhook that will be unregistred
     * @return If successful, returns a 204 No content.
     * */
@Override
@AccessControl(requiredScope = ScopePathType.WEBHOOK)
public Response unregisterWebhook(UriInfo uriInfo, String orcid, String webhookUri) {
    ProfileEntity profile = profileEntityCacheManager.retrieve(orcid);
    if (profile != null) {
        WebhookEntityPk webhookPk = new WebhookEntityPk(profile, webhookUri);
        WebhookEntity webhook = webhookManager.find(webhookPk);
        if (webhook == null) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("orcid", orcid);
            params.put("uri", webhookUri);
            throw new OrcidWebhookNotFoundException(params);
        } else {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String clientId = null;
            if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
                OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request();
                clientId = authorizationRequest.getClientId();
            }
            // Check if user can unregister this webhook
            if (webhook.getClientDetails().getId().equals(clientId)) {
                webhookManager.delete(webhookPk);
                return Response.noContent().build();
            } else {
                // that webhook
                throw new OrcidForbiddenException(localeManager.resolveMessage("apiError.forbidden_unregister_webhook.exception"));
            }
        }
    } else {
        Map<String, String> params = new HashMap<String, String>();
        params.put("orcid", orcid);
        throw new OrcidNotFoundException(params);
    }
}
Also used : OrcidWebhookNotFoundException(org.orcid.core.exception.OrcidWebhookNotFoundException) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OrcidForbiddenException(org.orcid.core.exception.OrcidForbiddenException) WebhookEntityPk(org.orcid.persistence.jpa.entities.keys.WebhookEntityPk) HashMap(java.util.HashMap) WebhookEntity(org.orcid.persistence.jpa.entities.WebhookEntity) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidNotFoundException(org.orcid.core.exception.OrcidNotFoundException) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) AccessControl(org.orcid.core.security.visibility.aop.AccessControl)

Example 45 with OAuth2Request

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

the class T2OrcidApiServiceDelegatorImpl method setSponsorFromAuthentication.

public void setSponsorFromAuthentication(OrcidProfile profile) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (profile.getOrcidHistory() == null) {
        OrcidHistory orcidHistory = new OrcidHistory();
        orcidHistory.setCreationMethod(CreationMethod.API);
        profile.setOrcidHistory(orcidHistory);
    }
    profile.getOrcidHistory().setSubmissionDate(new SubmissionDate(DateUtils.convertToXMLGregorianCalendar(new Date())));
    if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
        OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request();
        Source sponsor = new Source();
        String sponsorId = authorizationRequest.getClientId();
        ClientDetailsEntity clientDetails = clientDetailsManager.findByClientId(sponsorId);
        if (clientDetails != null) {
            sponsor.setSourceName(new SourceName(clientDetails.getClientName()));
            if (OrcidStringUtils.isClientId(sponsorId)) {
                sponsor.setSourceClientId(new SourceClientId(sponsorId));
            } else {
                sponsor.setSourceOrcid(new SourceOrcid(sponsorId));
            }
        }
        profile.getOrcidHistory().setSource(sponsor);
    }
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OrcidHistory(org.orcid.jaxb.model.message.OrcidHistory) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) SourceClientId(org.orcid.jaxb.model.message.SourceClientId) SourceName(org.orcid.jaxb.model.message.SourceName) SourceOrcid(org.orcid.jaxb.model.message.SourceOrcid) SubmissionDate(org.orcid.jaxb.model.message.SubmissionDate) Date(java.util.Date) SubmissionDate(org.orcid.jaxb.model.message.SubmissionDate) Source(org.orcid.jaxb.model.message.Source)

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 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)16 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)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