Search in sources :

Example 26 with TokenRequest

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

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

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

the class OrcidClientCredentialsCheckerTest method testInvalidCredentialsScopes.

@Test(expected = InvalidScopeException.class)
public void testInvalidCredentialsScopes() throws Exception {
    String memberId = "2875-8158-1475-6194";
    String clientId = "APP-1";
    setupMocks(clientId, memberId);
    Set<String> requestedScopes = new HashSet<String>(Arrays.asList(ScopePathType.FUNDING_CREATE.value()));
    Map<String, String> requestParams = new HashMap<String, String>();
    requestParams.put(OrcidOauth2Constants.SCOPE_PARAM, ScopePathType.FUNDING_CREATE.value());
    checker.validateCredentials("client_credentials", new TokenRequest(requestParams, clientId, requestedScopes, "client_credentials"));
}
Also used : HashMap(java.util.HashMap) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 29 with TokenRequest

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

the class AuthorizationEndpoint method getImplicitGrantResponse.

// We can grant a token and return it with implicit approval.
private ModelAndView getImplicitGrantResponse(AuthorizationRequest authorizationRequest) {
    try {
        TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, "implicit");
        OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest);
        OAuth2AccessToken accessToken = getAccessTokenForImplicitGrant(tokenRequest, storedOAuth2Request);
        if (accessToken == null) {
            throw new UnsupportedResponseTypeException("Unsupported response type: token");
        }
        return new ModelAndView(new RedirectView(appendAccessToken(authorizationRequest, accessToken), false, true, false));
    } catch (OAuth2Exception e) {
        return new ModelAndView(new RedirectView(getUnsuccessfulRedirect(authorizationRequest, e, true), false, true, false));
    }
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) ImplicitTokenRequest(org.springframework.security.oauth2.provider.implicit.ImplicitTokenRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) RedirectView(org.springframework.web.servlet.view.RedirectView) UnsupportedResponseTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedResponseTypeException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 30 with TokenRequest

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

the class DefaultTokenServices method createRefreshedAuthentication.

/**
	 * Create a refreshed authentication.
	 * 
	 * @param authentication The authentication.
	 * @param request The scope for the refreshed token.
	 * @return The refreshed authentication.
	 * @throws InvalidScopeException If the scope requested is invalid or wider than the original scope.
	 */
private OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, TokenRequest request) {
    OAuth2Authentication narrowed = authentication;
    Set<String> scope = request.getScope();
    OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request);
    if (scope != null && !scope.isEmpty()) {
        Set<String> originalScope = clientAuth.getScope();
        if (originalScope == null || !originalScope.containsAll(scope)) {
            throw new InvalidScopeException("Unable to narrow the scope of the client authentication to " + scope + ".", originalScope);
        } else {
            clientAuth = clientAuth.narrowScope(scope);
        }
    }
    narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication());
    return narrowed;
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException)

Aggregations

TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)40 Test (org.junit.Test)38 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)34 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)33 Authentication (org.springframework.security.core.Authentication)25 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)21 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)13 HashMap (java.util.HashMap)11 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)11 ModelAndView (org.springframework.web.servlet.ModelAndView)10 ExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)9 TokenGranter (org.springframework.security.oauth2.provider.TokenGranter)9 RedirectView (org.springframework.web.servlet.view.RedirectView)9 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)8 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)7 DefaultUserApprovalHandler (org.springframework.security.oauth2.provider.approval.DefaultUserApprovalHandler)7 InvalidGrantException (org.springframework.security.oauth2.common.exceptions.InvalidGrantException)6 Date (java.util.Date)5 HashSet (java.util.HashSet)5 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)5