Takes the header and tries to return an active token and decoded
    payload.
    :param auth_header:
    :param client_id:
    :param client_secret:
    :return: (token, profile)
774765
def _decode_header(auth_header, client_id, client_secret):
    
    try:
        token = auth_header.split()[1]
        payload = jwt.decode(
            token,
            client_secret,
            audience=client_id)
    except jwt.ExpiredSignature:
        raise exceptions.NotAuthorizedException(
            'Token has expired, please log in again.')
    # is valid client
    except jwt.InvalidAudienceError:
        message = 'Incorrect audience, expected: {}'.format(
            client_id)
        raise exceptions.NotAuthorizedException(message)
    # is valid token
    except jwt.DecodeError:
        raise exceptions.NotAuthorizedException(
            'Token signature could not be validated.')
    except Exception as e:
        raise exceptions.NotAuthorizedException(
            'Token signature was malformed. {}'.format(e.message))
    return token, payload
546313
def get_authorization_header(request):
    
    auth = request.META.get('HTTP_AUTHORIZATION', b'')

    if isinstance(auth, type('')):
        # Work around django test client oddness
        auth = auth.encode('iso-8859-1')

    return auth
1367709
def auth_token(self, apikey=None, secret=None, email=None, password=None):
        
        if (apikey and secret) or (self._apikey and self._secret):
            body = {
                "key_id": apikey or self._apikey,
                "secret": secret or self._secret
            }
        elif (email and password) or (self._email and self._password):
            body = {
                "user" : email or self._email,
                "password" : password or self._password
            }
        else:
            raise Value("No authentication provided.")
        response = self._post(url.auth, body=body)

        self._check_response(response, 200)
        return self._create_response(response).get("jwt")
346965
def _get_access_token(self, verifier=None):
        
        
        response, content = self.client(verifier).request(
            self.access_token_url, "POST")
        
        content = smart_unicode(content)

        if not response['status'] == '200':
            raise OAuthError(_(
                u"Invalid status code %s while obtaining access token from %s: %s") % 
                (response['status'], self.access_token_url, content))
        
        token = dict(urlparse.parse_qsl(content))
        
        
        return (oauth.Token(token['oauth_token'], token['oauth_token_secret']),
            token)
1358724
def get_profile_from_tokens(token_records, public_key_or_address,
                            hierarchical_keys=False):
    
    if hierarchical_keys:
        raise NotImplementedError("Hierarchical key support not implemented")

    profile = {}

    for token_record in token_records:
        # print token_record
        try:
            decoded_token = verify_token_record(token_record, public_key_or_address)
        except ValueError:
            # traceback.print_exc()
            continue
        else:
            if "payload" in decoded_token:
                if "claim" in decoded_token["payload"]:
                    claim = decoded_token["payload"]["claim"]
                    profile.update(claim)

    return profile
220448
def request_headers(headers = {}, auth: true, gzip: true)
      headers = default_headers.merge(headers)
      headers.merge!(bearer_authorization_header) if auth
      headers[ACCEPT_ENCODING] = GZIP if gzip
      headers.reject{|_,v| v.nil? || (v.respond_to?(:empty?) && v.empty?)}
    end
236787
def get_auth_token(cls):
        
        if 'Authorization' not in f_request.headers:
            raise ValueError("Missing Authorization Bearer in headers")
        data = f_request.headers['Authorization'].encode('ascii', 'ignore')
        return str.replace(str(data), 'Bearer ', '').strip()
492730
def _GetAuthCookie(self, auth_token):
		
		# This is a dummy value to allow us to identify when we're successful.
		continue_location = "http://localhost/"
		args = {"continue": continue_location, "auth": auth_token}
		req = self._CreateRequest("https://%s/_ah/login?%s" % (self.host, urllib.urlencode(args)))
		try:
			response = self.opener.open(req)
		except urllib2.HTTPError, e:
			response = e
		if (response.code != 302 or
				response.info()["location"] != continue_location):
			raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp)
		self.authenticated = True
