This method handle formlogin; If the SSO cookie exist, then it will use the cookie to authenticate. If
the cookie does not exist, then it will re-redirect to the login page.

@param req
@param res
@param enableRedirect
@return
760710
private AuthenticationResult handleFormLogin(HttpServletRequest req, HttpServletResponse res, WebRequest webRequest) {
        AuthenticationResult authResult = null;
        authResult = ssoAuthenticator.authenticate(webRequest);

        if (authResult != null) {
            authResult.setAuditCredType(AuditEvent.CRED_TYPE_FORM);
        }

        if (authResult != null && authResult.getStatus() != AuthResult.FAILURE) {
            postParameterHelper.restore(req, res);
            return authResult;
        }

        try {
            authResult = providerAuthenticatorProxy.authenticate(req, res, null);
        } catch (Exception e) {
            return new AuthenticationResult(AuthResult.FAILURE, e.getLocalizedMessage());
        }

        if (authResult.getStatus() == AuthResult.CONTINUE) {
            authResult = null;
            if (webRequest.isFormLoginRedirectEnabled()) {
                authResult = handleRedirect(req, res, webRequest);
                if (authResult != null) {
                    authResult.setAuditCredType(AuditEvent.CRED_TYPE_FORM);
                    authResult.setAuditOutcome(AuditEvent.OUTCOME_REDIRECT);
                }

            }
        }
        return authResult;
    }
870047
def authorized_default_handler(resp, remote, *args, **kwargs):
    
    response_token_setter(remote, resp)
    db.session.commit()
    return redirect(url_for('invenio_oauthclient_settings.index'))
485159
def login(request, template_name=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, extra_context=None):
    
    redirect_to = request.POST.get(
        redirect_field_name,
        request.GET.get(redirect_field_name, '')
    )

    def get_redirect_to():
        # Ensure the user-originating redirection url is safe.
        if not is_safe_url(url=redirect_to, host=request.get_host()):
            return resolve_url(settings.LOGIN_REDIRECT_URL)
        return redirect_to

    if request.user.is_authenticated:
        return HttpResponseRedirect(get_redirect_to())

    if request.method == "POST":
        form = authentication_form(request=request, data=request.POST)
        if form.is_valid():

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            return HttpResponseRedirect(get_redirect_to())
    else:
        form = authentication_form(request=request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)

    if current_app is not None:
        request.current_app = current_app

    return TemplateResponse(request, template_name, context)
204286
function(req, res) {
    var params = URL.parse(req.url, true).query;
    var oauth2_server_id = params.provider || this.config.default_server;
    var next_url = this.nexturl_query(req, params);
    this.redirects_for_login(oauth2_server_id, res, next_url);
  }
786743
public String getJavaScriptForRedirect(String reqUrlCookieName, String redirectUrl) throws Exception {
        return getJavaScriptForRedirect(reqUrlCookieName, redirectUrl, null);
    }
321687
def sso_entry(request):
    
    if request.method == 'POST':
        passed_data = request.POST
        binding = BINDING_HTTP_POST
    else:
        passed_data = request.GET
        binding = BINDING_HTTP_REDIRECT

    request.session['Binding'] = binding

    try:
        request.session['SAMLRequest'] = passed_data['SAMLRequest']
    except (KeyError, MultiValueDictKeyError) as e:
        return HttpResponseBadRequest(e)
    request.session['RelayState'] = passed_data.get('RelayState', '')
    # TODO check how the redirect saml way works. Taken from example idp in pysaml2.
    if "SigAlg" in passed_data and "Signature" in passed_data:
        request.session['SigAlg'] = passed_data['SigAlg']
        request.session['Signature'] = passed_data['Signature']
    return HttpResponseRedirect(reverse('djangosaml2idp:saml_login_process'))
505824
@GET
    @Path("create")
    public Response createFromRedirect() {
        KeycloakPrincipal principal = (KeycloakPrincipal) sessionContext.getCallerPrincipal();
        RefreshableKeycloakSecurityContext kcSecurityContext = (RefreshableKeycloakSecurityContext)
                principal.getKeycloakSecurityContext();

        String refreshToken = kcSecurityContext.getRefreshToken();
        Token token = create(refreshToken);
        try {
            String redirectTo = System.getProperty("secretstore.redirectTo");

            if (null == redirectTo || redirectTo.isEmpty()) {
                return Response.ok("Redirect URL was not specified but token was created.").build();
            }

            URI location;
            if (redirectTo.toLowerCase().startsWith("http")) {
                location = new URI(redirectTo);
            } else {
                URI uri = uriInfo.getAbsolutePath();
                String newPath = redirectTo.replace("{tokenId}", token.getId().toString());
                location = new URI(
                        uri.getScheme(),
                        uri.getUserInfo(),
                        uri.getHost(),
                        uri.getPort(),
                        newPath,
                        uri.getQuery(),
                        uri.getFragment()
                );
            }

            return Response.seeOther(location).build();
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return Response.ok("Could not redirect back to the original URL, but token was created.").build();
        }
    }
