Search in sources :

Example 51 with AuthorizationRequest

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

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

the class OauthAuthorizeController method authorize.

@RequestMapping(value = { "/oauth/custom/authorize.json" }, method = RequestMethod.POST)
@ResponseBody
public RequestInfoForm authorize(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthAuthorizeForm form) {
    RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    AuthorizationRequest authorizationRequest = (AuthorizationRequest) request.getSession().getAttribute("authorizationRequest");
    Map<String, String> requestParams = new HashMap<String, String>(authorizationRequest.getRequestParameters());
    Map<String, String> approvalParams = new HashMap<String, String>();
    // Add the persistent token information
    if (form.getApproved()) {
        requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
        approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    } else {
        requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "false");
        approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "false");
    }
    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
        if (form.getPersistentTokenEnabled())
            requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true");
    // strip /email/read-private scope if user has not consented
    if (requestInfoForm.containsEmailReadPrivateScope() && !form.isEmailAccessAllowed()) {
        requestInfoForm.removeEmailReadPrivateScope();
        requestParams.put(OrcidOauth2Constants.SCOPE_PARAM, requestInfoForm.getScopesAsString());
    }
    // 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
    RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
    requestInfoForm.setRedirectUrl(view.getUrl());
    if (new HttpSessionRequestCache().getRequest(request, response) != null)
        new HttpSessionRequestCache().removeRequest(request, response);
    LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: " + requestInfoForm.getRedirectUrl());
    return requestInfoForm;
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) HashMap(java.util.HashMap) Authentication(org.springframework.security.core.Authentication) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) RedirectView(org.springframework.web.servlet.view.RedirectView) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) SimpleSessionStatus(org.springframework.web.bind.support.SimpleSessionStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 53 with AuthorizationRequest

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

the class SourceManagerImpl method retrieveRealUserOrcid.

@Override
public String retrieveRealUserOrcid() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        return null;
    }
    // API
    if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
        OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request();
        return authorizationRequest.getClientId();
    }
    // Delegation mode
    String realUserIfInDelegationMode = getRealUserIfInDelegationMode(authentication);
    if (realUserIfInDelegationMode != null) {
        return realUserIfInDelegationMode;
    }
    // Normal web user
    return retrieveEffectiveOrcid(authentication);
}
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)

Example 54 with AuthorizationRequest

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

the class OrcidRandomValueTokenServicesImpl method refreshAccessToken.

