retrieve delegation token for the given user
979492
public String getDelegationToken(String owner, String renewer) throws HiveSQLException {
    if (saslServer == null) {
      throw new HiveSQLException(
          "Delegation token only supported over kerberos authentication", "08S01");
    }

    try {
      String tokenStr = saslServer.getDelegationTokenWithService(owner, renewer, HS2_CLIENT_TOKEN);
      if (tokenStr == null || tokenStr.isEmpty()) {
        throw new HiveSQLException(
            "Received empty retrieving delegation token for user " + owner, "08S01");
      }
      return tokenStr;
    } catch (IOException e) {
      throw new HiveSQLException(
          "Error retrieving delegation token for user " + owner, "08S01", e);
    } catch (InterruptedException e) {
      throw new HiveSQLException("delegation token retrieval interrupted", "08S01", e);
    }
  }
900497
def get_current_user():
    
    process = OpenProcessToken(
        ctypes.windll.kernel32.GetCurrentProcess(), TokenAccess.TOKEN_QUERY
    )
    return GetTokenInformation(process, TOKEN_USER)
1200606
def get_token(required_role: Roles::PUBLIC)
        token = params[:token]

        # Look up the cache. If present, use it and skip the verification.
        # Use token itself (and not a session UUID) as part of the key so
        # it can be considered *verified*.
        @auth_session = Cache.get(kind: :session, token: token)

        # Cache miss. So proceed to verify the token and get user and
        # session data from database. Then set the cache for later.
        if @auth_session.nil?
          @auth_session = verify_token(token)
          @auth_session.role  # NOTE: no-op
          Cache.set({kind: :session, token: token}, @auth_session)
        end

        # Obtained session may not have enough permission. Check here.
        if @auth_session.role < required_role
          logger.error("Not enough permission (role: #{@auth_session.role})")
          raise UNAUTHORIZED_ERROR, "Invalid token"
        end
        @auth_user = @auth_session.user
        @token = @auth_session.token
        return true
      end
620624
function getUsernameByToken(token) {
  for(var username in authTable) {
    if(authTable[username].indexOf(token) > -1) {
      return username;
    }
  }
  return null;
}
279561
def get_authorization(self, **kwargs):
        """"""
        if self.authorization is not None:
            return self.authorization

        auth_class = self.get_authorization_class()
        auth_user = self.get_authorization_user()
        auth_kwargs = {
            'token': self.get_authorization_token(**kwargs)
        }

        if auth_user and auth_user.is_authenticated():
            auth_kwargs['created_user'] = self.get_authorization_user()

        self.authorization = auth_class.objects.get_by_token_or_404(
            **auth_kwargs
        )
        return self.authorization
191282
def get_user(self, validated_token):
        
        if api_settings.USER_ID_CLAIM not in validated_token:
            # The TokenUser class assumes tokens will have a recognizable user
            # identifier claim.
            raise InvalidToken(_('Token contained no recognizable user identification'))

        return TokenUser(validated_token)
688159
function(req, res, user) {
    var jsonWebTokens = waterlock.config.jsonWebTokens || {};
    var expiryUnit = (jsonWebTokens.expiry && jsonWebTokens.expiry.unit) || 'days';
    var expiryLength = (jsonWebTokens.expiry && jsonWebTokens.expiry.length) || 7;
    var expires = moment().add(expiryLength, expiryUnit).valueOf();
    var issued = Date.now();
    user = user || req.session.user;

    var token = jwt.encode({
      iss: user.id + '|' + req.remoteAddress,
      sub: jsonWebTokens.subject,
      aud: jsonWebTokens.audience,
      exp: expires,
      nbf: issued,
      iat: issued,
      jti: uuid.v1()
    }, jsonWebTokens.secret);

    return {
      token: token,
      expires: expires
    };
  }
732507
private void initializeDelegationTokenSupport(Configuration config, URI path) throws IOException {
    logger.atFine().log("GHFS.initializeDelegationTokenSupport");
    // Load delegation token binding, if support is configured
    GcsDelegationTokens dts = new GcsDelegationTokens();
    Text service = new Text(getScheme() + "://" + path.getAuthority());
    dts.bindToFileSystem(this, service);
    try {
      dts.init(config);
      delegationTokens = dts;
      if (delegationTokens.isBoundToDT()) {
        logger.atFine().log(
            "GHFS.initializeDelegationTokenSupport: Using existing delegation token.");
      }
    } catch (IllegalStateException e) {
      logger.atInfo().log("GHFS.initializeDelegationTokenSupport: %s", e.getMessage());
    }
  }
