API to authorize HDFS access. This logins in the configured user via the keytab. If the user is
already logged in then it renews the TGT.
550274
public void authorize() {
    if (this.isSecurityEnabled) {
      try {
        login(this.keytabPrincipal, this.keytabPath);
      } catch (final IOException e) {
        log.error(e);
        throw new AzkabanException(String.format(
            "Error: Unable to authorize to Hadoop. Principal: %s Keytab: %s", this.keytabPrincipal,
            this.keytabPath));
      }
    }
  }
788792
def grant_user_access(self, instance, user, db_names, strict=True):
        
        return instance.grant_user_access(user, db_names, strict=strict)
657681
def auth_view(name, **kwargs):
    
    ctx = Context(**kwargs)
    ctx.execute_action('auth:group:view', **{
        'storage': ctx.repo.create_secure_service('storage'),
        'name': name,
    })
1268871
def accessible_to(self, user):
        
        if user.is_superuser:
            try:
                queryset = self.get_queryset()
            except AttributeError:
                queryset = self
        elif user.is_authenticated():
            # get user group (higher id)
            group = user.groups.all().order_by('-id')[0]
            queryset = self.filter(access_level__lte=ACCESS_LEVELS.get(group.name))
        else:
            queryset = self.filter(access_level__lte=ACCESS_LEVELS.get('public'))
        return queryset
1175409
private void loginHadoopUser(Subject subject) {
        Class<?> ugi = null;
        try {
            ugi = Class.forName("org.apache.hadoop.security.UserGroupInformation");
        } catch (ClassNotFoundException e) {
            LOG.info("Hadoop was not found on the class path");
            return;
        }
        try {
            Method isSecEnabled = ugi.getMethod("isSecurityEnabled");
            if (!((Boolean) isSecEnabled.invoke(null))) {
                LOG.warn("Hadoop is on the classpath but not configured for " + "security, if you want security you need to be sure that "
                        + "hadoop.security.authentication=kerberos in core-site.xml " + "in your jar");
                return;
            }

            try {
                Method login = ugi.getMethod("loginUserFromSubject", Subject.class);
                login.invoke(null, subject);
            } catch (NoSuchMethodException me) {
                // The version of Hadoop does not have the needed client changes.
                // So don't look now, but do something really ugly to work around it.
                // This is because we are reaching into the hidden bits of Hadoop security, and it works for now, but may stop at any point in time.

                // We are just trying to do the following
                // Configuration conf = new Configuration();
                // HadoopKerberosName.setConfiguration(conf);
                // subject.getPrincipals().add(new User(tgt.getClient().toString(), AuthenticationMethod.KERBEROS, null));
                String name = getTGT(subject).getClient().toString();

                LOG.warn("The Hadoop client does not have loginUserFromSubject, Trying to hack around it. This may not work...");
                Class<?> confClass = Class.forName("org.apache.hadoop.conf.Configuration");
                Constructor confCons = confClass.getConstructor();
                Object conf = confCons.newInstance();
                Class<?> hknClass = Class.forName("org.apache.hadoop.security.HadoopKerberosName");
                Method hknSetConf = hknClass.getMethod("setConfiguration", confClass);
                hknSetConf.invoke(null, conf);

                Class<?> authMethodClass = Class.forName("org.apache.hadoop.security.UserGroupInformation$AuthenticationMethod");
                Object kerbAuthMethod = null;
                for (Object authMethod : authMethodClass.getEnumConstants()) {
                    if ("KERBEROS".equals(authMethod.toString())) {
                        kerbAuthMethod = authMethod;
                        break;
                    }
                }

                Class<?> userClass = Class.forName("org.apache.hadoop.security.User");
                Constructor userCons = userClass.getConstructor(String.class, authMethodClass, LoginContext.class);
                userCons.setAccessible(true);
                Object user = userCons.newInstance(name, kerbAuthMethod, null);
                subject.getPrincipals().add((Principal) user);
            }
        } catch (Exception e) {
            LOG.warn("Something went wrong while trying to initialize Hadoop through reflection. This version of hadoop may not be compatible.", e);
        }
    }
1140021
public Credential createBigQueryCredential(Configuration config)
      throws GeneralSecurityException, IOException {
    Credential credential =
        CredentialFromAccessTokenProviderClassFactory.credential(
            new AccessTokenProviderClassFromConfigFactory().withOverridePrefix("mapred.bq"),
            config,
            BIGQUERY_OAUTH_SCOPES);
    if (credential != null) {
      return credential;
    }

    return HadoopCredentialConfiguration.newBuilder()
        .withConfiguration(config)
        .withOverridePrefix(BIGQUERY_CONFIG_PREFIX)
        .build()
        .getCredential(BIGQUERY_OAUTH_SCOPES);
  }
455542
def authenticate(self, api_key):
        """"""
        self._api_key = api_key

        # Attach auth to session.
        self._session.auth = ('', self._api_key)

        return self._verify_api_key()
