Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None
559315
def parse_auth(header):
    
    try:
        method, data = header.split(None, 1)
        if method.lower() == 'basic':
            user, pwd = touni(base64.b64decode(tob(data))).split(':',1)
            return user, pwd
    except (KeyError, ValueError):
        return None
696558
def parse_user(raw):
    
    nick = raw
    user = None
    host = None

    # Attempt to extract host.
    if protocol.HOST_SEPARATOR in raw:
        raw, host = raw.split(protocol.HOST_SEPARATOR)
    # Attempt to extract user.
    if protocol.USER_SEPARATOR in raw:
        nick, user = raw.split(protocol.USER_SEPARATOR)

    return nick, user, host
1109080
def GetAuth(self):
        '''
        '''
        if self.auth: return self.auth
        for elt in self.ps.GetMyHeaderElements():
            if elt.localName == 'BasicAuth' \
            and elt.namespaceURI == ZSI_SCHEMA_URI:
                d = _auth_tc.parse(elt, self.ps)
                self.auth = (AUTH.zsibasic, d['Name'], d['Password'])
                return self.auth
        ba = self.environ.get('HTTP_AUTHENTICATION')
        if ba:
            ba = ba.split(' ')
            if len(ba) == 2 and ba[0].lower() == 'basic':
                ba = _b64_decode(ba[1])
                self.auth = (AUTH.httpbasic,) + tuple(ba.split(':'))
                return self.auth
        self.auth = (AUTH.none,)
        return self.auth
237689
public function parse()
    {
        if (array_key_exists('PHP_AUTH_USER', $_SERVER)) { // mod_php
            $this->name = $_SERVER['PHP_AUTH_USER'];
            $this->password = array_key_exists('PHP_AUTH_PW', $_SERVER) ? $_SERVER['PHP_AUTH_PW'] : null;
        } elseif (array_key_exists('HTTP_AUTHENTICATION', $_SERVER)) { // most other servers
            if (strpos(strtolower($_SERVER['HTTP_AUTHENTICATION']), 'basic') === 0) {
                $userdata = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHENTICATION'], 6)));
                list($this->name, $this->password) = $userdata;
            }
        } elseif (array_key_exists('REDIRECT_HTTP_AUTHORIZATION', $_SERVER)) { // most other servers
            if (strpos(strtolower($_SERVER['REDIRECT_HTTP_AUTHORIZATION']), 'basic') === 0) {
                $userdata = explode(':', base64_decode(substr($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], 6)));
                list($this->name, $this->password) = $userdata;
            }
        }
    }
1022921
def http_auth(self):
        
        if 'HTTP_AUTHORIZATION' in self.request.META.keys():
            authmeth, auth = self.request.META['HTTP_AUTHORIZATION'].split(
                ' ', 1)
            if authmeth.lower() == 'basic':
                auth = auth.strip().decode('base64')
                identifier, password = auth.split(':', 1)
                username = get_username(identifier)
                user = authenticate(username=username, password=password)
                if user:
                    login(self.request, user)
                    return True
582721
def process_basic_auth(auth)
      case auth
        when String
          self.username, self.password = auth.split(':', 2)
        when Hash
          self.username = auth[:username]
          self.password = auth[:password]
      end
    end
75387
def www_authenticate(self):
        """"""
        def on_update(www_auth):
            if not www_auth and 'www-authenticate' in self.headers:
                del self.headers['www-authenticate']
            elif www_auth:
                self.headers['WWW-Authenticate'] = www_auth.to_header()
        header = self.headers.get('www-authenticate')
        return parse_www_authenticate_header(header, on_update)
614977
function _getDigestAuthHeader (headers) {
    return headers.find(function (property) {
        return (property.key.toLowerCase() === WWW_AUTHENTICATE) && (_.startsWith(property.value, DIGEST_PREFIX));
    });
}
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)
551866
def http_basic_auth_login_required(func=None):
    """"""

    wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_authenticated])

    # If @http_basic_auth_login_required() is used (with parenthesis)
    if func is None:
        return wrapper

    # If @http_basic_auth_login_required is used without parenthesis
    return wrapper(func)
1096786
private Creds parseAuthorizationBasic(String authHeader) {
        String userpassEncoded = authHeader.substring(6);
        String data = StringUtils.newStringUtf8(Base64.decodeBase64(userpassEncoded));
        int sepIdx = data.indexOf(':');
        if (sepIdx > 0) {
            String username = data.substring(0, sepIdx);
            String password = data.substring(sepIdx + 1);
            return new Creds(username, password);
        } else {
            return new Creds(data, null);
        }
    }