480585
def _win_user_token_is_admin(user_token):
    '''
    
    '''
    class SID_IDENTIFIER_AUTHORITY(ctypes.Structure):
        _fields_ = [
            ("byte0", ctypes.c_byte),
            ("byte1", ctypes.c_byte),
            ("byte2", ctypes.c_byte),
            ("byte3", ctypes.c_byte),
            ("byte4", ctypes.c_byte),
            ("byte5", ctypes.c_byte),
        ]
    nt_authority = SID_IDENTIFIER_AUTHORITY()
    nt_authority.byte5 = 5

    SECURITY_BUILTIN_DOMAIN_RID = 0x20
    DOMAIN_ALIAS_RID_ADMINS = 0x220
    administrators_group = ctypes.c_void_p()
    if ctypes.windll.advapi32.AllocateAndInitializeSid(
            ctypes.byref(nt_authority),
            2,
            SECURITY_BUILTIN_DOMAIN_RID,
            DOMAIN_ALIAS_RID_ADMINS,
            0, 0, 0, 0, 0, 0,
            ctypes.byref(administrators_group)) == 0:
        raise Exception("AllocateAndInitializeSid failed")

    try:
        is_admin = ctypes.wintypes.BOOL()
        if ctypes.windll.advapi32.CheckTokenMembership(
                user_token,
                administrators_group,
                ctypes.byref(is_admin)) == 0:
            raise Exception("CheckTokenMembership failed")
        return is_admin.value != 0

    finally:
        ctypes.windll.advapi32.FreeSid(administrators_group)
774346
public int getExpiresIn(String tokenGrantType, String scope) {
        int expiresIn = Integer.MAX_VALUE;
        List<Scope> scopes = loadScopes(scope);
        boolean ccGrantType = TokenRequest.CLIENT_CREDENTIALS.equals(tokenGrantType);
        if (TokenRequest.CLIENT_CREDENTIALS.equals(tokenGrantType)) {
            for (Scope s : scopes) {
                if (s.getCcExpiresIn() < expiresIn) {
                    expiresIn = s.getCcExpiresIn();
                }
            }
        } else if (TokenRequest.PASSWORD.equals(tokenGrantType)) {
            for (Scope s : scopes) {
                if (s.getPassExpiresIn() < expiresIn) {
                    expiresIn = s.getPassExpiresIn();
                }
            }
        } else {
            // refresh_token
            for (Scope s : scopes) {
                if (s.getRefreshExpiresIn() < expiresIn) {
                    expiresIn = s.getRefreshExpiresIn();
                }
            }
        }
        if (scopes.size() == 0 || expiresIn == Integer.MAX_VALUE) {
            expiresIn = (ccGrantType) ? OAuthConfig.DEFAULT_CC_EXPIRES_IN : OAuthConfig.DEFAULT_PASSWORD_EXPIRES_IN;
        }
        return expiresIn;
    }
189740
@SuppressWarnings("OptionalGetWithoutIsPresent")
  public Token<DelegationTokenIdentifier> getBoundOrNewDT(String renewer) throws IOException {
    logger.atFine().log("Delegation token requested");
    if (isBoundToDT()) {
      // the FS was created on startup with a token, so return it.
      logger.atFine().log("Returning current token");
      return getBoundDT();
    }

    // not bound to a token, so create a new one.
    // issued DTs are not cached so that long-lived filesystems can
    // reliably issue session/role tokens.
    return tokenBinding.createDelegationToken(renewer);
  }
273291
def _get_client_and_key(url, user, password, verbose=0):
    '''
    
    '''
    session = {}
    session['client'] = six.moves.xmlrpc_client.Server(url, verbose=verbose, use_datetime=True)
    session['key'] = session['client'].auth.login(user, password)

    return session
960719
def _token_auth(self):
        """"""
        return TcExTokenAuth(
            self,
            self.args.tc_token,
            self.args.tc_token_expires,
            self.args.tc_api_path,
            self.tcex.log,
        )
15696
def get_owner_access_token(self):
        """"""
        from .database import Session
        db_session = Session.object_session(self)
        owner = db_session.query(User).filter_by(
            id_=self.owner_id).first()
        return owner.access_token
1218474
def grant_member(context, request):
    """"""
    mapping = request.json['mapping']
    for entry in mapping:
        user = entry['user']
        roles = entry['roles']
        username = user.get('username', None)
        userid = user.get('userid', None)
        if userid:
            u = context.get_user_by_userid(userid)
        elif username:
            u = context.get_user_by_username(username)
        else:
            u = None
        if u is None:
            raise UnprocessableError(
                'User %s does not exists' % (userid or username))
        for rolename in roles:
            context.grant_member_role(u.userid, rolename)
    return {'status': 'success'}
814144
def get_user_token(self, scope, code=None):
        """"""

        user_token = self.__get_user_token(scope)

        if user_token:
            return user_token

        if self.__cache is not None:
            token = self.__cache.get(self.__user_token_cache_key())
            if token:
                return token

        if self.__redirect_uri is None or code is None:
            raise MxitAPIParameterException()

        self.__user_token = None

        payload = {
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': self.__redirect_uri
        }

        url = settings.AUTH_ENDPOINT + '/token'
        r = post(url, data=payload, auth=HTTPBasicAuth(self.__client_id, self.__client_secret), verify=self.__verify_cert)
        if r.status_code == 200:
            data = r.json()
            self.__set_user_token(scope, data[u'access_token'])
            if self.__cache is not None:
                self.__cache.set(self.__user_token_cache_key(scope), str(data[u'access_token']),
                                 data[u'expires_in'] - 300)

        user_token = self.__get_user_token(scope)

        if not user_token:
            raise MxitAPIException("Failed to retrieve user token for '%s' scope" % scope)

        return user_token
1325854
def fetch_token(self, **kwargs):
        """"""
        return super(AsanaOAuth2Session, self).fetch_token(self.token_url, client_secret=self.client_secret, **kwargs)