This action will ask for authorization and redirect user back to referer

@Route("/authenticate", name="ed_blog_redirect_authenticate")
970229
public function authenticateAction(Request $request)
    {
        if(!$this->getUser())
        {
            //Get redirecting route
            $referer = $request->headers->get('referer');
            //Get section on the page to be redirected at
            $pageSection = $request->get('section', false);

            $this->get('session')->set('refererUrl', $referer);

            if($pageSection)
            {
                $this->get('session')->set('refererUrlSection', $pageSection);
            }
        }

        $user = $this->get('security.token_storage')->getToken()->getUser();
        if (!is_object($user) || !$user instanceof UserInterface)
        {
            throw new AccessDeniedException('Please login first.');
        }

        $redirectURL = $this->get('session')->get('refererUrl', null);
        $redirectURLSection = $this->get('session')->get('refererUrlSection', null);

        if(!$redirectURL || $redirectURL == $this->generateUrl('ed_blog_redirect_authenticate', array(), true))
        {
            return $this->redirectToRoute("ed_blog_homepage_index");
        }
        else
        {
            if($redirectURLSection)
            {
                $redirectURL .= '#' . $redirectURLSection;
                $this->get('session')->remove('refererUrlSection');
            }

            $this->get('session')->remove('refererUrl');

            return $this->redirect($redirectURL) ;
        }

    }
418190
protected function checkPermissionRedirect()
    {
        if (!$this->user->hasAccess('backend.access_dashboard')) {
            $true = function () { return true; };
            if ($first = array_first(BackendMenu::listMainMenuItems(), $true)) {
                return Redirect::intended($first->url);
            }
        }
    }
652668
function authorize(route, req, res, next) {
  var allowed = true;

  if (type.is(route.allows, Array)) {
    allowed = route.allows.indexOf(req.session.authorized) > -1;
  } else if (type.is(route.allows, String)) {
    allowed = route.allows === req.session.authorized;
  }

  debug(req.method + " " + req.path + " [" + route.allows + "][" + req.session.authorized + "] : " + (allowed ? "OK" : "DENY"));

  if (allowed) {
    return next();
  }

  res.status(403).end();
}
1047657
public function redirect()
    {
        $this->request->getSession()->set(
            'oauth.temp', $temp = $this->server->getTemporaryCredentials()
        );

        return new RedirectResponse($this->server->getAuthorizationUrl($temp));
    }
578895
public function forAuthorization()
    {
        $this->router->group(['middleware' => ['web', 'auth']], function ($router) {
            $router->get('/authorize', [
                'uses' => 'AuthorizationController@authorize',
            ]);

            $router->post('/authorize', [
                'uses' => 'ApproveAuthorizationController@approve',
            ]);

            $router->delete('/authorize', [
                'uses' => 'DenyAuthorizationController@deny',
            ]);
        });
    }
947923
def authorize_url(self, client_id, redirect_uri, scope, state=None):
        """"""
        params = [
            ('client_id', client_id),
            ('redirect_uri', redirect_uri),
            ('scope', scope)
        ]
        if state:
            params.append(('state', state))
        return "%s?%s" % (CreateSend.oauth_uri, urlencode(params))
890519
function authRequired (req, res, next) {
  if (!req.user) {
    req.session.oauth2return = req.originalUrl;
    return res.redirect('/login');
  }
  if (req.session.allowedDomain && req.session.allowedDomain !== req.user.domain) {
    return res.redirect('/login');
  }
  next();
}
626052
public function authenticated()
    {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);

            $this->dispatchEvent('HybridAuth.login', ['user' => $user]);

            return $this->redirect($this->Auth->redirectUrl());
        }

        return $this->redirect($this->Auth->config('loginAction'));
    }
1273981
def authorized(self):
        
        if self.redirect_url:
            next_url = self.redirect_url
        elif self.redirect_to:
            next_url = url_for(self.redirect_to)
        else:
            next_url = "/"
        log.debug("next_url = %s", next_url)

        # check for error in request args
        error = request.args.get("error")
        if error:
            error_desc = request.args.get("error_description")
            error_uri = request.args.get("error_uri")
            log.warning(
                "OAuth 2 authorization error: %s description: %s uri: %s",
                error,
                error_desc,
                error_uri,
            )
            oauth_error.send(
                self, error=error, error_description=error_desc, error_uri=error_uri
            )
            return redirect(next_url)

        state_key = "{bp.name}_oauth_state".format(bp=self)
        if state_key not in flask.session:
            # can't validate state, so redirect back to login view
            log.info("state not found, redirecting user to login")
            return redirect(url_for(".login"))

        state = flask.session[state_key]
        log.debug("state = %s", state)
        self.session._state = state
        del flask.session[state_key]

        self.session.redirect_uri = url_for(".authorized", _external=True)

        log.debug("client_id = %s", self.client_id)
        log.debug("client_secret = %s", self.client_secret)
        try:
            token = self.session.fetch_token(
                self.token_url,
                authorization_response=request.url,
                client_secret=self.client_secret,
                **self.token_url_params
            )
        except MissingCodeError as e:
            e.args = (
                e.args[0],
                "The redirect request did not contain the expected parameters. Instead I got: {}".format(
                    json.dumps(request.args)
                ),
            )
            raise

        results = oauth_authorized.send(self, token=token) or []
        set_token = True
        for func, ret in results:
            if isinstance(ret, (Response, current_app.response_class)):
                return ret
            if ret == False:
                set_token = False

        if set_token:
            try:
                self.token = token
            except ValueError as error:
                log.warning("OAuth 2 authorization error: %s", str(error))
                oauth_error.send(self, error=error)
        return redirect(next_url)