139878
def get_api_key(client, username, secret):
    

    # Try to use a client with username/api key
    if len(secret) == 64:
        try:
            client['Account'].getCurrentUser()
            return secret
        except SoftLayer.SoftLayerAPIError as ex:
            if 'invalid api token' not in ex.faultString.lower():
                raise
    else:
        # Try to use a client with username/password
        client.authenticate_with_password(username, secret)

        user_record = client['Account'].getCurrentUser(mask='id, apiAuthenticationKeys')
        api_keys = user_record['apiAuthenticationKeys']
        if len(api_keys) == 0:
            return client['User_Customer'].addApiAuthenticationKey(id=user_record['id'])
        return api_keys[0]['authenticationKey']
219571
def extract_client_auth(request):
    
    auth_header = request.META.get('HTTP_AUTHORIZATION', '')

    if re.compile('^Basic\s{1}.+$').match(auth_header):
        b64_user_pass = auth_header.split()[1]
        try:
            user_pass = b64decode(b64_user_pass).decode('utf-8').split(':')
            client_id, client_secret = tuple(user_pass)
        except Exception:
            client_id = client_secret = ''
    else:
        client_id = request.POST.get('client_id', '')
        client_secret = request.POST.get('client_secret', '')

    return (client_id, client_secret)
213121
def parse_auth(header):
    
    try:
        method, data = header.split(None, 1)
        if method.lower() == 'basic':
            data = base64.b64decode(uniorbytes(data, bytes))
            user, pwd = uniorbytes(data).split(':', 1)
            return user, pwd
    except (KeyError, AttributeError, ValueError):
        return (None, None)
1027388
function verifyClientToken (req, res, next) {
  var header = req.headers['authorization']

  // missing header
  if (!header) {
    return next(new UnauthorizedError({
      realm: 'client',
      error: 'unauthorized_client',
      error_description: 'Missing authorization header',
      statusCode: 403
    }))

  // header found
  } else {
    var jwt = header.replace('Bearer ', '')
    var token = ClientToken.decode(jwt, settings.keys.sig.pub)

    // failed to decode
    if (!token || token instanceof Error) {
      next(new UnauthorizedError({
        realm: 'client',
        error: 'unauthorized_client',
        error_description: 'Invalid access token',
        statusCode: 403
      }))

    // decoded successfully
    } else {
      // validate token
      req.token = token
      next()
    }
  }
}
391280
function __process_authorization_header_for_client(request_params) {
    return new Promise(async (resolve, reject) => {
        try {
            const client_account_id = await client_endpoint
                .client_registrar_module
                .get_client_account_id_for_credentials(request_params.authorization_credentials.username, request_params.authorization_credentials.password);

            return resolve(request_params);
        } catch (err) {
            return reject(new Error("Unauthorized request"));
        }
    });
}
765094
def resolve(self, authorization: http.Header):
        
        from django_apistar.authentication.models import Token

        if authorization is None:
            return None

        scheme, token = authorization.split()
        if scheme.lower() != 'bearer':
            return None

        try:
            user = Token.objects.get(key=token).user
        except Token.DoesNotExist:
            return None

        return user
963980
def authenticate(self, client_id, client_secret, use_cache=True):
        
        # We will reuse a token for as long as we have one cached
        # and it hasn't expired.
        if use_cache:
            client = self._get_client_from_cache(client_id)
            if (client) and (not self.is_expired_token(client)):
                self.authenticated = True
                self.client = client
                return

        # Let's authenticate the client
        client = {
            'id': client_id,
            'secret': client_secret
        }

        res = self._authenticate_client(client_id, client_secret)
        client.update(res)

        expires = datetime.datetime.now() + \
                  datetime.timedelta(seconds=res['expires_in'])
        client['expires'] = expires.isoformat()

        # Cache it for repeated use until expired
        self._write_to_uaa_cache(client)

        self.client = client
        self.authenticated = True
3740
def _encode_message_header(cls, client_id, correlation_id, request_key,
                               api_version=0):
        
        return (struct.pack('>hhih',
                            request_key,          # ApiKey
                            api_version,          # ApiVersion
                            correlation_id,       # CorrelationId
                            len(client_id)) +     # ClientId size
                client_id)
48264
def authenticate_credentials(self, payload):
        
        User = get_user_model()
        username = jwt_get_username_from_payload(payload)

        if not username:
            msg = _('Invalid payload.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            user = User.objects.get_by_natural_key(username)
        except User.DoesNotExist:
            msg = _('Invalid signature.')
            raise exceptions.AuthenticationFailed(msg)

        if not user.is_active:
            msg = _('User account is disabled.')
            raise exceptions.AuthenticationFailed(msg)

        return user