532727
def login(self, request, extra_context=None):
        
        redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME))

        if not redirect_to or not is_safe_url(url=redirect_to, allowed_hosts=[request.get_host()]):
            redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

        return redirect_to_login(redirect_to)
1287489
def convert(request, form_class=None,
            redirect_field_name='redirect_to',
            anonymous_redirect=settings.LOGIN_URL,
            template_name='lazysignup/convert.html',
            ajax_template_name='lazysignup/convert_ajax.html'):
    
    redirect_to = 'lazysignup_convert_done'

    if form_class is None:
        if constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM is not None:
            form_class = import_string(constants.LAZYSIGNUP_CUSTOM_USER_CREATION_FORM)
        else:
            form_class = UserCreationForm

    # If we've got an anonymous user, redirect to login
    if request.user.is_anonymous:
        return HttpResponseRedirect(anonymous_redirect)

    if request.method == 'POST':
        redirect_to = request.POST.get(redirect_field_name) or redirect_to
        form = form_class(request.POST, instance=request.user)
        if form.is_valid():
            try:
                LazyUser.objects.convert(form)
            except NotLazyError:
                # If the user already has a usable password, return a Bad
                # Request to an Ajax client, or just redirect back for a
                # regular client.
                if request.is_ajax():
                    return HttpResponseBadRequest(
                        content=_(u"Already converted."))
                else:
                    return redirect(redirect_to)

            # Re-log the user in, as they'll now not be authenticatable with
            # the Lazy backend
            login(request, authenticate(**form.get_credentials()))

            # If we're being called via AJAX, then we just return a 200
            # directly to the client. If not, then we redirect to a
            # confirmation page or to redirect_to, if it's set.
            if request.is_ajax():
                return HttpResponse()
            else:
                return redirect(redirect_to)

        # Invalid form, now check to see if is an ajax call
        if request.is_ajax():
            return HttpResponseBadRequest(content=str(form.errors))
    else:
        form = form_class()

    # If this is an ajax request, prepend the ajax template to the list of
    # templates to be searched.
    if request.is_ajax():
        template_name = [ajax_template_name, template_name]
    return render(
        request,
        template_name,
        {
            'form': form,
            'redirect_to': redirect_to
        },
    )
519043
private String selectRedirectionUrl(HttpServletRequest request) {

        final String defaultRedirect = request.getContextPath() + "/";

        String rslt = null; // default

        // Get the person object associated with the request
        final IPerson person = this.personManager.getPerson(request);
        final String username = person != null ? person.getUserName() : "[unavailable]";

        if (person != null) {
            // Analyze the user's authentication status
            final ISecurityContext securityContext = person.getSecurityContext();
            if (securityContext.isAuthenticated() && StringUtils.isNotBlank(logoutRedirect)) {
                rslt = logoutRedirect;
            }
        }

        // Otherwise use a sensible default...
        rslt =
                rslt != null
                        ? urlCustomizer.customizeUrl(request, rslt)
                        : urlCustomizer.customizeUrl(request, defaultRedirect);

        logger.debug("Calculated redirectionURL='{}' for user='{}'", rslt, username);

        return rslt;
    }
141391
private void doClientSideRedirect(HttpServletResponse response, String loginURL, String state, String domain) throws IOException {

        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter pw = response.getWriter();
        pw.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        pw.println("<head>");

        pw.println(createJavaScriptForRedirect(loginURL, state, domain));

        pw.println("<title>Redirect To OP</title> ");
        pw.println("</head>");
        pw.println("<body></body>");
        pw.println("</html>");

        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private, max-age=0");
        // HTTP 1.0.
        response.setHeader("Pragma", "no-cache");
        // Proxies.
        response.setDateHeader("Expires", 0);
        response.setContentType("text/html; charset=UTF-8");

        pw.close();

    }