309828
def parse_http_header(header_line):
    

    header_line = header_line.decode().strip()
    col_idx = header_line.find(':')

    if col_idx < 1:
        raise BadHttpHeaderError('Bad header: {}'.format(repr(header_line)))

    key = header_line[0:col_idx].strip()
    value = header_line[(col_idx+1):].strip()
    return HttpHeader(key=key, value=value)
144760
def parse_session_token(response_headers):
        

        # extract session token from response header
        session_token = ''
        if http_constants.HttpHeaders.SessionToken in response_headers:
                session_token = response_headers[http_constants.HttpHeaders.SessionToken]

        id_to_sessionlsn = {}
        if session_token is not '':
            ''' extract id, lsn from the token. For p-collection,
            the token will be a concatenation of pairs for each collection'''
            token_pairs = session_token.split(',')
            for token_pair in token_pairs:
                tokens = token_pair.split(':')
                if (len(tokens) == 2):
                    id = tokens[0]
                    sessionToken = VectorSessionToken.create(tokens[1])
                    if sessionToken is None:
                        raise HTTPFailure(http_constants.StatusCodes.INTERNAL_SERVER_ERROR, "Could not parse the received session token: %s" % tokens[1])
                    id_to_sessionlsn[id] = sessionToken
        return id_to_sessionlsn
407794
def parse_authn_request(self, enc_request, binding=BINDING_HTTP_REDIRECT):
        

        return self._parse_request(enc_request, AuthnRequest,
                                   "single_sign_on_service", binding)
457749
def parse(self, charset=None, headers=None):
        

        if headers:
            self.headers = headers
        else:
            # Parse headers only from last response
            # There could be multiple responses in `self.head`
            # in case of 301/302 redirect
            # Separate responses
            if self.head:
                responses = self.head.rsplit(b'\nHTTP/', 1)
                # Cut off the 'HTTP/*' line from the last response
                _, response = responses[-1].split(b'\n', 1)
                response = response.decode('utf-8', 'ignore')
            else:
                response = u''
            if six.PY2:
                # email_from_string does not work with unicode input
                response = response.encode('utf-8')
            self.headers = email.message_from_string(response)

        if charset is None:
            if isinstance(self.body, six.text_type):
                self.charset = 'utf-8'
            else:
                self.detect_charset()
        else:
            self.charset = charset.lower()

        self._unicode_body = None
527357
def get_auth_from_url(url):
    
    parsed = urlparse(url)

    try:
        auth = (unquote(parsed.username), unquote(parsed.password))
    except (AttributeError, TypeError):
        auth = ('', '')

    return auth
1220826
def http_digest(r, username, password):
    

    def handle_401(r):
        """Takes the given response and tries digest-auth, if needed."""

        s_auth = r.headers.get('www-authenticate', '')

        if 'digest' in s_auth.lower():

            last_nonce = ''
            nonce_count = 0

            chal = parse_dict_header(s_auth.replace('Digest ', ''))

            realm = chal['realm']
            nonce = chal['nonce']
            qop = chal.get('qop')
            algorithm = chal.get('algorithm', 'MD5')
            opaque = chal.get('opaque', None)

            algorithm = algorithm.upper()
            # lambdas assume digest modules are imported at the top level
            if algorithm == 'MD5':
                H = lambda x: hashlib.md5(x).hexdigest()
            elif algorithm == 'SHA':
                H = lambda x: hashlib.sha1(x).hexdigest()
            # XXX MD5-sess
            KD = lambda s, d: H("%s:%s" % (s, d))

            if H is None:
                return None

            # XXX not implemented yet
            entdig = None
            p_parsed = urlparse(r.request.url)
            path = p_parsed.path + p_parsed.query

            A1 = "%s:%s:%s" % (username, realm, password)
            A2 = "%s:%s" % (r.request.method, path)

            if qop == 'auth':
                if nonce == last_nonce:
                    nonce_count += 1
                else:
                    nonce_count = 1
                    last_nonce = nonce

                ncvalue = '%08x' % nonce_count
                cnonce = (hashlib.sha1("%s:%s:%s:%s" % (
                    nonce_count, nonce, time.ctime(), randombytes(8)))
                    .hexdigest()[:16]
                )
                noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
                respdig = KD(H(A1), noncebit)
            elif qop is None:
                respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
            else:
                # XXX handle auth-int.
                return None

            # XXX should the partial digests be encoded too?
            base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
                   'response="%s"' % (username, realm, nonce, path, respdig)
            if opaque:
                base += ', opaque="%s"' % opaque
            if entdig:
                base += ', digest="%s"' % entdig
            base += ', algorithm="%s"' % algorithm
            if qop:
                base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)


            r.request.headers['Authorization'] = 'Digest %s' % (base)
            r.request.send(anyway=True)
            _r = r.request.response
            _r.history.append(r)

            return _r

        return r

    r.hooks['response'] = handle_401
    return r