POST /auth/
 Authenticate, generate token and add header
320775
def authenticate(username = nil, password = nil, options = {}, &block)
      if username.is_a?(Hash) or password.is_a?(Hash)
        options = username.is_a?(Hash) ? username : password
      end
      options["username"] = username if username and !username.is_a?Hash
      options["password"] = password if password and !password.is_a?Hash

      options = set_options(options, &block)

      #TODO: Raise error if doesn't find username and password key in options
      @response = post('auth', options)
      if @response.has_key?("success") and @response['success']
        add_header("X-Auth-Token", @response['token'])
      end
      @response
    end
307966
def to_header(self, realm=''):
        """"""
        oauth_params = ((k, v) for k, v in self.items() 
                            if k.startswith('oauth_'))
        stringy_params = ((k, escape(v)) for k, v in oauth_params)
        header_params = ('%s="%s"' % (k, v) for k, v in stringy_params)
        params_header = ', '.join(header_params)
 
        auth_header = 'OAuth realm="%s"' % realm
        if params_header:
            auth_header = "%s, %s" % (auth_header, params_header)
 
        return {'Authorization': auth_header}
450349
def create_token(credential, opts = {})
      data, _status_code, _headers = create_token_with_http_info(credential, opts)
      return data
    end
335161
def _add_bearer_token(self, uri, http_method='GET', body=None,
                          headers=None, token_placement=None):
        """"""
        if token_placement == AUTH_HEADER:
            headers = tokens.prepare_bearer_headers(self.access_token, headers)

        elif token_placement == URI_QUERY:
            uri = tokens.prepare_bearer_uri(self.access_token, uri)

        elif token_placement == BODY:
            body = tokens.prepare_bearer_body(self.access_token, body)

        else:
            raise ValueError("Invalid token placement.")
        return uri, headers, body
1081404
def authenticate(self, request):
        
        auth_header = get_authorization_header(request).decode(HTTP_HEADER_ENCODING)
        auth = auth_header.split()

        if not auth or auth[0].lower() != 'bearer':
            return None

        if len(auth) == 1:
            msg = 'Invalid token header. No backend provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) == 2:
            msg = 'Invalid token header. No credentials provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 3:
            msg = 'Invalid token header. Token string should not contain spaces.'
            raise exceptions.AuthenticationFailed(msg)

        token = auth[2]
        backend = auth[1]

        strategy = load_strategy(request=request)

        try:
            backend = load_backend(strategy, backend, reverse(NAMESPACE + ":complete", args=(backend,)))
        except MissingBackend:
            msg = 'Invalid token header. Invalid backend.'
            raise exceptions.AuthenticationFailed(msg)

        try:
            user = backend.do_auth(access_token=token)
        except requests.HTTPError as e:
            msg = e.response.text
            raise exceptions.AuthenticationFailed(msg)

        if not user:
            msg = 'Bad credentials.'
            raise exceptions.AuthenticationFailed(msg)
        return user, token
747942
def to_header(self):
        """"""
        d = dict(self)
        auth_type = d.pop("__auth_type__", None) or "basic"
        return "%s %s" % (
            auth_type.title(),
            ", ".join(
                [
                    "%s=%s"
                    % (
                        key,
                        quote_header_value(
                            value, allow_token=key not in self._require_quoting
                        ),
                    )
                    for key, value in iteritems(d)
                ]
            ),
        )
377460
def authenticate(self):
        """"""
        postdata = self.authentication_postdata
        jar = requests.cookies.cookielib.CookieJar()
        self.cookies = jar
        resp = self.get(self.authentication_base_url)
        authtok = _extract_authenticity_token(resp.content)
        if postdata is None:
            # This works for GitHub
            postdata = {"login": self.oauth2_username,
                        "password": self._oauth2_password,
                        "authenticity_token": authtok,
                        "commit": "Sign+in",
                        "utf8": u"\u2713",
                        }  # pylint: disable=bad-continuation
            self.authentication_postdata = postdata
        if self.authentication_session_url is None:
            # This is also for GitHub
            authentication_session_url = "https://github.com/session"
            self.authentication_session_url = authentication_session_url
        self.post(self.authentication_session_url, data=postdata)
349093
def post(self, request, data=None):
        
        headers = {"Authorization": "Bearer " + self.token }
        logging.debug(json.dumps(data, indent=4))
        p = requests.post(self.url + request, headers=headers, data=json.dumps(data))
        return json.loads(p.text)
