Search in sources :

Example 86 with OAuth2Authentication

use of org.springframework.security.oauth2.provider.OAuth2Authentication 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 87 with OAuth2Authentication

use of org.springframework.security.oauth2.provider.OAuth2Authentication 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 88 with OAuth2Authentication

use of org.springframework.security.oauth2.provider.OAuth2Authentication 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)

Example 89 with OAuth2Authentication

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

the class OrcidAuthorizationCodeServiceImpl method getDetailFromAuthorization.

private OrcidOauth2AuthoriziationCodeDetail getDetailFromAuthorization(String code, OAuth2Authentication authentication) {
    OAuth2Request oAuth2Request = authentication.getOAuth2Request();
    OrcidOauth2AuthoriziationCodeDetail detail = new OrcidOauth2AuthoriziationCodeDetail();
    Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
    if (requestParameters != null && !requestParameters.isEmpty()) {
        String clientId = (String) requestParameters.get(CLIENT_ID);
        ClientDetailsEntity clientDetails = getClientDetails(clientId);
        if (clientDetails == null) {
            return null;
        }
        detail.setScopes(OAuth2Utils.parseParameterList((String) requestParameters.get(SCOPE)));
        detail.setState((String) requestParameters.get(STATE));
        detail.setRedirectUri((String) requestParameters.get(REDIRECT_URI));
        detail.setResponseType((String) requestParameters.get(RESPONSE_TYPE));
        detail.setClientDetailsEntity(clientDetails);
        //persist the openID params if present
        if (requestParameters.get(OrcidOauth2Constants.NONCE) != null)
            detail.setNonce((String) requestParameters.get(OrcidOauth2Constants.NONCE));
    }
    detail.setId(code);
    detail.setApproved(authentication.getOAuth2Request().isApproved());
    Authentication userAuthentication = authentication.getUserAuthentication();
    Object principal = userAuthentication.getPrincipal();
    ProfileEntity entity = null;
    if (principal instanceof OrcidProfileUserDetails) {
        OrcidProfileUserDetails userDetails = (OrcidProfileUserDetails) principal;
        String effectiveOrcid = userDetails.getOrcid();
        if (effectiveOrcid != null) {
            entity = profileEntityCacheManager.retrieve(effectiveOrcid);
        }
    }
    if (entity == null) {
        return null;
    }
    detail.setProfileEntity(entity);
    detail.setAuthenticated(userAuthentication.isAuthenticated());
    Set<String> authorities = getStringSetFromGrantedAuthorities(authentication.getAuthorities());
    detail.setAuthorities(authorities);
    Object authenticationDetails = userAuthentication.getDetails();
    if (authenticationDetails instanceof WebAuthenticationDetails) {
        detail.setSessionId(((WebAuthenticationDetails) authenticationDetails).getSessionId());
    }
    boolean isPersistentTokenEnabledByUser = false;
    //Set token version to persistent token
    //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 (requestParameters.containsKey(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN)) {
        String grantPersitentToken = (String) requestParameters.get(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN);
        if (Boolean.parseBoolean(grantPersitentToken)) {
            isPersistentTokenEnabledByUser = true;
        }
    }
    detail.setPersistent(isPersistentTokenEnabledByUser);
    return detail;
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) 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) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) OrcidProfileUserDetails(org.orcid.core.oauth.OrcidProfileUserDetails) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity)

Example 90 with OAuth2Authentication

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

the class OrcidAuthorizationCodeServiceTest method testCreateAuthorizationCodeWithValidClient.

@Test
@Rollback
@Transactional
public void testCreateAuthorizationCodeWithValidClient() {
    AuthorizationRequest request = getAuthorizationRequest("4444-4444-4444-4441");
    OAuth2Authentication oauth2Authentication = new OAuth2Authentication(oAuth2RequestFactory.createOAuth2Request(request), getUserAuthentication());
    String authorizationCode = authorizationCodeServices.createAuthorizationCode(oauth2Authentication);
    assertNotNull(authorizationCode);
    oauth2Authentication = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
    assertNotNull(oauth2Authentication);
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test) Rollback(org.springframework.test.annotation.Rollback) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)166 Test (org.junit.Test)116 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)84 Authentication (org.springframework.security.core.Authentication)68 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)57 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)49 Date (java.util.Date)34 HashMap (java.util.HashMap)22 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)21 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)20 DBUnitTest (org.orcid.test.DBUnitTest)17 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)15 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)15 DefaultOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken)15 HashSet (java.util.HashSet)13 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)13 ExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)13 OAuth2RefreshToken (org.springframework.security.oauth2.common.OAuth2RefreshToken)13 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)13 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)12