Example usage for org.springframework.security.web.savedrequest HttpSessionRequestCache HttpSessionRequestCache

List of usage examples for org.springframework.security.web.savedrequest HttpSessionRequestCache HttpSessionRequestCache

Introduction

In this page you can find the example usage for org.springframework.security.web.savedrequest HttpSessionRequestCache HttpSessionRequestCache.

Prototype

HttpSessionRequestCache

Source Link

Usage

From source file:nl.surfnet.spring.security.opensaml.config.ServiceProviderBeanDefinitionParser.java

@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {

    final String preAuthFilterRef = element.getAttribute("preauth-filter-ref");
    if (StringUtils.isBlank(preAuthFilterRef)) {
        parserContext.getReaderContext().error("The preauth-filter-ref is mandatory", element);
    }/* w ww.  ja v a  2 s.  c  o m*/

    final String messageHandlerRef = element.getAttribute("message-handler-ref");
    if (StringUtils.isBlank(messageHandlerRef)) {
        parserContext.getReaderContext().error("The message-handler-ref is mandatory", element);
    }

    final String certificatestoreRef = element.getAttribute("certificatestore-ref");
    if (StringUtils.isBlank(certificatestoreRef)) {
        parserContext.getReaderContext().error("The certificatestore-ref is mandatory", element);
    }

    final String provisionerRef = element.getAttribute("provisioner-ref");
    if (StringUtils.isBlank(provisionerRef)) {
        parserContext.getReaderContext().error("The provisioner-ref is mandatory", element);
    }

    final String authenticationManangerRef = element.getAttribute("authentication-manager-ref");
    if (StringUtils.isBlank(authenticationManangerRef)) {
        parserContext.getReaderContext().error("The authentication-manager-ref is mandatory", element);
    }

    final String entityID = element.getAttribute("entity-id");
    if (StringUtils.isBlank(entityID)) {
        parserContext.getReaderContext().error("The entity-id is mandatory", element);
    }

    final String assertionConsumerURI = element.getAttribute("assertion-consumer-uri");
    if (StringUtils.isBlank(assertionConsumerURI)) {
        parserContext.getReaderContext().error("Missing or empty assertion-consumer-uri.", element);
    }

    final String poolSize = element.getAttribute("max-parser-pool-size");
    try {
        poolSizeInt = Integer.parseInt(poolSize);
    } catch (NumberFormatException nfe) {
        parserContext.getReaderContext().error("An invalid value for max-parser-pool-size was supplied",
                element);
    }

    final String replayCacheLife = element.getAttribute("replay-cache-life-in-millis");
    try {
        replayCacheDuration = Integer.parseInt(replayCacheLife);
    } catch (NumberFormatException nfe) {
        parserContext.getReaderContext().error("An invalid value for replay-cache-life-in-millis was supplied",
                element);
    }

    final String clockSkew = element.getAttribute("issue-instant-check-clock-skew-in-secs");
    try {
        newClockSkew = Integer.parseInt(clockSkew);
    } catch (NumberFormatException nfe) {
        parserContext.getReaderContext()
                .error("An invalid value for issue-instant-check-clock-skew-in-secs was supplied", element);
    }

    final String validTime = element.getAttribute("issue-instant-check-valid-time-in-secs");
    try {
        newExpires = Integer.parseInt(validTime);
    } catch (NumberFormatException nfe) {
        parserContext.getReaderContext()
                .error("An invalid value for issue-instant-check-valid-time-in-secs was supplied", element);
    }

    BeanDefinitionBuilder bootstrapBean = BeanDefinitionBuilder.genericBeanDefinition(DefaultBootstrap.class);
    bootstrapBean.setInitMethodName("bootstrap");
    parserContext.getRegistry().registerBeanDefinition(BEAN_SAMLINITIALIZER, bootstrapBean.getBeanDefinition());

    final BasicParserPool basicParserPool = new BasicParserPool();
    basicParserPool.setMaxPoolSize(poolSizeInt);

    final HTTPPostSimpleSignDecoder httpPostSimpleSignDecoder = new HTTPPostSimpleSignDecoder(basicParserPool);

    final VelocityEngineFactoryBean velocityEngineFactoryBean = new VelocityEngineFactoryBean();
    velocityEngineFactoryBean.setPreferFileSystemAccess(false);
    Properties velocityEngineProperties = new Properties();
    velocityEngineProperties.setProperty("resource.loader", "classpath");
    velocityEngineProperties.setProperty("classpath.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    velocityEngineFactoryBean.setVelocityProperties(velocityEngineProperties);
    VelocityEngine velocityEngine = null;
    try {
        velocityEngine = velocityEngineFactoryBean.createVelocityEngine();
    } catch (IOException e) {
        throw new RuntimeException("Unable to create velocity engine instance");
    }

    // Replay cache
    BeanDefinitionBuilder replayCacheBuilder = BeanDefinitionBuilder.genericBeanDefinition(ReplayCache.class);
    replayCacheBuilder.addConstructorArgValue(new MapBasedStorageService());
    replayCacheBuilder.addConstructorArgValue(replayCacheDuration);
    parserContext.getRegistry().registerBeanDefinition(BEAN_REPLAYCACHE,
            replayCacheBuilder.getBeanDefinition());

    // Message replay rule
    BeanDefinitionBuilder messageReplayRuleBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(MessageReplayRule.class);
    messageReplayRuleBuilder.addConstructorArgReference(BEAN_REPLAYCACHE);
    parserContext.getRegistry().registerBeanDefinition("messageReplayRule",
            messageReplayRuleBuilder.getBeanDefinition());

    // Issue instant rule
    BeanDefinitionBuilder issueInstantBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(IssueInstantRule.class);
    issueInstantBuilder.addConstructorArgValue(newClockSkew);
    issueInstantBuilder.addConstructorArgValue(newExpires);
    parserContext.getRegistry().registerBeanDefinition("issueInstantRule",
            issueInstantBuilder.getBeanDefinition());

    // KeyStore Credential Resolver
    BeanDefinitionBuilder keyStoreBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(KeyStoreCredentialResolverDelegate.class);
    keyStoreBuilder.addPropertyReference("keyStore", certificatestoreRef);
    parserContext.getRegistry().registerBeanDefinition(BEAN_KEYSTORECREDENTIALRESOLVER,
            keyStoreBuilder.getBeanDefinition());

    // Signature Rule Builder
    BeanDefinitionBuilder signatureRuleBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(SignatureSecurityPolicyRule.class);
    signatureRuleBuilder.addConstructorArgValue(new SAMLSignatureProfileValidator());
    signatureRuleBuilder.addPropertyReference("credentialResolver", BEAN_KEYSTORECREDENTIALRESOLVER);

    // List of rule beans
    final ManagedList<BeanMetadataElement> beanMetadataElements = new ManagedList<BeanMetadataElement>();
    beanMetadataElements.add(signatureRuleBuilder.getBeanDefinition());
    beanMetadataElements.add(issueInstantBuilder.getBeanDefinition());
    beanMetadataElements.add(messageReplayRuleBuilder.getBeanDefinition());

    // Security Policy
    BeanDefinitionBuilder securityPolicyDelegateBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(SecurityPolicyDelegate.class);
    securityPolicyDelegateBuilder.addConstructorArgValue(beanMetadataElements);
    parserContext.getRegistry().registerBeanDefinition(BEAN_SECURITYPOLICY,
            securityPolicyDelegateBuilder.getBeanDefinition());

    // Security Policy Resolver
    BeanDefinitionBuilder securityPolicyResolverBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(StaticSecurityPolicyResolver.class);
    securityPolicyResolverBuilder.addConstructorArgReference(BEAN_SECURITYPOLICY);
    parserContext.getRegistry().registerBeanDefinition(BEAN_SECURITYPOLICYRESOLVER,
            securityPolicyResolverBuilder.getBeanDefinition());

    // Message Handler
    BeanDefinitionBuilder postBindingAdapter = BeanDefinitionBuilder
            .rootBeanDefinition(SAMLMessageHandlerImpl.class);
    postBindingAdapter.addConstructorArgValue(httpPostSimpleSignDecoder);
    postBindingAdapter.addConstructorArgReference(BEAN_SECURITYPOLICYRESOLVER);
    postBindingAdapter.addPropertyValue("velocityEngine", velocityEngine);
    postBindingAdapter.addPropertyValue("entityId", entityID);
    parserContext.getRegistry().registerBeanDefinition(messageHandlerRef,
            postBindingAdapter.getBeanDefinition());

    // Assertion Consumer Bean
    BeanDefinitionBuilder assertionComsumerBean = BeanDefinitionBuilder
            .genericBeanDefinition(AssertionConsumerImpl.class);
    assertionComsumerBean.addPropertyReference("provisioner", provisionerRef);
    parserContext.getRegistry().registerBeanDefinition(BEAN_ASSERTIONCONSUMER,
            assertionComsumerBean.getBeanDefinition());

    BeanDefinitionBuilder authenticationProvider = BeanDefinitionBuilder
            .rootBeanDefinition(SAMLResponseAuthenticationProvider.class);
    authenticationProvider.addConstructorArgReference(BEAN_ASSERTIONCONSUMER);
    parserContext.getRegistry().registerBeanDefinition(BEAN_AUTHENTICATIONPROVIDER,
            authenticationProvider.getBeanDefinition());

    // Pre Auth Filter
    final HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
    final AuthenticationFailureHandlerImpl authenticationFailureHandler = new AuthenticationFailureHandlerImpl(
            requestCache);

    // Authentication Filter
    BeanDefinitionBuilder authenticationFilter = BeanDefinitionBuilder
            .rootBeanDefinition(SAMLResponseAuthenticationProcessingFilter.class);
    authenticationFilter.addConstructorArgValue(assertionConsumerURI);
    authenticationFilter.addPropertyReference("SAMLMessageHandler", messageHandlerRef);
    authenticationFilter.addPropertyReference("authenticationManager", authenticationManangerRef);
    authenticationFilter.addPropertyValue("authenticationFailureHandler", authenticationFailureHandler);
    parserContext.getRegistry().registerBeanDefinition(preAuthFilterRef,
            authenticationFilter.getBeanDefinition());

    return authenticationProvider.getBeanDefinition();
}

From source file:org.josso.spring.security.JOSSOAuthenticationFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    if (!(servletRequest instanceof HttpServletRequest)) {
        throw new IllegalArgumentException("Non HTTP request unsupported by this filter");
    }/*from  www  .  ja  v a  2 s  . c  om*/

    if (!(servletResponse instanceof HttpServletResponse)) {
        throw new IllegalArgumentException("Non HTTP response unsupported by this filter");
    }

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    // We have to provide Authentication information based on JOSSO auth information ...

    // Obtain a JOSSO security context instance, if none is found is because user has not been authenticated.
    JOSSOSecurityContext sctx = WebAccessControlUtil.getSecurityContext((HttpServletRequest) request);

    logger.debug("Current JOSSO Security Context is " + sctx);

    // This is the authentication information used by ACEGI
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    // If authentication information is present, we only need to validate that it is up to date.
    if (authentication != null) {

        if (logger.isDebugEnabled()) {
            logger.debug("Authentication information already present : '"
                    + SecurityContextHolder.getContext().getAuthentication() + "'");
        }

        // If there is no principal, we may need to logout this user ... TODO detect anonymous principals ?
        if (sctx == null && authentication.isAuthenticated()) {

            // If an authenticated Authentication is present, we must issue a logout !
            if (logger.isDebugEnabled()) {
                logger.debug("Logging out user '" + authentication + "'");
            }

            for (int i = 0; i < handlers.length; i++) {
                handlers[i].logout(request, response, authentication);
            }

        }

        chain.doFilter(request, response);

        return;
    }

    // We have a principal but no Spring Security authentication, propagate identity from JOSSO to Spring Security.
    if (sctx != null) {

        // If a saved request is present, we use the saved request to redirect the user to the original resource.
        SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);

        if (savedRequest != null)
            logger.debug("Redirecting to original resource " + savedRequest.getRedirectUrl());

        UserDetails userDetails = userDetailsService.loadUserByUsername(sctx.getSSOSession());
        //            String jossoSessionId = (String) request.getAttribute("org.josso.agent.ssoSessionid");

        // New authenticated autentication instance.
        Authentication jossoAuth = new JOSSOAuthenticationToken(sctx.getSSOSession(), userDetails,
                userDetails.getAuthorities());

        // Store to SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(jossoAuth);
        if (logger.isDebugEnabled()) {
            logger.debug("SecurityContextHolder populated with JOSSO Authentication Token: '"
                    + SecurityContextHolder.getContext().getAuthentication() + "'");
        }

        // Fire event
        if (this.eventPublisher != null) {
            eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
                    SecurityContextHolder.getContext().getAuthentication(), this.getClass()));
        }

        // We have a saved request, redirect to original URL ...
        if (savedRequest != null)
            response.sendRedirect(savedRequest.getRedirectUrl());

    } else {
        if (logger.isDebugEnabled())
            logger.debug("No principal found in request !");

    }

    // Move on ...
    chain.doFilter(request, response);

}