@Override
@Transactional
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) throws AuthenticationException {
    String parentTokenValue = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.AUTHORIZATION);
    String clientId = tokenRequest.getClientId();
    String scopes = tokenRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    Long expiresIn = tokenRequest.getRequestParameters().containsKey(OrcidOauth2Constants.EXPIRES_IN) ? Long.valueOf(tokenRequest.getRequestParameters().get(OrcidOauth2Constants.EXPIRES_IN)) : 0L;
    Boolean revokeOld = tokenRequest.getRequestParameters().containsKey(OrcidOauth2Constants.REVOKE_OLD) ? Boolean.valueOf(tokenRequest.getRequestParameters().get(OrcidOauth2Constants.REVOKE_OLD)) : true;
    // Check if the refresh token is enabled
    if (!customSupportRefreshToken) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }
    // Check if the client support refresh token
    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
    if (!clientDetails.getAuthorizedGrantTypes().contains(OrcidOauth2Constants.REFRESH_TOKEN)) {
        throw new InvalidGrantException("Client " + clientId + " doesnt have refresh token enabled");
    }
    OrcidOauth2TokenDetail parentToken = orcidOauth2TokenDetailDao.findByTokenValue(parentTokenValue);
    ProfileEntity profileEntity = new ProfileEntity(parentToken.getProfile().getId());
    OrcidOauth2TokenDetail newToken = new OrcidOauth2TokenDetail();
    newToken.setApproved(true);
    newToken.setClientDetailsId(clientId);
    newToken.setDateCreated(new Date());
    newToken.setLastModified(new Date());
    newToken.setPersistent(parentToken.isPersistent());
    newToken.setProfile(profileEntity);
    newToken.setRedirectUri(parentToken.getRedirectUri());
    newToken.setRefreshTokenValue(UUID.randomUUID().toString());
    newToken.setResourceId(parentToken.getResourceId());
    newToken.setResponseType(parentToken.getResponseType());
    newToken.setState(parentToken.getState());
    newToken.setTokenDisabled(false);
    if (expiresIn <= 0) {
        //If expiresIn is 0 or less, set the parent token 
        newToken.setTokenExpiration(parentToken.getTokenExpiration());
    } else {
        //Assumes expireIn already contains the real expired time expressed in millis 
        newToken.setTokenExpiration(new Date(expiresIn));
    }
    newToken.setTokenType(parentToken.getTokenType());
    newToken.setTokenValue(UUID.randomUUID().toString());
    newToken.setVersion(parentToken.getVersion());
    if (PojoUtil.isEmpty(scopes)) {
        newToken.setScope(parentToken.getScope());
    } else {
        newToken.setScope(scopes);
    }
    //Generate an authentication object to be able to generate the authentication key
    Set<String> scopesSet = OAuth2Utils.parseParameterList(newToken.getScope());
    AuthorizationRequest request = new AuthorizationRequest(clientId, scopesSet);
    request.setApproved(true);
    Authentication authentication = new OrcidOauth2UserAuthentication(profileEntity, true);
    OrcidOAuth2Authentication orcidAuthentication = new OrcidOAuth2Authentication(request, authentication, newToken.getTokenValue());
    newToken.setAuthenticationKey(authenticationKeyGenerator.extractKey(orcidAuthentication));
    // Store the new token and return it
    orcidOauth2TokenDetailDao.persist(newToken);
    // Revoke the old token when required
    if (revokeOld) {
        orcidOauth2TokenDetailDao.disableAccessToken(parentTokenValue);
    }
    // Save the changes
    orcidOauth2TokenDetailDao.flush();
    // and return it                
    return toOAuth2AccessToken(newToken);
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) OrcidOAuth2Authentication(org.orcid.core.oauth.OrcidOAuth2Authentication) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) Date(java.util.Date) OrcidOauth2UserAuthentication(org.orcid.core.oauth.OrcidOauth2UserAuthentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidOAuth2Authentication(org.orcid.core.oauth.OrcidOAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OrcidOauth2UserAuthentication(org.orcid.core.oauth.OrcidOauth2UserAuthentication) OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail) Transactional(org.springframework.transaction.annotation.Transactional)

Example 55 with AuthorizationRequest

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

the class OrcidTokenStoreServiceImpl method getOAuth2AuthenticationFromDetails.

private OAuth2Authentication getOAuth2AuthenticationFromDetails(OrcidOauth2TokenDetail details) {
    if (details != null) {
        ClientDetailsEntity clientDetailsEntity = clientDetailsEntityCacheManager.retrieve(details.getClientDetailsId());
        Authentication authentication = null;
        AuthorizationRequest request = null;
        if (clientDetailsEntity != null) {
            //Check member is not locked                
            orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetailsEntity);
            Set<String> scopes = OAuth2Utils.parseParameterList(details.getScope());
            request = new AuthorizationRequest(clientDetailsEntity.getClientId(), scopes);
            request.setAuthorities(clientDetailsEntity.getAuthorities());
            Set<String> resourceIds = new HashSet<>();
            resourceIds.add(details.getResourceId());
            request.setResourceIds(resourceIds);
            request.setApproved(details.isApproved());
            ProfileEntity profile = details.getProfile();
            if (profile != null) {
                authentication = new OrcidOauth2UserAuthentication(profile, details.isApproved());
            }
        }
        return new OrcidOAuth2Authentication(request, authentication, details.getTokenValue());
    }
    throw new InvalidTokenException("Token not found");
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) OrcidOauth2UserAuthentication(org.orcid.core.oauth.OrcidOauth2UserAuthentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidOAuth2Authentication(org.orcid.core.oauth.OrcidOAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OrcidOauth2UserAuthentication(org.orcid.core.oauth.OrcidOauth2UserAuthentication) OrcidOAuth2Authentication(org.orcid.core.oauth.OrcidOAuth2Authentication) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) HashSet(java.util.HashSet)

Aggregations

AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)66 Test (org.junit.Test)57 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)45 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)42 Authentication (org.springframework.security.core.Authentication)33 HashMap (java.util.HashMap)18 ModelAndView (org.springframework.web.servlet.ModelAndView)16 HashSet (java.util.HashSet)15 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)15 OrcidOAuth2Authentication (org.orcid.core.oauth.OrcidOAuth2Authentication)14 RedirectView (org.springframework.web.servlet.view.RedirectView)14 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)13 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)12 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)12 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)12 Date (java.util.Date)11 ScopePathType (org.orcid.jaxb.model.message.ScopePathType)10 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)8 TokenGranter (org.springframework.security.oauth2.provider.TokenGranter)8 DefaultUserApprovalHandler (org.springframework.security.oauth2.provider.approval.DefaultUserApprovalHandler)8