Authentication hook to allow plugging in custom authentication credential providers
552077
def get_auth(host, app_name, database_name):
    
    from .hooks import _get_auth_hook
    return _get_auth_hook(host, app_name, database_name)
1240420
public static LuisRuntimeAPI authenticate(EndpointAPI endpointAPI, ServiceClientCredentials credentials) {
        return authenticate(String.format("https://%s/luis/v2.0/", endpointAPI.toString()), credentials)
            .withEndpoint(endpointAPI.toString());
    }
103844
def set_credentials(self, username, password=None, region=None,
            tenant_id=None, authenticate=False):
        
        self.api_key = None
        super(RaxIdentity, self).set_credentials(username, password=password,
                region=region, tenant_id=tenant_id, authenticate=authenticate)
1172195
def _authenticate_plain(credentials, sock_info):
    
    source = credentials.source
    username = credentials.username
    password = credentials.password
    payload = ('\x00%s\x00%s' % (username, password)).encode('utf-8')
    cmd = SON([('saslStart', 1),
               ('mechanism', 'PLAIN'),
               ('payload', Binary(payload)),
               ('autoAuthorize', 1)])
    sock_info.command(source, cmd)
1123680
def _require_authenticate(func):
    ''''''

    def wrapped(self):
        if not hasattr(self, 'authenticated'):
            self.authenticated = None
        if self.authenticated:
            return func(self)

        auth = self.headers.get(u'Authorization')
        if auth is None:
            msg = u"You are not allowed to access this page. Please login first!"
            return _error_401(self, msg)

        token, fields = auth.split(' ', 1)
        if token != 'Digest':
            return _error_401(self, 'Unsupported authentication type')

        # Check the header fields of the request.
        cred = parse_http_list(fields)
        cred = parse_keqv_list(cred)
        keys = u'realm', u'username', u'nonce', u'uri', u'response'
        if not all(cred.get(key) for key in keys):
            return _error_401(self, 'Incomplete authentication header')
        if cred['realm'] != self.server.realm:
            return _error_401(self, 'Incorrect realm')
        if 'qop' in cred and ('nc' not in cred or 'cnonce' not in cred):
            return _error_401(self, 'qop with missing nc or cnonce')

        # Check the username.
        username = cred['username']
        password = self.server.get_password(username)
        if not username or password is None:
            return _error_401(self, 'Invalid username or password')

        # Check the digest string.
        location = u'%s:%s' % (self.command, self.path)
        location = md5hex(location.encode('utf8'))
        pwhash = md5hex('%s:%s:%s' % (username, self.server.realm, password))

        if 'qop' in cred:
            info = (cred['nonce'],
                    cred['nc'],
                    cred['cnonce'],
                    cred['qop'],
                    location)
        else:
            info = cred['nonce'], location

        expect = u'%s:%s' % (pwhash, ':'.join(info))
        expect = md5hex(expect.encode('utf8'))
        if expect != cred['response']:
            return _error_401(self, 'Invalid username or password')

        # Success!
        self.authenticated = True
        return func(self)

    return wrapped
202675
def _build_auth_request(self, verify=False, **kwargs):
        
        json = {
            'domain': self.domain
        }
        
        credential = self.credential
        params = {}
        
        if credential.provider_name.startswith('lms'):
            params = dict(
                login=credential._login,
                pwd=credential._pwd)
        else:
            json.update(authenticationkey=credential._api_key)
        
        if kwargs:
            json.update(**kwargs)
            self._extra_args.update(**kwargs) # Store in case we need to rebuild later
        
        request = dict(
            url=self.credential.get_provider_entry_point(self.url, self.api_version),
            json=json,
            params=params,
            headers={'content-type': 'application/json'},
            verify=verify)
        
        return request