From source file:org.orcid.frontend.web.controllers.OauthConfirmAccessController.java

@RequestMapping(value = { "/signin", "/login" }, method = RequestMethod.GET)
public ModelAndView loginGetHandler2(HttpServletRequest request, HttpServletResponse response,
        ModelAndView mav) {//from  w  w  w  .ja  v  a 2s .c  om
    // find client name if available
    SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
    String clientName = "";
    String clientId = "";
    String clientGroupName = "";
    String email = "";
    String clientDescription = "";
    String scope = "";
    String redirectUri = "";
    String responseType = "";
    String orcid = null;
    boolean showLogin = false; // default to Reg
    boolean usePersistentTokens = false;
    if (savedRequest != null) {
        String url = savedRequest.getRedirectUrl();
        if (url.toLowerCase().contains("show_login=true"))
            showLogin = true;
        //TODO: We should not load any info in the freemarker ModelAndViewObject, we should move all info we need to the forms
        Matcher matcher = clientIdPattern.matcher(url);
        if (matcher.find()) {
            clientId = matcher.group(1);
            if (clientId != null) {
                try {
                    clientId = URLDecoder.decode(clientId, "UTF-8").trim();
                } catch (UnsupportedEncodingException e) {
                }
                Matcher emailMatcher = RegistrationController.emailPattern.matcher(url);
                if (emailMatcher.find()) {
                    String tempEmail = emailMatcher.group(1);
                    try {
                        tempEmail = URLDecoder.decode(tempEmail, "UTF-8").trim();
                    } catch (UnsupportedEncodingException e) {
                    }
                    if (orcidProfileManager.emailExists(tempEmail))
                        email = tempEmail;
                }

                Matcher orcidMatcher = orcidPattern.matcher(url);
                if (orcidMatcher.find()) {
                    String tempOrcid = orcidMatcher.group(2);
                    try {
                        tempOrcid = URLDecoder.decode(tempOrcid, "UTF-8").trim();
                    } catch (UnsupportedEncodingException e) {
                    }
                    if (orcidProfileManager.exists(tempOrcid))
                        orcid = tempOrcid;
                }

                Matcher scopeMatcher = scopesPattern.matcher(url);
                if (scopeMatcher.find()) {
                    scope = scopeMatcher.group(1);
                    try {
                        scope = URLDecoder.decode(scope, "UTF-8").trim();
                        scope = scope.replaceAll(" +", " ");
                    } catch (UnsupportedEncodingException e) {
                    }
                }

                Matcher redirectUriMatcher = redirectUriPattern.matcher(url);
                if (redirectUriMatcher.find()) {
                    try {
                        redirectUri = URLDecoder.decode(redirectUriMatcher.group(1), "UTF-8").trim();
                    } catch (UnsupportedEncodingException e) {
                    }
                }

                Matcher responseTypeMatcher = responseTypePattern.matcher(url);
                if (responseTypeMatcher.find()) {
                    responseType = responseTypeMatcher.group(1);
                    try {
                        responseType = URLDecoder.decode(responseType, "UTF-8").trim();
                    } catch (UnsupportedEncodingException e) {
                    }
                }

                // Get client name
                ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);

                // Check if the client has persistent tokens enabled
                if (clientDetails.isPersistentTokensEnabled())
                    usePersistentTokens = true;

                // validate client scopes
                try {
                    authorizationEndpoint.validateScope(scope, clientDetails);
                    orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
                } catch (InvalidScopeException ise) {
                    String redirectUriWithParams = redirectUri;
                    redirectUriWithParams += "?error=invalid_scope&error_description=" + ise.getMessage();
                    RedirectView rView = new RedirectView(redirectUriWithParams);

                    ModelAndView error = new ModelAndView();
                    error.setView(rView);
                    return error;
                } catch (LockedException le) {
                    String redirectUriWithParams = redirectUri;
                    redirectUriWithParams += "?error=client_locked&error_description=" + le.getMessage();
                    RedirectView rView = new RedirectView(redirectUriWithParams);

                    ModelAndView error = new ModelAndView();
                    error.setView(rView);
                    return error;
                }
                // If client details is ok, continue
                clientName = clientDetails.getClientName() == null ? "" : clientDetails.getClientName();
                clientDescription = clientDetails.getClientDescription() == null ? ""
                        : clientDetails.getClientDescription();

                // If client type is null it means it is a public client
                if (clientDetails.getClientType() == null) {
                    clientGroupName = PUBLIC_MEMBER_NAME;
                } else if (!PojoUtil.isEmpty(clientDetails.getGroupProfileId())) {
                    ProfileEntity groupProfile = profileEntityCacheManager
                            .retrieve(clientDetails.getGroupProfileId());
                    clientGroupName = groupProfile.getCreditName();
                }
                // If the group name is empty, use the same as the client
                // name, since it should be a SSO user
                if (StringUtils.isBlank(clientGroupName)) {
                    clientGroupName = clientName;
                }
            }
        }
    }
    mav.addObject("scopes", ScopePathType.getScopesFromSpaceSeparatedString(scope));
    mav.addObject("scopesString", scope);
    mav.addObject("redirect_uri", redirectUri);
    mav.addObject("response_type", responseType);
    mav.addObject("client_name", clientName);
    mav.addObject("client_id", clientId);
    mav.addObject("client_group_name", clientGroupName);
    mav.addObject("client_description", clientDescription);
    mav.addObject("userId", orcid != null ? orcid : email);
    mav.addObject("hideUserVoiceScript", true);
    mav.addObject("usePersistentTokens", usePersistentTokens);
    mav.addObject("showLogin", String.valueOf(showLogin));
    mav.setViewName("oauth_login");
    return mav;
}

