Pick authentication method

    :param areq: AuthorizationRequest instance
    :return: A dictionary with the authentication method and its authn class ref
487396
def pick_auth(endpoint_context, areq, all=False):
    

    acrs = []
    try:
        if len(endpoint_context.authn_broker) == 1:
            return endpoint_context.authn_broker.default()

        if "acr_values" in areq:
            if not isinstance(areq["acr_values"], list):
                areq["acr_values"] = [areq["acr_values"]]
            acrs = areq["acr_values"]
        else:  # same as any
            try:
                acrs = areq["claims"]["id_token"]["acr"]["values"]
            except KeyError:
                try:
                    _ith = areq[verified_claim_name("id_token_hint")]
                except KeyError:
                    try:
                        _hint = areq['login_hint']
                    except KeyError:
                        pass
                    else:
                        if endpoint_context.login_hint2acrs:
                            acrs = endpoint_context.login_hint2acrs(_hint)
                else:
                    try:
                        acrs = [_ith['acr']]
                    except KeyError:
                        pass

                if not acrs:
                    return endpoint_context.authn_broker.default()

        for acr in acrs:
            res = endpoint_context.authn_broker.pick(acr)
            logger.debug("Picked AuthN broker for ACR %s: %s" % (
                str(acr), str(res)))
            if res:
                if all:
                    return res
                else:
                    # Return the first guess by pick.
                    return res[0]

    except KeyError as exc:
        logger.debug(
            "An error occurred while picking the authN broker: %s" % str(exc))

    return None
174462
def _auth():
    '''
    
    '''
    if 'auth' not in __context__:
        try:
            __context__['auth'] = salt.crypt.SAuth(__opts__)
        except SaltClientError:
            log.error('Could not authenticate with master.'
                      'Mine data will not be transmitted.')
    return __context__['auth']
243660
def request(method, url, **kwargs):
    
    auth = kwargs.get('auth')
    headers = kwargs.get('headers', {})
    # headers = headers.copy() # ? We do modify the dict in place here...
    if isinstance(auth, TreqKerberosAuth):
        del kwargs['auth']
        if auth.force_preemptive:
            # Save a round-trip and set the Negotiate header on the first req.
            headers['Authorization'] = yield negotiate_header(url)
    response = yield treq.request(method=method, url=url, headers=headers,
                                  **kwargs)
    # Retry if we got a 401 / Negotiate response.
    if response.code == 401 and isinstance(auth, TreqKerberosAuth):
        auth_mechs = response.headers.getRawHeaders('WWW-Authenticate')
        if 'Negotiate' in auth_mechs:
            headers['Authorization'] = yield negotiate_header(url)
            response = yield treq.request(method=method, url=url,
                                          headers=headers, **kwargs)
    defer.returnValue(response)
561721
def authenticate(self):
        
        basic_auth = request.authorization
        is_valid = False
        user = None
        if basic_auth:
            is_valid, user = self.check_basic_auth(
                basic_auth.username, basic_auth.password
            )
        else:  # Try token auth
            token = request.headers.get('Authorization', None)
            param_token = request.args.get('access_token')
            if token or param_token:
                if token:
                    # slice the 'token ' piece of the header (following
                    # github style):
                    token = token[6:]
                else:
                    # Grab it from query dict instead
                    token = param_token
                log.debug('Received token: %s', token)

                is_valid, user = self.check_token_auth(token)
        return (is_valid, user)
174046
def credentials_required(view_func):
    
    @wraps(view_func, assigned=available_attrs(view_func))
    def decorator(request, *args, **kwargs):
        if settings.LOCALSHOP_USE_PROXIED_IP:
            try:
                ip_addr = request.META['HTTP_X_FORWARDED_FOR']
            except KeyError:
                return HttpResponseForbidden('No permission')
            else:
                # HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs.
                # The client's IP will be the first one.
                ip_addr = ip_addr.split(",")[0].strip()
        else:
            ip_addr = request.META['REMOTE_ADDR']

        if CIDR.objects.has_access(ip_addr, with_credentials=False):
            return view_func(request, *args, **kwargs)

        if not CIDR.objects.has_access(ip_addr, with_credentials=True):
            return HttpResponseForbidden('No permission')

        # Just return the original view because already logged in
        if request.user.is_authenticated():
            return view_func(request, *args, **kwargs)

        user = authenticate_user(request)
        if user is not None:
            login(request, user)
            return view_func(request, *args, **kwargs)

        return HttpResponseUnauthorized(content='Authorization Required')
    return decorator