1218542
def authenticated(viewfunc):
    """"""
    @wraps(viewfunc)
    def wrapper(*args, **kwargs):
        ctx = stack.top
        if ctx and hasattr(ctx, 'htauth'):
            auth_header = request.headers.get('Authorization', None)
            if not auth_header:
                return _unauthorized_response()

            if not auth_header.startswith('Basic '):
                raise RuntimeError('Flask-HTAuth supports only Basic auth.')

            auth_header = auth_header.replace('Basic ', '')
            auth_header = base64.b64decode(auth_header)
            username, password = auth_header.split(':', 1)

            if not username in ctx.htauth['users']:
                return _unauthorized_response()

            if not check_password(password, ctx.htauth['users'][username]):
                return _unauthorized_response()

            g.htauth_user = username

        return viewfunc(*args, **kwargs)

    return wrapper
614739
def _build_credentials_tuple(mech, source, user, passwd, extra, database):
    
    if mech != 'MONGODB-X509' and user is None:
        raise ConfigurationError("%s requires a username." % (mech,))
    if mech == 'GSSAPI':
        if source is not None and source != '$external':
            raise ValueError(
                "authentication source must be $external or None for GSSAPI")
        properties = extra.get('authmechanismproperties', {})
        service_name = properties.get('SERVICE_NAME', 'mongodb')
        canonicalize = properties.get('CANONICALIZE_HOST_NAME', False)
        service_realm = properties.get('SERVICE_REALM')
        props = GSSAPIProperties(service_name=service_name,
                                 canonicalize_host_name=canonicalize,
                                 service_realm=service_realm)
        # Source is always $external.
        return MongoCredential(mech, '$external', user, passwd, props, None)
    elif mech == 'MONGODB-X509':
        if passwd is not None:
            raise ConfigurationError(
                "Passwords are not supported by MONGODB-X509")
        if source is not None and source != '$external':
            raise ValueError(
                "authentication source must be "
                "$external or None for MONGODB-X509")
        # user can be None.
        return MongoCredential(mech, '$external', user, None, None, None)
    elif mech == 'PLAIN':
        source_database = source or database or '$external'
        return MongoCredential(mech, source_database, user, passwd, None, None)
    else:
        source_database = source or database or 'admin'
        if passwd is None:
            raise ConfigurationError("A password is required.")
        return MongoCredential(
            mech, source_database, user, passwd, None, _Cache())
261207
def credential_update(self, cred_id, **options):
        
        payload = None

        # First we pull the credentials and populate the payload if we
        # find a match.
        for cred in self.credentials()['credentials']:
            if cred['id'] == str(cred_id):
                payload = {
                    'id': cred_id,
                    'type': cred['type'],
                    'name': cred['name'],
                    'description': cred['description'],
                    'visibility': cred['visibility'],
                    'group': cred['group'],
                    'users': cred['users'],
                }

                if cred['type'] == 'kerberos':
                    payload['ip'] = cred['ip']
                    payload['port'] = cred['port']
                    payload['protocol'] = cred['protocol']
                    payload['realm'] = cred['realm']

                if cred['type'] == 'snmp':
                    payload['communityString'] = cred['communityString']

                if cred['type'] == 'ssh':
                    payload['username'] = cred['username']
                    payload['publickey'] = cred['publickey']
                    payload['privatekey'] = cred['privatekey']
                    payload['priviledgeEscalation'] = cred['priviledgeEscalation']
                    payload['escalationUsername'] = cred['escalationUsername']

                if cred['type'] == 'windows':
                    payload['username'] = cred['username']
                    payload['domain'] = cred['domain']

        if payload is None:
            raise APIError(13, 'cred_id %s does not exist' % cred_id)

        for option in options:
            payload[option] = options[option]

        return self.raw_query('credential', 'edit', data=payload)
1301684
@Override
    public Principal authenticate(String username, String credentials) {
        GenericPrincipal principal = (GenericPrincipal) getPrincipal(username);
        if (null != principal) {
            try {
                if (!PasswordStorage.verifyPassword(credentials, principal.getPassword())) {
                    principal = null;
                }
            } catch (CannotPerformOperationException | InvalidHashException e) {
                LOGR.log(Level.WARNING, e.getMessage());
                principal = null;
            }
        }
        return principal;
    }
471302
def SetCredentials(api_username,api_passwd):
	""""""
	global V2_API_USERNAME
	global V2_API_PASSWD
	global _V2_ENABLED
	_V2_ENABLED = True
	V2_API_USERNAME = api_username
	V2_API_PASSWD = api_passwd