From source file:org.orcid.frontend.web.controllers.OauthConfirmAccessController.java

@RequestMapping(value = { "/custom/signin.json", "/custom/login.json" }, method = RequestMethod.POST)
public @ResponseBody OauthAuthorizeForm authenticateAndAuthorize(HttpServletRequest request,
        HttpServletResponse response, @RequestBody OauthAuthorizeForm form) {
    // Clean form errors
    form.setErrors(new ArrayList<String>());
    boolean willBeRedirected = false;

    if (form.getApproved()) {
        // Validate name and password
        validateUserNameAndPassword(form);
        if (form.getErrors().isEmpty()) {
            try {
                // Authenticate user
                Authentication auth = authenticateUser(request, form);
                // Create authorization params
                SimpleSessionStatus status = new SimpleSessionStatus();
                Map<String, Object> model = new HashMap<String, Object>();
                Map<String, String> params = new HashMap<String, String>();
                Map<String, String> approvalParams = new HashMap<String, String>();

                // Set params
                setOauthParams(form, params, approvalParams, false);

                // Authorize
                try {
                    authorizationEndpoint.authorize(model, params, status, auth);
                } catch (RedirectMismatchException rUriError) {
                    String redirectUri = this.getBaseUri() + REDIRECT_URI_ERROR;
                    // Set the client id
                    redirectUri = redirectUri.replace("{0}", form.getClientId().getValue());
                    // Set the response type if needed
                    if (!PojoUtil.isEmpty(form.getResponseType()))
                        redirectUri += "&response_type=" + form.getResponseType().getValue();
                    // Set the redirect uri
                    if (!PojoUtil.isEmpty(form.getRedirectUri()))
                        redirectUri += "&redirect_uri=" + form.getRedirectUri().getValue();
                    // Set the scope param
                    if (!PojoUtil.isEmpty(form.getScope()))
                        redirectUri += "&scope=" + form.getScope().getValue();
                    // Copy the state param if present
                    if (params != null && params.containsKey("state"))
                        redirectUri += "&state=" + params.get("state");
                    form.setRedirectUri(Text.valueOf(redirectUri));
                    LOGGER.info(/*  w ww .  ja v  a2 s.  c om*/
                            "OauthConfirmAccessController form.getRedirectUri being sent to client browser: "
                                    + form.getRedirectUri());
                    return form;
                }
                // Approve
                RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model,
                        status, auth);
                form.setRedirectUri(Text.valueOf(view.getUrl()));
                willBeRedirected = true;
            } catch (AuthenticationException ae) {
                form.getErrors().add(getMessage("orcid.frontend.security.bad_credentials"));
            }
        }
    } else {
        String stateParam = null;

        if (!PojoUtil.isEmpty(form.getStateParam())) {
            stateParam = form.getStateParam().getValue();
        }
        form.setRedirectUri(Text.valueOf(buildDenyRedirectUri(form.getRedirectUri().getValue(), stateParam)));
        willBeRedirected = true;
    }

    // If there was an authentication error, dont log since the user will
    // not be redirected yet
    if (willBeRedirected) {
        SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
        if (savedRequest != null)
            LOGGER.info("OauthConfirmAccessController original request: " + savedRequest.getRedirectUrl());
        LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: "
                + form.getRedirectUri());
    }
    return form;
}

