Set up basic auth for the client
    @param username: Login name.
    @param password: Login password.
    @param realm: The authentication realm.
    @return: The current object
6707
def set_basic_auth(self, username, password, realm):
    
    self._passmgr.add_password(realm, self._base_url, username, password)
    return self
219363
def set_basic_auth(self, username, password):
        """"""
        credentials = str(b64encode('{}:{}'.format(username, password).encode('utf-8')), 'utf-8')
        self.authorization = 'Basic {}'.format(credentials)
295993
public RequestBuilder basicAuth(String user, String password) {
        this.basicAuth = new BasicAuth(user, password);
        return this;
    }
451212
public void authenticateAndSignin(String username, String password) {
		logger.debug("authenticateAndSignin:" + username);

		Authentication request = new UsernamePasswordAuthenticationToken(username, password);
		Authentication result = authenticationManager.authenticate(request);
		SecurityContextHolder.getContext().setAuthentication(result);
	}
654476
def basicauth(self, realm = b'all', nofail = False):
        ""
        if b'authorization' in self.headerdict:
            auth = self.headerdict[b'authorization']
            auth_pair = auth.split(b' ', 1)
            if len(auth_pair) < 2:
                raise HttpInputException('Authorization header is malformed')
            if auth_pair[0].lower() == b'basic':
                try:
                    userpass = base64.b64decode(auth_pair[1])
                except Exception:
                    raise HttpInputException('Invalid base-64 string')
                userpass_pair = userpass.split(b':', 1)
                if len(userpass_pair) != 2:
                    raise HttpInputException('Authorization header is malformed')
                return userpass_pair
        if nofail:
            return (None, None)
        else:
            self.basicauthfail(realm)
914676
def _auth_session(self, username, password):
        
        api = self.api[self.account]['auth']
        endpoint = api.get('endpoint', self.api[self.account]['endpoint'])
        session = requests.Session()
        session_retries = Retry(total=10, backoff_factor=0.5)
        session_adapter = requests.adapters.HTTPAdapter(max_retries=session_retries)
        session.mount('https://', session_adapter)
        response = session.request('GET', endpoint + api['GET'].get('url', '/'))
        dom = Provider._filter_dom(response.text, api['filter'])
        data = Provider._extract_hidden_data(dom)
        data[api['user']], data[api['pass']] = username, password
        response = session.request('POST', endpoint + api['POST']['url'], data=data)
        if Provider._filter_dom(response.text, api['filter']):
            LOGGER.error('Hetzner => Unable to authenticate session with %s account \'%s\': '
                         'Invalid credentials',
                         self.account, username)
            raise AssertionError
        LOGGER.info('Hetzner => Authenticate session with %s account \'%s\'',
                    self.account, username)
        return session
245789
public static Action unauthorized(final String realm) {
        return new Action(r -> {
            r.addHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
            r.setStatus(HttpStatus.UNAUTHORIZED_401);
            return r;
        });
    }
1104694
def auth_basic(check, realm="private", text="Access denied"):
    '''  '''
    def decorator(func):
        def wrapper(*a, **ka):
            user, password = request.auth or (None, None)
            if user is None or not check(user, password):
                err = HTTPError(401, text)
                err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
                return err
            return func(*a, **ka)
        return wrapper
    return decorator
1197142
public T authentication(String username, String password, boolean allowAnyHost) {
        if (StringUtils.isNotBlank(username)) {
            if (defaultHost == null || StringUtils.isBlank(defaultHost.getHostName())) {
                throw new IllegalStateException("Cannot configure authentication when host is not set.");
            }
            AuthScope authscope = allowAnyHost ?
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM) :
                    new AuthScope(defaultHost.getHostName(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            credsProvider.setCredentials(authscope, new UsernamePasswordCredentials(username, password));
        }
        return self();
    }
600497
public RestTemplateBuilder basicAuthentication(String username, String password) {
		return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
				this.messageConverters, this.requestFactorySupplier,
				this.uriTemplateHandler, this.errorHandler,
				new BasicAuthenticationInterceptor(username, password),
				this.restTemplateCustomizers, this.requestFactoryCustomizer,
				this.interceptors);
	}
796239
def _login(self, username, password):
        '''
        '''
        logger.debug('login in as user "%s"' % username)
        url = self._build_url('/auth')
        payload = {'username': username, 'password': password}
        res = self._session.post(url, json=payload)
        res.raise_for_status()
        self._access_token = res.json()['access_token']
        self._session.headers.update(
            {'Authorization': 'JWT %s' % self._access_token}
        )
1192499
def _setup_authentication(self, username, password):
        ''''''

        ## BUG WORKAROUND
        if self.version < 1.1:
            # Version 1.0 had a bug when using the key parameter.
            # Later versions have the opposite bug (a key in the username doesn't function)
            if not username:
                username = self._key
                self._key = None

        if not username:
            return
        if not password:
            password = '12345'  #the same combination on my luggage!  (required dummy value)

        #realm = 'Redmine API' - doesn't always work
        # create a password manager
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

        password_mgr.add_password(None, self._url, username, password )
        handler = urllib2.HTTPBasicAuthHandler( password_mgr )

        # create "opener" (OpenerDirector instance)
        self._opener = urllib2.build_opener( handler )

        # set the opener when we fetch the URL
        self._opener.open( self._url )

        # Install the opener.
        urllib2.install_opener( self._opener )
1017634
def authDomainUser(self, realmname, username, password, environ):
        """"""
        try:
            apikey = self.user_manager.get_user_api_key(username, create=None)
            return apikey is not None and password == apikey
        except:
            return False
954112
def http_basic(r, username, password):
    
    username = str(username)
    password = str(password)

    auth_s = b64encode('%s:%s' % (username, password))
    r.headers['Authorization'] = ('Basic %s' % auth_s)

    return r
46210
protected static HttpClientBuilder addAuthentication(final HttpClientBuilder builder, 
            final URI uri, final String username,
            String password) {
        if (isNotBlank(username)) {
            CredentialsProvider provider = new BasicCredentialsProvider();
            AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), "realm");
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
            provider.setCredentials(scope, credentials);
            builder.setDefaultCredentialsProvider(provider);

            builder.addInterceptorFirst(new PreemptiveAuth());
        }
        return builder;
    }
539725
def authenticate_account(self, authc_token):
        
        try:
            identifier = authc_token.identifier
        except AttributeError:
            msg = 'Failed to obtain authc_token.identifiers'
            raise AttributeError(msg)

        tc = authc_token.__class__
        try:
            verifier = self.token_resolver[tc]
        except KeyError:
            raise TypeError('realm does not support token type: ', tc.__name__)

        account = self.get_authentication_info(identifier)

        try:
            if account.get('account_locked'):
                msg = "Account Locked:  {0} locked at: {1}".\
                    format(account['account_id'], account['account_locked'])
                raise LockedAccountException(msg)
        except (AttributeError, TypeError):
            if not account:
                msg = "Could not obtain account credentials for: " + str(identifier)
                raise AccountException(msg)

        self.assert_credentials_match(verifier, authc_token, account)

        return account
181117
def basic_auth(self, response=None):
        """"""
        auth = request.authorization
        if auth and self._login_checker({'username': auth.username,
                                         'password': auth.password}):
            session['simple_logged_in'] = True
            session['simple_basic_auth'] = True
            session['simple_username'] = auth.username
            return response or True
        else:
            headers = {'WWW-Authenticate': 'Basic realm="Login Required"'}
            return 'Invalid credentials', 401, headers