Search in sources :

Example 21 with ClientDetailsEntity

use of org.orcid.persistence.jpa.entities.ClientDetailsEntity in project ORCID-Source by ORCID.

the class OrcidRandomValueTokenServicesTest method testCreateAddWorkAccessToken.

@Test
public void testCreateAddWorkAccessToken() {
    Date earliestExpiry = oneHoursTime();
    Map<String, String> authorizationParameters = new HashMap<>();
    String clientId = "4444-4444-4444-4441";
    authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
    authorizationParameters.put(OAuth2Utils.SCOPE, "/orcid-works/create");
    OAuth2Request request = new OAuth2Request(Collections.<String, String>emptyMap(), clientId, Collections.<GrantedAuthority>emptyList(), true, new HashSet<String>(Arrays.asList("/orcid-profile/read-limited")), Collections.<String>emptySet(), null, Collections.<String>emptySet(), Collections.<String, Serializable>emptyMap());
    ClientDetailsEntity clientDetails = clientDetailsManager.findByClientId(clientId);
    Authentication userAuthentication = new OrcidOauth2ClientAuthentication(clientDetails);
    OAuth2Authentication authentication = new OAuth2Authentication(request, userAuthentication);
    OAuth2AccessToken oauth2AccessToken = tokenServices.createAccessToken(authentication);
    Date latestExpiry = oneHoursTime();
    assertNotNull(oauth2AccessToken);
    assertFalse(oauth2AccessToken.getExpiration().before(earliestExpiry));
    assertFalse(oauth2AccessToken.getExpiration().after(latestExpiry));
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) HashMap(java.util.HashMap) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidOauth2ClientAuthentication(org.orcid.core.oauth.OrcidOauth2ClientAuthentication) Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Date(java.util.Date) OrcidOauth2ClientAuthentication(org.orcid.core.oauth.OrcidOauth2ClientAuthentication) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test)

Example 22 with ClientDetailsEntity

use of org.orcid.persistence.jpa.entities.ClientDetailsEntity in project ORCID-Source by ORCID.

the class OauthControllerBase method generateRequestInfoForm.