From source file:org.orcid.frontend.web.controllers.OauthConfirmAccessController.java

/**
 * Fill the for with the state param and the client and member names.
 * //  w  ww. j a  v  a 2  s.co m
 * @param form
 * @param request
 * @param response
 * */
private void fillOauthFormWithRequestInformation(OauthForm form, HttpServletRequest request,
        HttpServletResponse response) {
    Map<String, String[]> requestParams = new HashMap<String, String[]>();
    SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);

    //Get the params from the saved request
    if (savedRequest != null) {
        requestParams = savedRequest.getParameterMap();
    } else {
        //If there are no saved request, get them from the session
        AuthorizationRequest authorizationRequest = (AuthorizationRequest) request.getSession()
                .getAttribute("authorizationRequest");
        Map<String, String> authRequestParams = new HashMap<String, String>(
                authorizationRequest.getRequestParameters());
        for (String param : authRequestParams.keySet()) {
            requestParams.put(param, new String[] { authRequestParams.get(param) });
        }
    }

    if (requestParams == null || requestParams.isEmpty()) {
        throw new InvalidRequestException("Unable to find parameters");
    }

    //Save state param
    if (requestParams.containsKey(OrcidOauth2Constants.STATE_PARAM)) {
        if (requestParams.get(OrcidOauth2Constants.STATE_PARAM).length > 0)
            form.setStateParam(Text.valueOf(requestParams.get(OrcidOauth2Constants.STATE_PARAM)[0]));
    }

    //Get and set client info
    if (!requestParams.containsKey(OrcidOauth2Constants.CLIENT_ID_PARAM)) {
        throw new InvalidRequestException("Empty client id");
    }
    String clientId = requestParams.get(OrcidOauth2Constants.CLIENT_ID_PARAM)[0];
    try {
        clientId = URLDecoder.decode(clientId, "UTF-8").trim();
    } catch (UnsupportedEncodingException e) {
        throw new InvalidRequestException("Unable to parse client id: " + e);
    }

    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
    try {
        orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
    } catch (LockedException le) {
        throw new InvalidRequestException("Client " + clientId + " is locked");
    }

    String clientName = clientDetails.getClientName() == null ? "" : clientDetails.getClientName();
    String memberName = null;
    // If it is the 
    if (ClientType.PUBLIC_CLIENT.equals(clientDetails.getClientType())) {
        memberName = PUBLIC_MEMBER_NAME;
    } else {
        ProfileEntity groupProfile = profileEntityCacheManager.retrieve(clientDetails.getGroupProfileId());
        memberName = groupProfile.getCreditName();
    }

    form.setClientName(Text.valueOf(clientName));
    form.setMemberName(Text.valueOf(memberName));
    form.setClientId(Text.valueOf(clientId));

    //If it is a new registration, set the referred by flag
    if (form instanceof OauthRegistrationForm) {
        ((OauthRegistrationForm) form).setReferredBy(Text.valueOf(clientId));
    }
}

