API Key Header Authentication

    The verify_user function passed in to ths authenticator shall receive an
    API key as input, and return a user object to store in the request context
    if the request was successful.
163031
def api_key(request, response, verify_user, context=None, **kwargs):
    
    api_key = request.get_header('X-Api-Key')

    if api_key:
        try:
            user = verify_user(api_key)
        except TypeError:
            user = verify_user(api_key, context)
        if user:
            return user
        else:
            return False
    else:
        return None
156081
def httpauth_login_required(func):
    

    def wrapper(request, *args, **kwargs):
        user = None
        # get the Basic username and password from the request.
        auth_string = request.META.get('HTTP_AUTHORIZATION', None)

        if auth_string:
            (authmeth, auth) = auth_string.split(" ", 1)
            auth = auth.strip().decode('base64')
            (username, password) = auth.split(':', 1)

            # print username, password
            user = authenticate(username=username, password=password)

        if not user or not user.is_active:
            return HttpResponse(unauthorized_json_response(),
                                content_type="application/json", status=401)
        login(request, user)
        return func(request, *args, **kwargs)

    return update_wrapper(wrapper, func)
698677
def _authenticate(self):
        
        url = "{base_url}/api/authenticate".format(base_url=self._base_url())
        data = json.dumps({'username': self.username, "password": self.password})
        # Bypass authentication check in make_request by using _send_request
        logger.debug("Authenticating against NetMRI")
        self._send_request(url, method="post", data=data)
        self._is_authenticated = True
306405
def requires_api_auth(fn):
    """"""
    def wrapper(self, *args, **kwargs):
        self.auth_context = HAPI.auth_context_hapi
        return fn(self, *args, **kwargs)
    return wrapper
418219
def authenticate(self, reauth=False):
        
        auth_url = BASE_URL + "/rest/user"
        payload = {'email': self.email, 'password': self.password}
        arequest = requests.get(auth_url, params=payload)
        status = arequest.status_code
        if status != 200:
            if reauth:
                _LOGGER.error("Reauthentication request failed. " + status)
            else:
                _LOGGER.error("Authentication request failed, please check credintials. " + status)
        self.token = arequest.json().get('usertoken')
        if reauth:
            _LOGGER.info("Reauthentication was successful, token updated.")
        else:
            _LOGGER.info("Authentication was successful, token set.")
811461
def verify(self, verifier, consumer_key=None, consumer_secret=None,
               access_token=None, access_token_secret=None):
        
        # Stored values can be supplied to verify
        self.consumer_key = consumer_key or self.consumer_key
        self.consumer_secret = consumer_secret or self.consumer_secret
        self.access_token = access_token or self.access_token
        self.access_token_secret = access_token_secret or self.access_token_secret

        oauth = OAuth1(
            self.consumer_key,
            client_secret=self.consumer_secret,
            resource_owner_key=self.access_token,
            resource_owner_secret=self.access_token_secret,
            verifier=verifier)
        r = requests.post(self.url('ACCESS_TOKEN'), auth=oauth)
        if r.status_code == 200:
            creds = parse_qs(r.content)
        else:
            return (False, r.content)

        self.finalize_oauth(creds.get('oauth_token')[0],
                            creds.get('oauth_token_secret')[0])
        return (True, None)
1028598
def authenticate(self, request):
        
        auth = get_authorization_header(request).split()

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

        if len(auth) == 1:
            msg = _('Invalid auth token header. No credentials provided.')
            raise AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid auth token.')
            raise AuthenticationFailed(msg)

        try:
            token = urlsafe_b64decode(auth[1])
        except ValueError:
            msg = _('Invalid auth token.')
            raise AuthenticationFailed(msg)

        return self.authenticate_credentials(token, request)
428797
def is_authenticated(self, request, **kwargs):
        
        log.info("OAuth20Authentication")
        try:
            key = request.GET.get('oauth_consumer_key')
            if not key:
                for header in ['Authorization', 'HTTP_AUTHORIZATION']:
                    auth_header_value = request.META.get(header)
                    if auth_header_value:
                        key = auth_header_value.split(' ', 1)[1]
                        break
            if not key and request.method == 'POST':
                if request.META.get('CONTENT_TYPE') == 'application/json':
                    decoded_body = request.body.decode('utf8')
                    key = json.loads(decoded_body)['oauth_consumer_key']
            if not key:
                log.info('OAuth20Authentication. No consumer_key found.')
                return None
            """
            If verify_access_token() does not pass, it will raise an error
            """
            token = self.verify_access_token(key, request, **kwargs)

            # If OAuth authentication is successful, set the request user to
            # the token user for authorization
            request.user = token.user

            # If OAuth authentication is successful, set oauth_consumer_key on
            # request in case we need it later
            request.META['oauth_consumer_key'] = key
            return True
        except KeyError:
            log.exception("Error in OAuth20Authentication.")
            request.user = AnonymousUser()
            return False
        except Exception:
            log.exception("Error in OAuth20Authentication.")
            return False