130811
def post(self, request, provider=None):
        
        # if settings.CAS_FEDERATE is not True redirect to the login page
        if not settings.CAS_FEDERATE:
            logger.warning("CAS_FEDERATE is False, set it to True to use federation")
            return redirect("cas_server:login")
        # POST with a provider suffix, this is probably an SLO request. csrf is disabled for
        # allowing SLO requests reception
        try:
            provider = FederatedIendityProvider.objects.get(suffix=provider)
            auth = self.get_cas_client(request, provider)
            try:
                auth.clean_sessions(request.POST['logoutRequest'])
            except (KeyError, AttributeError):
                pass
            return HttpResponse("ok")
        # else, a User is trying to log in using an identity provider
        except FederatedIendityProvider.DoesNotExist:
            # Manually checking for csrf to protect the code below
            reason = CsrfViewMiddleware().process_view(request, None, (), {})
            if reason is not None:  # pragma: no cover (csrf checks are disabled during tests)
                return reason  # Failed the test, stop here.
            form = forms.FederateSelect(request.POST)
            if form.is_valid():
                params = utils.copy_params(
                    request.POST,
                    ignore={"provider", "csrfmiddlewaretoken", "ticket", "lt"}
                )
                if params.get("renew") == "False":
                    del params["renew"]
                url = utils.reverse_params(
                    "cas_server:federateAuth",
                    kwargs=dict(provider=form.cleaned_data["provider"].suffix),
                    params=params
                )
                return HttpResponseRedirect(url)
            else:
                return redirect("cas_server:login")
1259060
private String getLoginURL(JaspiRequest jaspiRequest, HttpServletRequest req) {
        String loginURL = null;
        LoginConfiguration loginConfig = jaspiRequest.getLoginConfig();
        if (loginConfig != null) {
            FormLoginConfiguration formLoginConfig = loginConfig.getFormLoginConfiguration();
            if (formLoginConfig != null) {
                String formLoginPageURL = formLoginConfig.getLoginPage();
                StringBuilder builder = new StringBuilder(req.getRequestURL());
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "getFormURL", new Object[] { "formLoginPageURL=" + formLoginPageURL, " requestURL=" + builder });
                int hostIndex = builder.indexOf("//");
                int contextIndex = builder.indexOf("/", hostIndex + 2);
                builder.replace(contextIndex, builder.length(), normalizeURL(formLoginPageURL, req.getContextPath()));
                loginURL = builder.toString();
            }
        }
        return loginURL;
    }
406507
private void loginForm(HttpServletResponse response) {
        response.reset();
        response.addHeader("WWW-Authenticate",
                           "Basic realm=\"!!Fedora Repository Server\"");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
722889
def sso_redirect(request, scopes=list([]), return_to=None):
    
    logger.debug("Initiating redirect of {0} session {1}".format(request.user, request.session.session_key[:5]))
    if isinstance(scopes, string_types):
        scopes = list([scopes])

    # ensure only one callback redirect model per session
    CallbackRedirect.objects.filter(session_key=request.session.session_key).delete()

    # ensure session installed in database
    if not request.session.exists(request.session.session_key):
        logger.debug("Creating new session before redirect.")
        request.session.create()

    if return_to:
        url = reverse(return_to)
    else:
        url = request.get_full_path()

    oauth = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID, redirect_uri=app_settings.ESI_SSO_CALLBACK_URL, scope=scopes)
    redirect_url, state = oauth.authorization_url(app_settings.ESI_OAUTH_LOGIN_URL)

    CallbackRedirect.objects.create(session_key=request.session.session_key, state=state, url=url)
    logger.debug("Redirecting {0} session {1} to SSO. Callback will be redirected to {2}".format(request.user, request.session.session_key[:5], url))
    return redirect(redirect_url)
365878
public ValidationSessionInfo createSession(HttpServletRequest req, HttpServletResponse res) {
        String key = this.getSessionKey();
        ValidationSessionInfo sessionInfo = new ValidationSessionInfo(req, key);
        this.sessionMap.put(key, sessionInfo);
        res.addCookie(new Cookie("AuthToken", key));
        return sessionInfo;
    }
1356803
def redirect(to, *args, **kwargs):
    
    params = kwargs.pop('params', {})

    try:
        to = reverse(to, args=args, kwargs=kwargs)
    except NoReverseMatch:
        if '/' not in to and '.' not in to:
            to = reverse('cas_login')
        elif not service_allowed(to):
            raise PermissionDenied()

    if params:
        to = add_query_params(to, params)

    logger.debug("Redirecting to %s" % to)
    return HttpResponseRedirect(to)