From source file:org.orcid.frontend.web.controllers.OauthConfirmAccessController.java

@RequestMapping(value = "/custom/register.json", method = RequestMethod.POST)
public @ResponseBody OauthRegistrationForm checkRegisterForm(HttpServletRequest request,
        HttpServletResponse response, @RequestBody OauthRegistrationForm form) {
    form.setErrors(new ArrayList<String>());

    if (form.getApproved()) {
        registrationController.validateRegistrationFields(request, form);
        registrationController.validateGrcaptcha(request, form);
    } else {//w  ww. j a  v a2 s  . c  o m
        SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
        String stateParam = null;

        if (savedRequest != null && savedRequest.getParameterMap() != null
                && savedRequest.getParameterValues("state") != null) {
            if (savedRequest.getParameterValues("state").length > 0)
                stateParam = savedRequest.getParameterValues("state")[0];
        }
        form.setRedirectUri(Text.valueOf(buildDenyRedirectUri(form.getRedirectUri().getValue(), stateParam)));
    }

    return form;
}

From source file:org.orcid.frontend.web.controllers.OauthConfirmAccessController.java

@RequestMapping(value = "/custom/registerConfirm.json", method = RequestMethod.POST)
public @ResponseBody OauthRegistrationForm registerAndAuthorize(HttpServletRequest request,
        HttpServletResponse response, @RequestBody OauthRegistrationForm form) {
    if (form.getApproved()) {
        boolean usedCaptcha = false;

        // If recatcha wasn't loaded do nothing. This is for countries that
        // block google.
        if (form.getGrecaptchaWidgetId().getValue() != null) {
            // If the captcha verified key is not in the session, redirect
            // to
            // the login page
            if (request.getSession()
                    .getAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME) == null
                    || PojoUtil.isEmpty(form.getGrecaptcha())
                    || !encryptionManager.encryptForExternalUse(form.getGrecaptcha().getValue())
                            .equals(request.getSession()
                                    .getAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME))) {
                String redirectUri = this.getBaseUri() + REDIRECT_URI_ERROR;
                // Set the client id
                redirectUri = redirectUri.replace("{0}", form.getClientId().getValue());
                // Set the response type if needed
                if (!PojoUtil.isEmpty(form.getResponseType()))
                    redirectUri += "&response_type=" + form.getResponseType().getValue();
                // Set the redirect uri
                if (!PojoUtil.isEmpty(form.getRedirectUri()))
                    redirectUri += "&redirect_uri=" + form.getRedirectUri().getValue();
                // Set the scope param
                if (!PojoUtil.isEmpty(form.getScope()))
                    redirectUri += "&scope=" + form.getScope().getValue();
                // Copy the state param if present
                if (!PojoUtil.isEmpty(request.getParameter("state")))
                    redirectUri += "&state=" + request.getParameter("state");
                form.setRedirectUri(Text.valueOf(redirectUri));
                SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
                if (savedRequest != null)
                    LOGGER.info(//from  ww  w . ja v  a2 s .  co m
                            "OauthConfirmAccessController original request: " + savedRequest.getRedirectUrl());
                LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: "
                        + form.getRedirectUri());
                return form;
            }

            usedCaptcha = true;
        }

        // Remove the session hash if needed
        if (request.getSession()
                .getAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME) != null) {
            request.getSession().removeAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME);
        }

        // Check there are no errors
        registrationController.validateRegistrationFields(request, form);
        if (form.getErrors().isEmpty()) {
            // Register user
            registrationController.createMinimalRegistration(request,
                    RegistrationController.toProfile(form, request), usedCaptcha);
            // Authenticate user
            String email = form.getEmail().getValue();
            String password = form.getPassword().getValue();
            Authentication auth = authenticateUser(request, email, password);
            // Create authorization params
            SimpleSessionStatus status = new SimpleSessionStatus();
            Map<String, Object> model = new HashMap<String, Object>();
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String> approvalParams = new HashMap<String, String>();
            // Set params
            setOauthParams(form, params, approvalParams, true);

            // Authorize
            try {
                authorizationEndpoint.authorize(model, params, status, auth);
            } catch (RedirectMismatchException rUriError) {
                String redirectUri = this.getBaseUri() + REDIRECT_URI_ERROR;
                // Set the client id
                redirectUri = redirectUri.replace("{0}", form.getClientId().getValue());
                // Set the response type if needed
                if (!PojoUtil.isEmpty(form.getResponseType()))
                    redirectUri += "&response_type=" + form.getResponseType().getValue();
                // Set the redirect uri
                if (!PojoUtil.isEmpty(form.getRedirectUri()))
                    redirectUri += "&redirect_uri=" + form.getRedirectUri().getValue();
                // Set the scope param
                if (!PojoUtil.isEmpty(form.getScope()))
                    redirectUri += "&scope=" + form.getScope().getValue();
                // Copy the state param if present
                if (params != null && params.containsKey("state"))
                    redirectUri += "&state=" + params.get("state");
                form.setRedirectUri(Text.valueOf(redirectUri));
                LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: "
                        + form.getRedirectUri());
                return form;
            }
            // Approve
            RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model,
                    status, auth);
            form.setRedirectUri(Text.valueOf(view.getUrl()));
        }
    } else {
        form.setRedirectUri(Text.valueOf(
                buildDenyRedirectUri(form.getRedirectUri().getValue(), request.getParameter("state"))));
    }

    SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
    if (savedRequest != null) {
        if (savedRequest != null)
            LOGGER.info("OauthConfirmAccessController original request: " + savedRequest.getRedirectUrl());
        LOGGER.info("OauthConfirmAccessController original request: " + savedRequest.getRedirectUrl());
    }
    LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: "
            + form.getRedirectUri());
    return form;
}