846471
def init_with_keytab(self):
        """"""
        creds_opts = {
            'usage': 'initiate',
            'name': self._cleaned_options['principal'],
        }

        store = {}
        if self._cleaned_options['keytab'] != DEFAULT_KEYTAB:
            store['client_keytab'] = self._cleaned_options['keytab']
        if self._cleaned_options['ccache'] != DEFAULT_CCACHE:
            store['ccache'] = self._cleaned_options['ccache']
        if store:
            creds_opts['store'] = store

        creds = gssapi.creds.Credentials(**creds_opts)
        try:
            creds.lifetime
        except gssapi.exceptions.ExpiredCredentialsError:
            new_creds_opts = copy.deepcopy(creds_opts)
            # Get new credential and put it into a temporary ccache
            if 'store' in new_creds_opts:
                new_creds_opts['store']['ccache'] = _get_temp_ccache()
            else:
                new_creds_opts['store'] = {'ccache': _get_temp_ccache()}
            creds = gssapi.creds.Credentials(**new_creds_opts)
            # Then, store new credential back to original specified ccache,
            # whatever a given ccache file or the default one.
            _store = None
            # If default cccache is used, no need to specify ccache in store
            # parameter passed to ``creds.store``.
            if self._cleaned_options['ccache'] != DEFAULT_CCACHE:
                _store = {'ccache': store['ccache']}
            creds.store(usage='initiate', store=_store, overwrite=True)
1369199
private User authcz(final Cache<AuthCredentials, User> cache, Cache<User, Set<String>> roleCache, final AuthCredentials ac,
            final AuthenticationBackend authBackend, final Set<AuthorizationBackend> authorizers) {
        if (ac == null) {
            return null;
        }
        try {

            //noop backend configured and no authorizers
            //that mean authc and authz was completely done via HTTP (like JWT or PKI)
            if (authBackend.getClass() == NoOpAuthenticationBackend.class && authorizers.isEmpty()) {
                //no cache
                return authBackend.authenticate(ac);
            }

            return cache.get(ac, new Callable<User>() {
                @Override
                public User call() throws Exception {
                    if (log.isTraceEnabled()) {
                        log.trace("Credentials for user " + ac.getUsername() + " not cached, return from " + authBackend.getType()
                                + " backend directly");
                    }
                    final User authenticatedUser = authBackend.authenticate(ac);
                    authz(authenticatedUser, roleCache, authorizers);

                    return authenticatedUser;
                }
            });
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Can not authenticate " + ac.getUsername() + " due to " + e.toString(), e);
            }
            return null;
        } finally {
            ac.clearSecrets();
        }
    }
520514
def set_credential_password(self, access_id, password):
        

        return self.client.call('Network_Storage_Allowed_Host', 'setCredentialPassword',
                                password, id=access_id)
1076931
def _auth(self):
        
        ts = datetime.datetime.now().strftime("%Y-%m-%d%H:%M:%S")
        hash_string = hashlib.md5("%s%s%s" % (ts, self.private_key, self.public_key)).hexdigest()
        return "ts=%s&apikey=%s&hash=%s" % (ts, self.public_key, hash_string)
737684
def verify_permitted_to_read(gs_path):
    
    # TODO(qimingj): Storage APIs need to be modified to allow absence of project
    #                or credential on Items. When that happens we can move the function
    #                to Items class.
    from . import _bucket
    bucket, prefix = _bucket.parse_name(gs_path)
    credentials = None
    if datalab.context.Context.is_signed_in():
      credentials = datalab.context._utils.get_credentials()
    args = {
        'maxResults': Api._MAX_RESULTS,
        'projection': 'noAcl'
    }
    if prefix is not None:
      args['prefix'] = prefix
    url = Api._ENDPOINT + (Api._OBJECT_PATH % (bucket, ''))
    try:
      datalab.utils.Http.request(url, args=args, credentials=credentials)
    except datalab.utils.RequestException as e:
      if e.status == 401:
        raise Exception('Not permitted to read from specified path. '
                        'Please sign in and make sure you have read access.')
      raise e
1085967
def _is_authenticated(self):
        """"""
        if not self.auth_api_client.is_valid_api_key():
            raise CartoException(
                'Cannot authenticate user `{}`. Check credentials.'.format(
                    self.creds.username()))
108550
function AuthDB(options) {
  if (!(this instanceof AuthDB))
    return new AuthDB(options);

  this.logger = Logger.global;
  this.resolve = dns.lookup;
  this.prefix = null;
  this.dnsKnown = [];

  this.known = new Map();
  this.authorized = [];

  this._init(options);
}
70251
function SharedKeyTable(storageAccount, storageAccessKey) {
  this.storageAccount = storageAccount;
  this.storageAccessKey = storageAccessKey;
  this.signer = new HmacSha256Sign(storageAccessKey);
}
759500
def authenticate(self):
        
        # Make sure we've stored uri for use
        predix.config.set_env_value(self.use_class, 'uri', self._get_uri())

        self.uaac = predix.security.uaa.UserAccountAuthentication()
        self.uaac.authenticate('admin', self._get_admin_secret(),
                use_cache=False)
        self.is_admin = True
1072138
public function authorize(): bool
    {
        $twoFactor = $this->user($this->route('guard'))->getTwoFactor();

        if (! $twoFactor['totp']['enabled']) {
            throw new GenericException(trans('cortex/auth::messages.verification.twofactor.totp.cant_backup'), route('adminarea.account.settings'));
        }

        return true;
    }