Build an auth-token-protected CAS API url.
555505
def get_api_url(
        self,
        api_resource,
        auth_token_ticket,
        authenticator,
        private_key,
        service_url=None,
        **kwargs
    ):
        '''
        
        '''
        auth_token, auth_token_signature = self._build_auth_token_data(
            auth_token_ticket,
            authenticator,
            private_key,
            **kwargs
            )
        params = {
            'at': auth_token,
            'ats': auth_token_signature,
            }
        if service_url is not None:
            params['service'] = service_url
        url = '{}?{}'.format(
            self._get_api_url(api_resource),
            urlencode(params),
            )
        return url
985258
def authenticate(api_key, api_url, **kwargs):
    """"""

    muddle = Muddle(**kwargs)

    # Login.
    muddle.authenticate(api_key, api_url)
    return muddle
531564
def get_cas_client(service_url=None, request=None):
    
    # Handle CAS_SERVER_URL without protocol and hostname
    server_url = django_settings.CAS_SERVER_URL
    if server_url and request and server_url.startswith('/'):
        scheme = request.META.get("X-Forwarded-Proto", request.scheme)
        server_url = scheme + "://" + request.META['HTTP_HOST'] + server_url
    # assert server_url.startswith('http'), "settings.CAS_SERVER_URL invalid"

    if not django_settings.CAS_VERIFY_SSL_CERTIFICATE:
        warnings.warn(
            "`CAS_VERIFY_SSL_CERTIFICATE` is disabled, meaning that SSL certificates "
            "are not being verified by a certificate authority. This can expose your "
            "system to various attacks and should _never_ be disabled in a production "
            "environment."
        )

    return CASClient(
        service_url=service_url,
        version=django_settings.CAS_VERSION,
        server_url=server_url,
        extra_login_params=django_settings.CAS_EXTRA_LOGIN_PARAMS,
        renew=django_settings.CAS_RENEW,
        username_attribute=django_settings.CAS_USERNAME_ATTRIBUTE,
        proxy_callback=django_settings.CAS_PROXY_CALLBACK,
        verify_ssl_certificate=django_settings.CAS_VERIFY_SSL_CERTIFICATE
    )
972443
def _build_url(self):
        """"""
        if self.connection.get("username") and self.connection.get("password"):
            auth = "%s:%s@" % (self.connection["username"],
                               self._encoded_password)
            if self.connection.get("domain"):
                auth = r"%s;%s" % (self.connection["domain"], auth)
        else:
            auth = ""

        # Optional port number
        port = self.connection.get("port")
        port = ":" + port if port else ""

        # Construct mount_url
        self.connection["mount_url"] = "//%s%s%s/%s" % (
            auth, self.connection["url"], port, self.connection["share_name"])
745401
def authentication_url(self):
        """"""
        params = {
            'client_id': self.client_id,
            'response_type': self.type,
            'redirect_uri': self.callback_url
        }
        return AUTHENTICATION_URL + "?" + urlencode(params)
1107536
def http_auth_required(realm):
    """"""

    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            if _check_http_auth():
                return fn(*args, **kwargs)
            if _security._unauthorized_callback:
                return _security._unauthorized_callback()
            else:
                r = _security.default_http_auth_realm \
                    if callable(realm) else realm
                h = {'WWW-Authenticate': 'Basic realm="%s"' % r}
                return _get_unauthorized_response(headers=h)
        return wrapper

    if callable(realm):
        return decorator(realm)
    return decorator