760122
def list_auth_methods(self):
        
        api_path = '/v1/sys/auth'
        response = self._adapter.get(
            url=api_path,
        )
        return response.json()
104253
def parse_authentication_request(self, request_body, http_headers=None):
        # type: (str, Optional[Mapping[str, str]]) -> oic.oic.message.AuthorizationRequest
        

        auth_req = AuthorizationRequest().deserialize(request_body)

        for validator in self.authentication_request_validators:
            validator(auth_req)

        logger.debug('parsed authentication_request: %s', auth_req)
        return auth_req
1283434
def build_authorization_arg(authdict):
  
  vallist = []
  for k in authdict.keys():
    vallist += ['%s=%s' % (k,authdict[k])]
  return 'Digest '+', '.join(vallist)
7655
def authenticate(self, request, username=None, password=None, realm=None):
        
        if isinstance(username, basestring):
            username = username.encode('utf-8')

        if isinstance(password, basestring):
            password = password.encode('utf-8')

        server = self.get_server(realm)

        if not server:
            return None

        result = self._radius_auth(server, username, password)

        if result:
            full_username = self.construct_full_username(username, realm)
            return self.get_django_user(full_username, password)

        return None
311445
def __process_acl(self, load, auth_list):
        '''
        
        '''
        if 'eauth' not in load:
            return auth_list
        fstr = '{0}.process_acl'.format(load['eauth'])
        if fstr not in self.auth:
            return auth_list
        try:
            return self.auth[fstr](auth_list, self.opts)
        except Exception as e:
            log.debug('Authentication module threw %s', e)
            return auth_list
4391
def authentication(self):
        """"""
        if self.session.digest:
            authentication = self.session.generate_digest()
        elif self.session.basic:
            authentication = self.session.generate_basic()
        else:
            return ''
        return "Authorization: " + authentication + '\r\n'
235862
def _get_credentials(self, request):
        
        authorization = request.headers.get('Authorization')
        if not authorization:
            return None
        try:
            authmeth, authbytes = authorization.split(' ', 1)
        except ValueError:  # not enough values to unpack
            return None
        if authmeth.lower() != 'apikey':
            return None

        if six.PY2 or isinstance(authbytes, bytes):
            try:
                auth = authbytes.decode('utf-8')
            except UnicodeDecodeError:
                auth = authbytes.decode('latin-1')
        else:
            auth = authbytes

        try:
            username, api_key = auth.split(':', 1)
        except ValueError:  # not enough values to unpack
            return None
        return username, api_key
768182
def handle_authn_response(self, context, internal_response):
        
        return self._handle_authn_response(context, internal_response, self.idp)
651854
def _get_authenticated_session(self):
        
        session = requests.Session()
        session.auth = self.auth
        return session
384616
def authenticate(self, environ):
        
        try:
            hd = parse_dict_header(environ['HTTP_AUTHORIZATION'])
        except (KeyError, ValueError):
            return False

        return self.credentials_valid(
            hd['response'],
            environ['REQUEST_METHOD'],
            environ['httpauth.uri'],
            hd['nonce'],
            hd['Digest username'],
        )
195364
def _verify_authentication(self, handler, args, kwargs):
        
        if not self.user_manager.session_logged_in():
            raise APIForbidden()
        return handler(*args, **kwargs)
1244235
def authenticate(self):
        
        resp = self.session.get(self.api_url, auth=self.auth)
        resp = self._process_response(resp)
        return resp