Search in sources :

Example 1 with ImplicitTokenRequest

use of org.springframework.security.oauth2.provider.implicit.ImplicitTokenRequest 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 2 with ImplicitTokenRequest

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

Example 3 with ImplicitTokenRequest

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

the class OrcidImplicitTokenGranter method getOAuth2Authentication.

/**
 * Note, client must have implicit scope in client_authorized_grant_type
 * table to get this far. Otherwise request will be rejected by
 * OrcidClientCredentialsChecker
 */
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest clientToken) {
    Authentication userAuthSpring = SecurityContextHolder.getContext().getAuthentication();
    if (userAuthSpring == null || !userAuthSpring.isAuthenticated()) {
        throw new InsufficientAuthenticationException("There is no currently logged in user");
    }
    OAuth2Request request = ((ImplicitTokenRequest) clientToken).getOAuth2Request();
    OrcidOauth2UserAuthentication userAuth = new OrcidOauth2UserAuthentication(profileEntityManager.findByOrcid(userAuthSpring.getName()), userAuthSpring.isAuthenticated());
    OAuth2Authentication result = new OAuth2Authentication(request, userAuth);
    return result;
}
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) ImplicitTokenRequest(org.springframework.security.oauth2.provider.implicit.ImplicitTokenRequest) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Aggregations

Authentication (org.springframework.security.core.Authentication)3 InsufficientAuthenticationException (org.springframework.security.authentication.InsufficientAuthenticationException)2 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)2 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)2 HashMap (java.util.HashMap)1 LockedException (org.orcid.core.security.aop.LockedException)1 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)1 RequestInfoForm (org.orcid.pojo.ajaxForm.RequestInfoForm)1 InvalidScopeException (org.springframework.security.oauth2.common.exceptions.InvalidScopeException)1 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)1 ImplicitTokenRequest (org.springframework.security.oauth2.provider.implicit.ImplicitTokenRequest)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1 SimpleSessionStatus (org.springframework.web.bind.support.SimpleSessionStatus)1 ModelAndView (org.springframework.web.servlet.ModelAndView)1 RedirectView (org.springframework.web.servlet.view.RedirectView)1