From source file:org.orcid.frontend.web.controllers.OauthConfirmAccessController.java

@RequestMapping(value = { "/custom/authorize.json" }, method = RequestMethod.POST)
public @ResponseBody OauthAuthorizeForm authorize(HttpServletRequest request, HttpServletResponse response,
        @RequestBody OauthAuthorizeForm 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 {/* www  .ja va 2  s.co  m*/
        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(form.getClientId().getValue()))
        // Then check if the client granted the persistent token
        if (form.getPersistentTokenEnabled())
            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
    RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
    form.setRedirectUri(Text.valueOf(view.getUrl()));
    SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
    if (savedRequest != null)
        LOGGER.info("OauthConfirmAccessController original request: " + savedRequest.getRedirectUrl());
    LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: "
            + form.getRedirectUri());
    return form;
}

From source file:org.orcid.frontend.web.controllers.RegistrationController.java

@RequestMapping(value = "/register.json", method = RequestMethod.GET)
public @ResponseBody Registration getRegister(HttpServletRequest request, HttpServletResponse response) {
    // Remove the session hash if needed
    if (request.getSession().getAttribute(GRECAPTCHA_SESSION_ATTRIBUTE_NAME) != null) {
        request.getSession().removeAttribute(GRECAPTCHA_SESSION_ATTRIBUTE_NAME);
    }//from  ww  w.j  ava2s .  co m
    Registration reg = new Registration();

    reg.getEmail().setRequired(true);

    reg.getEmailConfirm().setRequired(true);

    reg.getPassword();
    reg.getPasswordConfirm();
    reg.getEmail();

    reg.getFamilyNames().setRequired(false);

    reg.getGivenNames().setRequired(true);

    reg.getSendChangeNotifications().setValue(true);
    reg.getSendOrcidNews().setValue(true);
    reg.getSendMemberUpdateRequests().setValue(true);
    reg.getSendEmailFrequencyDays().setValue(SendEmailFrequency.WEEKLY.value());
    reg.getTermsOfUse().setValue(false);
    setError(reg.getTermsOfUse(), "AssertTrue.registrationForm.acceptTermsAndConditions");

    SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
    if (savedRequest != null) {
        String url = savedRequest.getRedirectUrl();

        Matcher emailMatcher = emailPattern.matcher(url);
        if (emailMatcher.find()) {
            String tempEmail = emailMatcher.group(1);
            try {
                tempEmail = URLDecoder.decode(tempEmail, "UTF-8");
            } catch (UnsupportedEncodingException e) {
            }
            if (!orcidProfileManager.emailExists(tempEmail)) {
                reg.getEmail().setValue(tempEmail);
            }
        }

        Matcher givenNamesMatcher = givenNamesPattern.matcher(url);
        if (givenNamesMatcher.find())
            try {
                reg.getGivenNames().setValue(URLDecoder.decode(givenNamesMatcher.group(1), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                LOGGER.info("error parsing users family name from oauth url", e);
            }

        Matcher familyNamesMatcher = familyNamesPattern.matcher(url);
        if (familyNamesMatcher.find())
            try {
                reg.getFamilyNames().setValue(URLDecoder.decode(familyNamesMatcher.group(1), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                LOGGER.info("error parsing users family name from oauth url", e);
            }
    }
    long numVal = generateRandomNumForValidation();
    reg.setValNumServer(numVal);
    reg.setValNumClient(0);
    return reg;
}