private RequestInfoForm generateRequestInfoForm(String clientId, String scopesString, String redirectUri, String responseType, String stateParam, String email, String orcid, String givenNames, String familyNames, String nonce, String maxAge) throws UnsupportedEncodingException {
    RequestInfoForm infoForm = new RequestInfoForm();
    //If the user is logged in 
    String loggedUserOrcid = getEffectiveUserOrcid();
    if (!PojoUtil.isEmpty(loggedUserOrcid)) {
        infoForm.setUserOrcid(loggedUserOrcid);
        ProfileEntity profile = profileEntityCacheManager.retrieve(loggedUserOrcid);
        String creditName = "";
        RecordNameEntity recordName = profile.getRecordNameEntity();
        if (recordName != null) {
            if (!PojoUtil.isEmpty(profile.getRecordNameEntity().getCreditName())) {
                creditName = profile.getRecordNameEntity().getCreditName();
            } else {
                creditName = PojoUtil.isEmpty(profile.getRecordNameEntity().getGivenNames()) ? profile.getRecordNameEntity().getFamilyName() : profile.getRecordNameEntity().getGivenNames() + " " + profile.getRecordNameEntity().getFamilyName();
            }
        }
        if (!PojoUtil.isEmpty(creditName)) {
            infoForm.setUserName(URLDecoder.decode(creditName, "UTF-8").trim());
        }
    }
    Set<ScopePathType> scopes = new HashSet<ScopePathType>();
    if (!PojoUtil.isEmpty(clientId) && !PojoUtil.isEmpty(scopesString)) {
        scopesString = URLDecoder.decode(scopesString, "UTF-8").trim();
        scopesString = scopesString.replaceAll(" +", " ");
        scopes = ScopePathType.getScopesFromSpaceSeparatedString(scopesString);
    } else {
        throw new InvalidRequestException("Unable to find parameters");
    }
    for (ScopePathType theScope : scopes) {
        ScopeInfoForm scopeInfoForm = new ScopeInfoForm();
        scopeInfoForm.setValue(theScope.value());
        scopeInfoForm.setName(theScope.name());
        try {
            scopeInfoForm.setDescription(getMessage(ScopePathType.class.getName() + '.' + theScope.name()));
            scopeInfoForm.setLongDescription(getMessage(ScopePathType.class.getName() + '.' + theScope.name() + ".longDesc"));
        } catch (NoSuchMessageException e) {
            LOGGER.warn("Unable to find key message for scope: " + theScope.name() + " " + theScope.value());
        }
        infoForm.getScopes().add(scopeInfoForm);
    }
    // Check if the client has persistent tokens enabled
    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
    if (clientDetails.isPersistentTokensEnabled()) {
        infoForm.setClientHavePersistentTokens(true);
    }
    // If client details is ok, continue
    String clientName = clientDetails.getClientName() == null ? "" : clientDetails.getClientName();
    String clientEmailRequestReason = clientDetails.getEmailAccessReason() == null ? "" : clientDetails.getEmailAccessReason();
    String clientDescription = clientDetails.getClientDescription() == null ? "" : clientDetails.getClientDescription();
    String memberName = "";
    // If client type is null it means it is a public client
    if (ClientType.PUBLIC_CLIENT.equals(clientDetails.getClientType())) {
        memberName = PUBLIC_MEMBER_NAME;
    } else if (!PojoUtil.isEmpty(clientDetails.getGroupProfileId())) {
        ProfileEntity groupProfile = profileEntityCacheManager.retrieve(clientDetails.getGroupProfileId());
        if (groupProfile.getRecordNameEntity() != null) {
            memberName = groupProfile.getRecordNameEntity().getCreditName();
        }
    }
    // name, since it should be a SSO user
    if (StringUtils.isBlank(memberName)) {
        memberName = clientName;
    }
    if (!PojoUtil.isEmpty(email) || !PojoUtil.isEmpty(orcid)) {
        // Check if orcid exists, if so, show login screen
        if (!PojoUtil.isEmpty(orcid)) {
            orcid = orcid.trim();
            if (orcidProfileManager.exists(orcid)) {
                infoForm.setUserId(orcid);
            }
        } else {
            // Check if email exists, if so, show login screen
            if (!PojoUtil.isEmpty(email)) {
                email = email.trim();
                if (emailManager.emailExists(email)) {
                    infoForm.setUserId(email);
                }
            }
        }
    }
    infoForm.setUserEmail(email);
    if (PojoUtil.isEmpty(loggedUserOrcid))
        infoForm.setUserOrcid(orcid);
    infoForm.setUserGivenNames(givenNames);
    infoForm.setUserFamilyNames(familyNames);
    infoForm.setClientId(clientId);
    infoForm.setClientDescription(clientDescription);
    infoForm.setClientName(clientName);
    infoForm.setClientEmailRequestReason(clientEmailRequestReason);
    infoForm.setMemberName(memberName);
    infoForm.setRedirectUrl(redirectUri);
    infoForm.setStateParam(stateParam);
    infoForm.setResponseType(responseType);
    infoForm.setNonce(nonce);
    return infoForm;
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) NoSuchMessageException(org.springframework.context.NoSuchMessageException) ScopePathType(org.orcid.jaxb.model.message.ScopePathType) RecordNameEntity(org.orcid.persistence.jpa.entities.RecordNameEntity) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) ScopeInfoForm(org.orcid.pojo.ajaxForm.ScopeInfoForm) HashSet(java.util.HashSet)

Example 23 with ClientDetailsEntity

use of org.orcid.persistence.jpa.entities.ClientDetailsEntity in project ORCID-Source by ORCID.

the class OauthLoginController method loginGetHandler.