571816
def _on_auth(self, sock, authenticated):  # pylint: disable=unused-argument
        """"""
        def ack(eventname, error, data):  # pylint: disable=unused-argument
            """Ack"""
            if error:
                self.log.error(f"""OnAuth: {error}""")
            else:
                self.connect_channels(self.channels)
                self.post_conn_cb()

        sock.emitack("auth", self.creds, ack)
1183214
function auth(endo, options) {
  options || (options = {});

  //
  // add token utility methods, binding first options arg
  //
  endo.createToken = auth.createToken.bind(null, options.sign);
  endo.verifyToken = auth.verifyToken.bind(null, options.verify);

  //
  // verify provided credentials are valid and set user auth on request
  //
  var _parseRequest = endo.parseRequest;
  endo.parseRequest = function() {
    var request = _parseRequest.apply(this, arguments);
    return Promise.resolve(request).then(this.authenticate.bind(this));
  };

  endo.authenticate = function (request) {
    //
    // no auth if request already contains user auth data
    //
    if (request.user !== undefined) {
      return;
    }

    //
    // parse authorization header for JWT token
    //
    request.headers || (request.headers || {});
    var header = request.headers && request.headers.authorization || '';
    var match = header.match(BEARER_RE);
    if (!match) {
      throw new util.UnauthorizedError('Token required');
    }

    return auth.verifyToken(match[1])
      .then(endo.handleAuthentication.bind(endo, request))
  };

  //
  // implementations may wrap this method perform additional verification
  //
  endo.handleAuthentication = function (request, data) {
    request.user = data || null;
  };

  return endo;
}
547273
def _authn_context_decl(decl, authn_auth=None):
    
    return factory(saml.AuthnContext,
                   authn_context_decl=decl,
                   authenticating_authority=factory(
                       saml.AuthenticatingAuthority, text=authn_auth))
1214526
def add_credential(self, url, username, password):
        
        cur = self.conn.cursor()

        cur.execute("SELECT * FROM credentials WHERE LOWER(username)=LOWER(?) AND password=?", [url, username, password])
        results = cur.fetchall()

        if not len(results):
            cur.execute("INSERT INTO credentials (username, password) VALUES (?,?)", [username, password] )

        cur.close()
90353
def _authGetDBusCookie(self, cookie_context, cookie_id):
        
        # XXX   Ensure we obtain the correct directory for the
        #       authenticating user and that that user actually
        #       owns the keyrings directory

        if self.cookie_dir is None:
            cookie_dir = os.path.expanduser('~/.dbus-keyrings')
        else:
            cookie_dir = self.cookie_dir

        dstat = os.stat(cookie_dir)

        if dstat.st_mode & 0x36:  # 066
            raise Exception('User keyrings directory is writeable by other users. Aborting authentication')

        import pwd
        if dstat.st_uid != pwd.getpwuid(os.geteuid()).pw_uid:
            raise Exception('Keyrings directory is not owned by the current user. Aborting authentication!')
        
        f = open(os.path.join(cookie_dir, cookie_context), 'r')

        try:
            for line in f:
                try:
                    k_id, k_time, k_cookie_hex = line.split()
                    if k_id == cookie_id:
                        return k_cookie_hex
                except:
                    pass
        finally:
            f.close()
1061732
private void loadAuthenticationMethodTypes(ExtensionHook hook) {
		this.authenticationMethodTypes = new ArrayList<>();
		this.authenticationMethodTypes.add(new FormBasedAuthenticationMethodType());
		this.authenticationMethodTypes.add(new HttpAuthenticationMethodType());
		this.authenticationMethodTypes.add(new ManualAuthenticationMethodType());
		this.authenticationMethodTypes.add(new ScriptBasedAuthenticationMethodType());
		this.authenticationMethodTypes.add(new JsonBasedAuthenticationMethodType());

		for (AuthenticationMethodType a : authenticationMethodTypes) {
			a.hook(hook);
		}

		if (log.isInfoEnabled()) {
			log.info("Loaded authentication method types: " + authenticationMethodTypes);
		}
	}