1190456
function _getToken(opts, cb) {
    assert.string(opts.indexName, 'opts.indexName'); // used for error messages
    assert.string(opts.realm, 'opts.realm');
    assert.optionalString(opts.service, 'opts.service');
    assert.optionalArrayOfString(opts.scopes, 'opts.scopes');
    assert.optionalString(opts.username, 'opts.username');
    assert.optionalString(opts.password, 'opts.password');
    // HTTP client opts:
    assert.object(opts.log, 'opts.log');
    assert.optionalObject(opts.agent, 'opts.agent');
    // assert.optional object or bool(opts.proxy, 'opts.proxy');
    assert.optionalBool(opts.insecure, 'opts.insecure');
    assert.optionalString(opts.userAgent, 'opts.userAgent');
    var log = opts.log;

    // - add https:// prefix (or http) if none on 'realm'
    var tokenUrl = opts.realm;
    var match = /^(\w+):\/\//.exec(tokenUrl);
    if (!match) {
        tokenUrl = (opts.insecure ? 'http' : 'https') + '://' + tokenUrl;
    } else if (['http', 'https'].indexOf(match[1]) === -1) {
        return cb(new Error(fmt('unsupported scheme for ' +
            'WWW-Authenticate realm "%s": "%s"', opts.realm, match[1])));
    }

    // - GET $realm
    //      ?service=$service
    //      (&scope=$scope)*
    //      (&account=$username)
    //   Authorization: Basic ...
    var headers = {};
    var query = {};
    if (opts.service) {
        query.service = opts.service;
    }
    if (opts.scopes && opts.scopes.length) {
        query.scope = opts.scopes;  // intentionally singular 'scope'
    }

    if (opts.username) {
        query.account = opts.username;
        _setAuthHeaderFromAuthInfo(headers, {
            username: opts.username,
            password: opts.password
        });
    }
    if (Object.keys(query).length) {
        tokenUrl += '?' + querystring.stringify(query);
    }
    log.trace({tokenUrl: tokenUrl}, '_getToken: url');

    var parsedUrl = mod_url.parse(tokenUrl);
    var client = new DockerJsonClient({
        url: parsedUrl.protocol + '//' + parsedUrl.host,
        log: log,
        agent: opts.agent,
        proxy: opts.proxy,
        rejectUnauthorized: !opts.insecure,
        userAgent: opts.userAgent || common.DEFAULT_USERAGENT
    });
    client.get({
        path: parsedUrl.path,
        headers: headers
    }, function (err, req, res, body) {
        client.close();
        if (err) {
            if (err.statusCode === 401) {
                // Convert *all* 401 errors to use a generic error constructor
                // with a simple error message.
                var errMsg = _getRegistryErrorMessage(err);
                return cb(new errors.UnauthorizedError(errMsg));
            }
            return cb(err);
        } else if (!body.token) {
            return cb(new errors.UnauthorizedError(err, 'authorization ' +
                'server did not include a token in the response'));
        }
        cb(null, body.token);
    });
}
171735
def _request_access_token(self):
        
        payload = {'grant_type': 'authorization_code',
                   'code': code,
                   'redirect_uri': self.redirect_uri}

        headers = _make_authorization_headers(self.client_id,
                                              self.client_secret)

        response = requests.post(self.OAUTH_TOKEN_URL, data=payload,
                                 headers=headers,
                                 verify=LOGIN_VERIFY_SSL_CERT)

        if response.status_code is not 200:
            raise MercedesMeAuthError(response.reason)
        token_info = response.json()
        return token_info
720701
private String buildAuthUrl(String baseAuthUrl, GrantType grantType, OAuth2Parameters parameters) {
		StringBuilder authUrl = new StringBuilder(baseAuthUrl);
		if (grantType == GrantType.AUTHORIZATION_CODE) {
			authUrl.append('&').append("response_type").append('=').append("code");
		} else if (grantType == GrantType.IMPLICIT_GRANT) {
			authUrl.append('&').append("response_type").append('=').append("token");
		}
		for (Iterator<Entry<String, List<String>>> additionalParams = parameters.entrySet().iterator(); additionalParams.hasNext();) {
			Entry<String, List<String>> param = additionalParams.next();
			String name = formEncode(param.getKey());
			for (Iterator<String> values = param.getValue().iterator(); values.hasNext();) {
				authUrl.append('&').append(name);
				String value = values.next();
				if (StringUtils.hasLength(value)) {
					authUrl.append('=').append(formEncode(value));
				}
			}
		}
		return authUrl.toString();		
	}
235678
def access_token(self):
        
        access_token = generate_token(length=self.access_token_length[1])
        token_secret = generate_token(self.secret_length)
        client_key = request.oauth.client_key
        self.save_access_token(client_key, access_token,
            request.oauth.resource_owner_key, secret=token_secret)
        return urlencode([(u'oauth_token', access_token),
                          (u'oauth_token_secret', token_secret)])
796312
def generate_token(self):
        """"""

        response = self._make_request()
        self.auth = response
        self.token = response['token']
1144752
def _auth(uri):
    '''
    
    '''

    user, password = _get_credentials()
    if user is False or password is False:
        return False

    basic = _HTTPBasicAuthHandler()
    basic.add_password(realm='Tomcat Manager Application', uri=uri,
                       user=user, passwd=password)
    digest = _HTTPDigestAuthHandler()
    digest.add_password(realm='Tomcat Manager Application', uri=uri,
                        user=user, passwd=password)
    return _build_opener(basic, digest)
1010668
def url(self):
        ""
        # The authorize url is always api.xero.com
        query_string = {'oauth_token': self.oauth_token}

        if self.scope:
            query_string['scope'] = self.scope

        url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \
              urlencode(query_string)
        return url
211998
def _build_url(self):
        """"""
        if self.connection.get("username") and self.connection.get("password"):
            auth = "%s:%s@" % (self.connection["username"],
                               self._encoded_password)
        else:
            auth = ""

        # Optional port number
        port = self.connection.get("port")
        port = ":" + port if port else ""

        self.connection["mount_url"] = "%s://%s%s%s/%s" % (
            self.protocol, auth, self.connection["url"], port,
            self.connection["share_name"])
481789
def authorized(self, request_token):
        """"""
        verifier = generate_token(length=self.verifier_length[1])
        self.save_verifier(request_token, verifier)
        response = [
            (u'oauth_token', request_token),
            (u'oauth_verifier', verifier)
        ]
        callback = self.get_callback(request_token)
        return redirect(add_params_to_uri(callback, response))
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")
472828
def cas!(key, ttl=nil, options=nil, &block)
      cas_core(key, true, ttl, options, &block)
    end