@RequestMapping(value = { "/oauth/signin", "/oauth/login" }, method = RequestMethod.GET)
public ModelAndView loginGetHandler(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) throws UnsupportedEncodingException {
    String url = request.getQueryString();
    // default to Reg
    boolean showLogin = showLoginDefault;
    // Get and save the request information form
    RequestInfoForm requestInfoForm = generateRequestInfoForm(url);
    request.getSession().setAttribute(REQUEST_INFO_FORM, requestInfoForm);
    if (url.toLowerCase().contains("show_login=true"))
        showLogin = true;
    else if (url.toLowerCase().contains("show_login=false"))
        showLogin = false;
    //Check if userId is set so we should show the login screen
    if (!PojoUtil.isEmpty(requestInfoForm.getUserId())) {
        showLogin = true;
    }
    // Check that the client have the required permissions
    // Get client name
    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(requestInfoForm.getClientId());
    // validate client scopes
    try {
        authorizationEndpoint.validateScope(requestInfoForm.getScopesAsString(), clientDetails);
        orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
    } catch (InvalidScopeException | LockedException e) {
        String redirectUriWithParams = requestInfoForm.getRedirectUrl();
        if (e instanceof InvalidScopeException) {
            redirectUriWithParams += "?error=invalid_scope&error_description=" + e.getMessage();
        } else {
            redirectUriWithParams += "?error=client_locked&error_description=" + e.getMessage();
        }
        RedirectView rView = new RedirectView(redirectUriWithParams);
        ModelAndView error = new ModelAndView();
        error.setView(rView);
        return error;
    }
    //handle openID behaviour
    if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()) && ScopePathType.getScopesFromSpaceSeparatedString(requestInfoForm.getScopesAsString()).contains(ScopePathType.OPENID)) {
        String prompt = request.getParameter(OrcidOauth2Constants.PROMPT);
        if (prompt != null && prompt.equals(OrcidOauth2Constants.PROMPT_NONE)) {
            String redirectUriWithParams = requestInfoForm.getRedirectUrl();
            redirectUriWithParams += "?error=login_required";
            RedirectView rView = new RedirectView(redirectUriWithParams);
            ModelAndView error = new ModelAndView();
            error.setView(rView);
            return error;
        }
    }
    mav.addObject("hideUserVoiceScript", true);
    mav.addObject("showLogin", String.valueOf(showLogin));
    mav.setViewName("oauth_login");
    return mav;
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) LockedException(org.orcid.core.security.aop.LockedException) RedirectView(org.springframework.web.servlet.view.RedirectView) ModelAndView(org.springframework.web.servlet.ModelAndView) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 24 with ClientDetailsEntity

use of org.orcid.persistence.jpa.entities.ClientDetailsEntity in project ORCID-Source by ORCID.

the class OauthAuthorizeController method loginGetHandler.

/** This is called if user is already logged in.  
     * Checks permissions have been granted to client and generates access code.
     * 
     * @param request
     * @param response
     * @param mav
     * @return
     * @throws UnsupportedEncodingException
     */