915867
def authenticate(self):
        ''''''

        if not hasattr(self, 'client'):
            self.client = uservoice.Client(self.subdomain,
                                           self.api_key,
                                           self.api_secret)
1343284
def verify_request_signature(request: RequestType, public_key: Union[str, bytes]):
    
    key = encode_if_text(public_key)
    date_header = request.headers.get("Date")
    if not date_header:
        raise ValueError("Rquest Date header is missing")

    ts = parse_http_date(date_header)
    dt = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc)
    delta = datetime.timedelta(seconds=30)
    now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
    if dt < now - delta or dt > now + delta:
        raise ValueError("Request Date is too far in future or past")

    HTTPSignatureHeaderAuth.verify(request, key_resolver=lambda **kwargs: key)
1287035
def _verify_client_authentication(self, request_body, http_headers=None):
        # type (str, Optional[Mapping[str, str]] -> Mapping[str, str]
        
        if http_headers is None:
            http_headers = {}
        token_request = dict(parse_qsl(request_body))
        token_request['client_id']  = verify_client_authentication(self.clients, token_request, http_headers.get('Authorization'))
        return token_request
84314
def authenticate_user(self, request, user):
        
        return user.check_password(request.data.get('password')) or \
               self.check_user_token(request, user)
597518
def verify_request_common(consumers, url, method, headers, params):
    
    log.debug("consumers %s", consumers)
    log.debug("url %s", url)
    log.debug("method %s", method)
    log.debug("headers %s", headers)
    log.debug("params %s", params)

    oauth_server = LTIOAuthServer(consumers)
    oauth_server.add_signature_method(
        SignatureMethod_PLAINTEXT_Unicode())
    oauth_server.add_signature_method(
        SignatureMethod_HMAC_SHA1_Unicode())

    # Check header for SSL before selecting the url
    if headers.get('X-Forwarded-Proto', 'http') == 'https':
        url = url.replace('http:', 'https:', 1)

    oauth_request = Request_Fix_Duplicate.from_request(
        method,
        url,
        headers=dict(headers),
        parameters=params
    )
    if not oauth_request:
        log.info('Received non oauth request on oauth protected page')
        raise LTIException('This page requires a valid oauth session '
                           'or request')
    try:
        # pylint: disable=protected-access
        oauth_consumer_key = oauth_request.get_parameter('oauth_consumer_key')
        consumer = oauth_server.lookup_consumer(oauth_consumer_key)
        if not consumer:
            raise oauth2.Error('Invalid consumer.')
        oauth_server.verify_request(oauth_request, consumer, None)
    except oauth2.Error:
        # Rethrow our own for nice error handling (don't print
        # error message as it will contain the key
        raise LTIException("OAuth error: Please check your key and secret")

    return True
996692
def authenticate_credentials(self, payload):
        
        User = get_user_model()  # noqa
        username = jwt_get_username_from_payload_handler(payload)

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

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

        return user
1244235
def authenticate(self):
        
        resp = self.session.get(self.api_url, auth=self.auth)
        resp = self._process_response(resp)
        return resp
1227488
def get_authenticated_user(self, callback):
        
        self.require_setting(self._CLIENT_ID_SETTING, self._API_NAME)
        self.require_setting(self._CLIENT_SECRET_SETTING, self._API_NAME)

        if self.state:
            if (not self.get_argument('state', None) or
                self.state != self.get_argument('state')):
                LOGGER.error('State did not match: %s != %s',
                             self.state, self.get_argument('state'))
                raise auth.AuthError('Problematic Reply from %s' %
                                     self._API_NAME)

        args = {'client_id': self.settings[self._CLIENT_ID_SETTING],
                'client_secret': self.settings[self._CLIENT_SECRET_SETTING],
                'code': self.get_argument('code'),
                'redirect_uri': self.oauth2_redirect_uri()}

        http_client = self._get_auth_http_client()
        callback = self.async_callback(self._on_access_token, callback)
        http_client.fetch(self._OAUTH_ACCESS_TOKEN_URL,
                          method='POST',
                          headers={'Accept': self._ACCEPT},
                          user_agent=self._USER_AGENT,
                          body=auth.urllib_parse.urlencode(args),
                          callback=callback)
1123116
def VerifyCoARequest(self):
        
        assert(self.raw_packet)
        hash = md5_constructor(self.raw_packet[0:4] + 16 * six.b('\x00') +
                self.raw_packet[20:] + self.secret).digest()
        return hash == self.authenticator