Search in sources :

Example 26 with ClientDetails

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

the class ImplicitTokenGranter method getOAuth2Authentication.

@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest clientToken) {
    Authentication userAuth = SecurityContextHolder.getContext().getAuthentication();
    if (userAuth == null || !userAuth.isAuthenticated()) {
        throw new InsufficientAuthenticationException("There is no currently logged in user");
    }
    Assert.state(clientToken instanceof ImplicitTokenRequest, "An ImplicitTokenRequest is required here. Caller needs to wrap the TokenRequest.");
    OAuth2Request requestForStorage = ((ImplicitTokenRequest) clientToken).getOAuth2Request();
    return new OAuth2Authentication(requestForStorage, userAuth);
}
Also used : 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) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 27 with ClientDetails

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

the class DefaultOAuth2RequestFactory method extractScopes.

private Set<String> extractScopes(Map<String, String> requestParameters, String clientId) {
    Set<String> scopes = OAuth2Utils.parseParameterList(requestParameters.get(OAuth2Utils.SCOPE));
    ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
    if ((scopes == null || scopes.isEmpty())) {
        // If no scopes are specified in the incoming data, use the default values registered with the client
        // (the spec allows us to choose between this option and rejecting the request completely, so we'll take the
        // least obnoxious choice as a default).
        scopes = clientDetails.getScope();
    }
    if (checkUserScopes) {
        scopes = checkUserScopes(scopes, clientDetails);
    }
    return scopes;
}
Also used : ClientDetails(org.springframework.security.oauth2.provider.ClientDetails)

Example 28 with ClientDetails

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

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

the class LoginController method handleOauthSignIn.

private ModelAndView handleOauthSignIn(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
    String queryString = request.getQueryString();
    String redirectUri = null;
    // Get and save the request information form
    RequestInfoForm requestInfoForm = generateRequestInfoForm(queryString);
    request.getSession().setAttribute(REQUEST_INFO_FORM, requestInfoForm);
    // Save also the original query string
    request.getSession().setAttribute(OrcidOauth2Constants.OAUTH_QUERY_STRING, queryString);
    // Save a flag to indicate this is a request from the new
    request.getSession().setAttribute(OrcidOauth2Constants.OAUTH_2SCREENS, true);
    // Redirect URI
    redirectUri = requestInfoForm.getRedirectUrl();
    // Check that the client have the required permissions
    // Get client name
    String clientId = requestInfoForm.getClientId();
    if (PojoUtil.isEmpty(clientId)) {
        String redirectUriWithParams = redirectUri + "?error=invalid_client&error_description=invalid client_id";
        return new ModelAndView(new RedirectView(redirectUriWithParams));
    }
    // Validate client details
    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
    try {
        orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
    } catch (LockedException e) {
        String redirectUriWithParams = redirectUri + "?error=client_locked&error_description=" + e.getMessage();
        return new ModelAndView(new RedirectView(redirectUriWithParams));
    }
    // validate client scopes
    try {
        authorizationEndpoint.validateScope(requestInfoForm.getScopesAsString(), clientDetails, requestInfoForm.getResponseType());
    } catch (InvalidScopeException e) {
        String redirectUriWithParams = redirectUri + "?error=invalid_scope&error_description=" + e.getMessage();
        return new ModelAndView(new RedirectView(redirectUriWithParams));
    }
    // 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;
        }
    }
    ModelAndView mav = new ModelAndView("login");
    boolean showLogin = false;
    // orcid and email take precedence over show_login param
    if (PojoUtil.isEmpty(requestInfoForm.getUserOrcid()) && PojoUtil.isEmpty(requestInfoForm.getUserEmail()) && queryString.toLowerCase().contains("show_login=false")) {
        showLogin = false;
    } else if (PojoUtil.isEmpty(requestInfoForm.getUserOrcid()) && PojoUtil.isEmpty(requestInfoForm.getUserEmail())) {
        showLogin = true;
    } else if (!PojoUtil.isEmpty(requestInfoForm.getUserOrcid()) && profileEntityManager.orcidExists(requestInfoForm.getUserOrcid())) {
        mav.addObject("oauth_userId", requestInfoForm.getUserOrcid());
        showLogin = true;
    } else if (!PojoUtil.isEmpty(requestInfoForm.getUserEmail())) {
        mav.addObject("oauth_userId", requestInfoForm.getUserEmail());
        if (emailManagerReadOnly.emailExists(requestInfoForm.getUserEmail())) {
            showLogin = true;
        }
    }
    mav.addObject("showLogin", String.valueOf(showLogin));
    mav.addObject("hideUserVoiceScript", true);
    mav.addObject("oauth2Screens", true);
    return mav;
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) LockedException(org.orcid.core.security.aop.LockedException) ModelAndView(org.springframework.web.servlet.ModelAndView) RedirectView(org.springframework.web.servlet.view.RedirectView) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException)

Example 30 with ClientDetails

use of org.springframework.security.oauth2.provider.ClientDetails 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, requestInfoForm.getResponseType());
        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.  max_age is in seconds.
            // is also on the entity.
            java.util.Date authTime = profileEntityManager.getLastLogin(orcid);
            try {
                long max = Long.parseLong(maxAge);
                if (authTime == null || ((authTime.getTime() + (max * 1000)) < (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);
            boolean hasPersistent = hasPersistenTokensEnabled(requestInfoForm.getClientId());
            // Don't let non persistent clients persist
            if (!hasPersistent && "true".equals(requestParams.get(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN))) {
                requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false");
            }
            // default to client default if not set
            if (requestParams.get(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN) == null) {
                if (hasPersistent)
                    requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true");
                else
                    requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false");
            }
            // 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;
        }
    }
    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=interaction_required";
            RedirectView rView = new RedirectView(redirectUriWithParams);
            ModelAndView error = new ModelAndView();
            error.setView(rView);
            return error;
        }
    }
    mav.addObject("hideUserVoiceScript", true);
    mav.addObject("originalOauth2Process", 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)

Aggregations

ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)44 Test (org.junit.Test)36 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)30 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)27 Authentication (org.springframework.security.core.Authentication)21 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)20 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)19 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)19 Date (java.util.Date)13 HashMap (java.util.HashMap)12 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)8 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)7 ClientDetailsService (org.springframework.security.oauth2.provider.ClientDetailsService)7 DBUnitTest (org.orcid.test.DBUnitTest)6 AnnotationConfigServletWebServerApplicationContext (org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext)6 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)6 OAuth2Exception (org.springframework.security.oauth2.common.exceptions.OAuth2Exception)6 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)6 OrcidOauth2ClientAuthentication (org.orcid.core.oauth.OrcidOauth2ClientAuthentication)5 InvalidClientException (org.springframework.security.oauth2.common.exceptions.InvalidClientException)5