@RequestMapping(value = "/oauth/confirm_access", method = RequestMethod.GET)
public ModelAndView loginGetHandler(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) throws UnsupportedEncodingException {
    //Get and save the request information form
    RequestInfoForm requestInfoForm = generateRequestInfoForm(request);
    request.getSession().setAttribute(REQUEST_INFO_FORM, requestInfoForm);
    Boolean justRegistered = (Boolean) request.getSession().getAttribute(OrcidOauth2Constants.JUST_REGISTERED);
    if (justRegistered != null) {
        request.getSession().removeAttribute(OrcidOauth2Constants.JUST_REGISTERED);
        mav.addObject(OrcidOauth2Constants.JUST_REGISTERED, justRegistered);
    }
    boolean usePersistentTokens = false;
    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(requestInfoForm.getClientId());
    // validate client scopes
    try {
        authorizationEndpoint.validateScope(requestInfoForm.getScopesAsString(), clientDetails);
        orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
    } catch (InvalidScopeException | LockedException e) {
        String redirectUriWithParams = requestInfoForm.getRedirectUrl();
        if (e instanceof InvalidScopeException) {
            redirectUriWithParams += "?error=invalid_scope&error_description=" + e.getMessage();
        } else {
            redirectUriWithParams += "?error=client_locked&error_description=" + e.getMessage();
        }
        RedirectView rView = new RedirectView(redirectUriWithParams);
        ModelAndView error = new ModelAndView();
        error.setView(rView);
        return error;
    }
    //Add check for prompt=login and max_age here. This is a MUST in the openid spec.
    //Add check for prompt=confirm here. This is a SHOULD in the openid spec.
    boolean forceConfirm = false;
    if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()) && ScopePathType.getScopesFromSpaceSeparatedString(requestInfoForm.getScopesAsString()).contains(ScopePathType.OPENID)) {
        String prompt = request.getParameter(OrcidOauth2Constants.PROMPT);
        String maxAge = request.getParameter(OrcidOauth2Constants.MAX_AGE);
        String orcid = getEffectiveUserOrcid();
        if (maxAge != null) {
            //if maxAge+lastlogin > now, force login
            //is also on the entity.
            java.util.Date authTime = profileEntityManager.getLastLogin(orcid);
            try {
                long max = Long.parseLong(maxAge);
                if (authTime == null || ((authTime.getTime() + max) < (new java.util.Date()).getTime())) {
                    return oauthLoginController.loginGetHandler(request, response, new ModelAndView());
                }
            } catch (NumberFormatException e) {
            //ignore
            }
        }
        if (prompt != null && prompt.equals(OrcidOauth2Constants.PROMPT_CONFIRM)) {
            forceConfirm = true;
        } else if (prompt != null && prompt.equals(OrcidOauth2Constants.PROMPT_LOGIN)) {
            request.getParameterMap().remove(OrcidOauth2Constants.PROMPT);
            return oauthLoginController.loginGetHandler(request, response, new ModelAndView());
        }
    }
    // Check if the client has persistent tokens enabled
    if (clientDetails.isPersistentTokensEnabled()) {
        usePersistentTokens = true;
    }
    if (!forceConfirm && usePersistentTokens) {
        boolean tokenLongLifeAlreadyExists = tokenServices.longLifeTokenExist(requestInfoForm.getClientId(), getEffectiveUserOrcid(), OAuth2Utils.parseParameterList(requestInfoForm.getScopesAsString()));
        if (tokenLongLifeAlreadyExists) {
            AuthorizationRequest authorizationRequest = (AuthorizationRequest) request.getSession().getAttribute("authorizationRequest");
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            Map<String, String> requestParams = new HashMap<String, String>();
            copyRequestParameters(request, requestParams);
            Map<String, String> approvalParams = new HashMap<String, String>();
            requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
            approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
            requestParams.put(OrcidOauth2Constants.TOKEN_VERSION, OrcidOauth2Constants.PERSISTENT_TOKEN);
            // Check if the client have persistent tokens enabled
            requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false");
            if (hasPersistenTokensEnabled(requestInfoForm.getClientId())) {
                // Then check if the client granted the persistent token
                requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true");
            }
            // Session status
            SimpleSessionStatus status = new SimpleSessionStatus();
            authorizationRequest.setRequestParameters(requestParams);
            // Authorization request model
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("authorizationRequest", authorizationRequest);
            // Approve using the spring authorization endpoint code. 
            //note this will also handle generting implicit tokens via getTokenGranter().grant("implicit",new ImplicitTokenRequest(tokenRequest, storedOAuth2Request));
            RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
            ModelAndView authCodeView = new ModelAndView();
            authCodeView.setView(view);
            return authCodeView;
        }
    }
    mav.addObject("hideUserVoiceScript", true);
    mav.setViewName("confirm-oauth-access");
    return mav;
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) LockedException(org.orcid.core.security.aop.LockedException) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) Authentication(org.springframework.security.core.Authentication) RedirectView(org.springframework.web.servlet.view.RedirectView) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException) SimpleSessionStatus(org.springframework.web.bind.support.SimpleSessionStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 25 with ClientDetailsEntity

use of org.orcid.persistence.jpa.entities.ClientDetailsEntity in project ORCID-Source by ORCID.

the class AnalyticsProcess method getClientDetailsString.

private String getClientDetailsString() {
    if (clientDetailsId != null) {
        ClientDetailsEntity client = clientDetailsEntityCacheManager.retrieve(clientDetailsId);
        StringBuilder clientDetails = new StringBuilder(client.getClientType().value());
        clientDetails.append(" | ");
        clientDetails.append(client.getClientName());
        clientDetails.append(" - ");
        clientDetails.append(clientDetailsId);
        return clientDetails.toString();
    } else {
        return PUBLIC_API_USER;
    }
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity)

Aggregations

ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)149 Test (org.junit.Test)75 SourceEntity (org.orcid.persistence.jpa.entities.SourceEntity)57 BaseTest (org.orcid.core.BaseTest)51 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)33 Date (java.util.Date)23 Transactional (org.springframework.transaction.annotation.Transactional)16 HashSet (java.util.HashSet)15 DBUnitTest (org.orcid.test.DBUnitTest)15 HashMap (java.util.HashMap)14 Authentication (org.springframework.security.core.Authentication)13 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)13 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)11 Work (org.orcid.jaxb.model.record_v2.Work)9 Before (org.junit.Before)8 ArrayList (java.util.ArrayList)7 OrcidClient (org.orcid.jaxb.model.clientgroup.OrcidClient)7 ClientSecretEntity (org.orcid.persistence.jpa.entities.ClientSecretEntity)7 OrcidProfile (org.orcid.jaxb.model.message.OrcidProfile)6 Funding (org.orcid.jaxb.model.record_v2.Funding)6