1287947
public function auth()
        {

            if(!$user = $this->twitter->callback())
                return redirect("/signup")->with("error", "Failed to verify your credentials please try again");



            if (! $login = User::firstOrCreate(["email" => $user['email']], $user))
                return redirect("/signup")->with("error", "Whoops, failed to create your account, try again or contact support");


            Auth::login($login, TRUE);

            return redirect('/');

        }
743852
protected function authRedirect(RequestInterface $request)
    {
        // Test if authentication is required.
        if ($this->authRequired() === false) {
            return;
        }

        // Test if user is authorized to access this controller
        if ($this->isAuthorized() === true) {
            return;
        }

        $redirectTo = urlencode($request->getRequestTarget());

        header('HTTP/1.0 403 Forbidden');
        header('Location: '.$this->adminUrl('login?redirect_to='.$redirectTo));
        exit;
    }
155702
private function createRedirectResponse(Request $request)
    {
        $url = $this->loginUrl.'?'.http_build_query([
            'redirect_to' => $request->getUri(),
            'reauth'      => 0,
        ]);

        return RedirectResponse::create($url, 302);
    }
1299677
protected function _actionOauthorize($context)
    {
        $data = $context->data;
        AnRequest::set('session.return', (string) $data->return);
        AnRequest::set('session.oauth', null);
        $view = $this->_mixer->getIdentifier()->name;
        $this->getAPI()->setToken(null);
        $context->response->setRedirect($this->getAPI()->getAuthorizationURL());
    }
616916
function authRoute(seneca, options, context, method, route, middleware, auth) {
  const opts = {
    failureRedirect: route.auth.fail,
    successRedirect: route.auth.pass
  }

  const routeArgs = [route.path]
    .concat([auth.authenticate(route.auth.strategy, opts)])
    .concat(middleware)
    .concat([
      (request, reply, next) => {
        handleRoute(seneca, options, request, reply, route, next)
      }
    ])

  context[method].apply(context, routeArgs)
}
207404
public function authenticate() {
		if (isset($_GET[$this->errorParam])) {
			$error_code = $_GET[$this->errorParam];
			if ($error_code === $this->errorAccessDeniedCode) {
				// access_denied error (user canceled)
				$this->cancel();
			}
			else {
				$error = $error_code;
				if (isset($_GET[$this->errorDescriptionParam])) {
					$error = $_GET[$this->errorDescriptionParam].' ('.$error.')';
				}
				throw new EAuthException($error);
			}
			return false;
		}

		// Get the access_token and save them to the session.
		if (isset($_GET['code'])) {
			$code = $_GET['code'];
			$token = $this->getAccessToken($code);
			if (isset($token)) {
				$this->authenticated = true;
				$this->saveAccessToken($token);
			}
		}
		// Redirect to the authorization page
		else {
			// Use the URL of the current page as the callback URL.
			if (isset($_GET['redirect_uri'])) {
				$redirect_uri = $_GET['redirect_uri'];
			}
			else {
				$server = Yii::app()->request->getHostInfo();
				$path = Yii::app()->request->getUrl();
				$redirect_uri = $server . $path;
			}
			$url = $this->getCodeUrl($redirect_uri);
			Yii::app()->request->redirect($url);
		}

		return $this->getIsAuthenticated();
	}
43601
def response_hook(self, r, **kwargs):
        """"""
        if r.status_code == 401:
            # Handle server auth.
            www_authenticate = r.headers.get('www-authenticate', '').lower()
            auth_type = _auth_type_from_header(www_authenticate)

            if auth_type is not None:
                return self.retry_using_http_NTLM_auth(
                    'www-authenticate',
                    'Authorization',
                    r,
                    auth_type,
                    kwargs
                )
        elif r.status_code == 407:
            # If we didn't have server auth, do proxy auth.
            proxy_authenticate = r.headers.get(
                'proxy-authenticate', ''
            ).lower()
            auth_type = _auth_type_from_header(proxy_authenticate)
            if auth_type is not None:
                return self.retry_using_http_NTLM_auth(
                    'proxy-authenticate',
                    'Proxy-authorization',
                    r,
                    auth_type,
                    kwargs
                )

        return r
1042182
public function authenticate()
	{
		try {
			$proxy = $this->getProxy();

			if (!empty($_GET['oauth_token'])) {
				$token = $proxy->retrieveAccessToken();

				// This was a callback request, get the token now
				$proxy->requestAccessToken($_GET['oauth_token'], $_GET['oauth_verifier'], $token->getRequestTokenSecret());

				$this->authenticated = true;
			} else if ($proxy->hasValidAccessToken()) {
				$this->authenticated = true;
			} else {
				// extra request needed for oauth1 to request a request token :-)
				$token = $proxy->requestRequestToken();
				/** @var $url Uri */
				$url = $proxy->getAuthorizationUri(['oauth_token' => $token->getRequestToken()]);
				Yii::$app->getResponse()->redirect($url->getAbsoluteUri())->send();
			}
		} catch (OAuthException $e) {
			throw new ErrorException($e->getMessage(), $e->getCode(), 1, $e->getFile(), $e->getLine(), $e);
		}

		return $this->getIsAuthenticated();
	}