1060447
function authorize (req, res, next) {
  var params = req.connectParams
  var responseTypes = params.response_type.trim().split(' ')
  var responseMode = (params.response_mode && params.response_mode.trim()) ||
    (params.response_type === 'code' ||
      params.response_type === 'none') ? '?' : '#'

  // ACCESS GRANTED
  if (params.authorize === 'true') {
    // compose the response
    async.waterfall([

      function includeAccessToken (callback) {
        if (responseTypes.indexOf('token') !== -1) {
          AccessToken.issue(req, function (err, response) {
            if (err) { return callback(err) }
            callback(null, response)
          })

        // initialize an empty response
        } else {
          callback(null, {})
        }
      },

      function includeAuthorizationCode (response, callback) {
        if (responseTypes.indexOf('code') !== -1) {
          AuthorizationCode.insert({
            client_id: req.client._id,
            redirect_uri: params.redirect_uri,
            nonce: params.nonce,
            max_age: parseInt(params.max_age, 10) || req.client.default_max_age,
            user_id: req.user._id,
            scope: req.scope

          }, function (err, ac) {
            if (err) { return callback(err) }
            response.code = ac.code
            callback(null, response)
          })

        // pass through to next
        } else {
          callback(null, response)
        }
      },

      function includeIDToken (response, callback) {
        if (responseTypes.indexOf('id_token') !== -1) {
          var shasum, hash, atHash

          if (response.access_token) {
            shasum = crypto.createHash('sha256')
            shasum.update(response.access_token)
            hash = shasum.digest('hex')
            atHash = hash.slice(0, hash.length / 2)
          }

          var idToken = new IDToken({
            iss: settings.issuer,
            sub: req.user._id,
            aud: req.client._id,
            exp: nowSeconds(response.expires_in),
            nonce: params.nonce,
            at_hash: atHash,
            amr: req.session.amr
          })

          response.id_token = idToken.encode(settings.keys.sig.prv)
        }

        callback(null, response)
      }

    ], function (err, response) {
      if (err) { return next(err) }

      if (params.state) {
        response.state = params.state
      }

      // Set the OP browser state.
      var opbs = req.session.opbs

      // if responseTypes includes id_token or token
      // calculate session_state and add to response
      if (responseTypes.indexOf('id_token') !== -1 ||
        responseTypes.indexOf('token') !== -1) {
        var session = sessionState(req.client, req.client.client_uri, opbs)
        response.session_state = session
      }

      res.redirect(
        params.redirect_uri + responseMode + qs.stringify(response)
      )
    })

  // ACCESS DENIED
  } else {
    res.redirect(params.redirect_uri + '?error=access_denied')
  }
}
816598
def apply_basic_auth(params)
      headers = params.fetch(:headers, {})
      headers = basic_auth_header.merge(headers)
      params.merge(:headers => headers)
    end
455981
def auth_request(self, url, headers, body):
        """"""

        return self.req.post(url, headers, body=body)
197287
def token(config, token):
    """"""
    if not token:
        info_out(
            "To generate a personal API token, go to:\n\n\t"
            "https://github.com/settings/tokens\n\n"
            "To read more about it, go to:\n\n\t"
            "https://help.github.com/articles/creating-an-access"
            "-token-for-command-line-use/\n\n"
            'Remember to enable "repo" in the scopes.'
        )
        token = getpass.getpass("GitHub API Token: ").strip()
    url = urllib.parse.urljoin(config.github_url, "/user")
    assert url.startswith("https://"), url
    response = requests.get(url, headers={"Authorization": "token {}".format(token)})
    if response.status_code == 200:
        update(
            config.configfile,
            {
                "GITHUB": {
                    "github_url": config.github_url,
                    "token": token,
                    "login": response.json()["login"],
                }
            },
        )
        name = response.json()["name"] or response.json()["login"]
        success_out("Hi! {}".format(name))
    else:
        error_out("Failed - {} ({})".format(response.status_code, response.content))
1069383
def post_with_auth(path, response_class, payload)
      response_class.new(client.post_with_auth(path, payload))
    end
506240
function generateSetupToken (tokenPath) {
  mkdirp.sync(path.dirname(tokenPath))

  var token = crypto.randomBytes(256).toString('hex')
  try {
    fs.writeFileSync(tokenPath, token, 'utf8')
  } catch (e) {
    throw new Error('Unable to save setup token to ' + tokenPath)
  }
  return token
}
926295
def post_with_auth(path, payload)
      @connection.post(
        path,
        payload.merge(client_id: @client_id, secret: @secret)
      ).body
    end
758672
private function prepare_auth_header() {
    $this->headers = array();
    uksort($this->auth_params, 'strcmp');
    if (!$this->config['as_header']) :
      $this->request_params = array_merge($this->request_params, $this->auth_params);
      return;
    endif;

    foreach ($this->auth_params as $k => $v) {
      $kv[] = "{$k}=\"{$v}\"";
    }
    $this->auth_header = 'OAuth ' . implode(', ', $kv);
    $this->headers['Authorization'] = $this->auth_header;
  }
1138547
def get_token(username, password, server):
    
    method = 'PUT'
    uri = 'https://' + server + '/authenticate'
    token = ''

    authinfo = {
        "username": username,
        "password": password,
        "local_user": username}

    token = tonicdns_client(uri, method, token, data=authinfo)

    return token