a method to validate active access token
483006
def _validate_token(self):
        
        '''  '''
        
        title = '%s._validate_token' % self.__class__.__name__
    
    # construct access token url
        import requests
        url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % self.access_token
    
    # retrieve access token details
        try:
            token_details = requests.get(url).json()
        except:
            raise DriveConnectionError(title)
        if 'error' in token_details.keys():
            raise ValueError('access_token for google drive account is %s' % token_details['error_description'])
    
    # determine collection space
    # https://developers.google.com/drive/v3/web/about-organization
        if 'scope' in token_details.keys():
            service_scope = token_details['scope']
            if service_scope.find('drive.appfolder') > -1:
                self.drive_space = 'appDataFolder'
                if not self.collection_name:
                    self.collection_name = 'App Data Folder'
            elif service_scope.find('drive.photos.readonly') > -1:
                self.drive_space = 'photos'
                if not self.collection_name:
                    self.collection_name = 'Photos'
    
    # determine permissions
    # https://developers.google.com/drive/v3/web/about-auth
            if service_scope.find('readonly') > -1:
                self.permissions_write = False
            if service_scope.find('readonly.metadata') > -1:
                self.permissions_content = False
          
    # TODO refresh token
        if 'expires_in' in token_details.keys():
            from time import time
            expiration_date = time() + token_details['expires_in']
        if 'issued_to' in token_details.keys():
            client_id = token_details['issued_to']
    
        return token_details
639091
function(tokenStr) {
            if (typeof tokenStr !== 'string') {
                return null;
            }
            var token = tokenCache[tokenStr];
            if (token !== undefined) {
                return token;
            } else {
                try {
                    token = tokens.validate(tokenStr, trustedPubKey);
                    tokenCache[tokenStr] = token;
                    return token;
                } catch (err) {
                    // did not validate, cache negative result.
                    tokenCache[tokenStr] = null;
                    return null;
                }
            }
        }
358581
def validate_access!
        action = self.action_name
        clearance_levels = Array(current_clearance_levels)
        authorized = clearance_levels.any? { |c| keeper.lets? c, action, self.class }
        not_authorized! unless authorized
      end
646935
private String validateAuthn(String value) {
        // for now, if we got here we're validating an authnToken
        String result = null;
        String valueLower = value.toLowerCase();
        do {
            if (valueLower.equals("saml")) {
                result = JAXRSClientConstants.SAML_HANDLER;
                break;
            }
            if (valueLower.equals("oauth")) {
                result = JAXRSClientConstants.OAUTH_HANDLER;
                break;
            }
            if (valueLower.equals("ltpa")) {
                result = JAXRSClientConstants.LTPA_HANDLER;
            }
        } while (false);
        if (result == null) {
            Tr.warning(tc, "warn.invalid.authorization.token.type", value); // CWWKW0061W
        }
        return result;
    }
357901
def validate_csrf_token(self, field):
        """"""
        if current_app.testing:
            return
        super(InvenioBaseForm, self).validate_csrf_token(field)
569581
function validateAskPermission (token) {
  const header = jwt.decode(token)

  return validateToken(token) && header[ASK_CLAIM_KEY]
}
675817
function validateRSAA(action) {
  var validationErrors = [];
  const validCallAPIKeys = [
    'endpoint',
    'options',
    'method',
    'body',
    'headers',
    'credentials',
    'bailout',
    'types',
    'fetch',
    'ok'
  ];
  const validMethods = [
    'GET',
    'HEAD',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS'
  ];
  const validCredentials = ['omit', 'same-origin', 'include'];

  if (!isRSAA(action)) {
    validationErrors.push(
      'RSAAs must be plain JavaScript objects with an [RSAA] property'
    );
    return validationErrors;
  }

  const callAPI = action[RSAA];
  if (!isPlainObject(callAPI)) {
    validationErrors.push('[RSAA] property must be a plain JavaScript object');
  }
  for (let key in callAPI) {
    if (!~validCallAPIKeys.indexOf(key)) {
      validationErrors.push(`Invalid [RSAA] key: ${key}`);
    }
  }

  const {
    endpoint,
    method,
    headers,
    options,
    credentials,
    types,
    bailout,
    fetch,
    ok
  } = callAPI;
  if (typeof endpoint === 'undefined') {
    validationErrors.push('[RSAA] must have an endpoint property');
  } else if (typeof endpoint !== 'string' && typeof endpoint !== 'function') {
    validationErrors.push(
      '[RSAA].endpoint property must be a string or a function'
    );
  }
  if (typeof method === 'undefined') {
    validationErrors.push('[RSAA] must have a method property');
  } else if (typeof method !== 'string') {
    validationErrors.push('[RSAA].method property must be a string');
  } else if (!~validMethods.indexOf(method.toUpperCase())) {
    validationErrors.push(`Invalid [RSAA].method: ${method.toUpperCase()}`);
  }

  if (
    typeof headers !== 'undefined' &&
    !isPlainObject(headers) &&
    typeof headers !== 'function'
  ) {
    validationErrors.push(
      '[RSAA].headers property must be undefined, a plain JavaScript object, or a function'
    );
  }
  if (
    typeof options !== 'undefined' &&
    !isPlainObject(options) &&
    typeof options !== 'function'
  ) {
    validationErrors.push(
      '[RSAA].options property must be undefined, a plain JavaScript object, or a function'
    );
  }
  if (typeof credentials !== 'undefined') {
    if (typeof credentials !== 'string') {
      validationErrors.push(
        '[RSAA].credentials property must be undefined, or a string'
      );
    } else if (!~validCredentials.indexOf(credentials)) {
      validationErrors.push(`Invalid [RSAA].credentials: ${credentials}`);
    }
  }
  if (
    typeof bailout !== 'undefined' &&
    typeof bailout !== 'boolean' &&
    typeof bailout !== 'function'
  ) {
    validationErrors.push(
      '[RSAA].bailout property must be undefined, a boolean, or a function'
    );
  }

  if (typeof types === 'undefined') {
    validationErrors.push('[RSAA] must have a types property');
  } else if (!Array.isArray(types) || types.length !== 3) {
    validationErrors.push('[RSAA].types property must be an array of length 3');
  } else {
    const [requestType, successType, failureType] = types;
    if (
      typeof requestType !== 'string' &&
      typeof requestType !== 'symbol' &&
      !isValidTypeDescriptor(requestType)
    ) {
      validationErrors.push('Invalid request type');
    }
    if (
      typeof successType !== 'string' &&
      typeof successType !== 'symbol' &&
      !isValidTypeDescriptor(successType)
    ) {
      validationErrors.push('Invalid success type');
    }
    if (
      typeof failureType !== 'string' &&
      typeof failureType !== 'symbol' &&
      !isValidTypeDescriptor(failureType)
    ) {
      validationErrors.push('Invalid failure type');
    }
  }

  if (typeof fetch !== 'undefined') {
    if (typeof fetch !== 'function') {
      validationErrors.push('[RSAA].fetch property must be a function');
    }
  }

  if (typeof ok !== 'undefined') {
    if (typeof ok !== 'function') {
      validationErrors.push('[RSAA].ok property must be a function');
    }
  }

  return validationErrors;
}
147825
function (done) {
      // the token is random
      if (token.indexOf('.') === -1) {
        AccessToken.get(token, function (err, instance) {
          if (err) {
            return done(err)
          }

          if (!instance) {
            return done(new UnauthorizedError({
              realm: 'user',
              error: 'invalid_request',
              error_description: 'Unknown access token',
              statusCode: 401
            }))
          }

          done(null, {
            jti: instance.at,
            iss: instance.iss,
            sub: instance.uid,
            aud: instance.cid,
            iat: instance.created,
            exp: instance.created + instance.ei,
            scope: instance.scope
          })
        })

      // the token is not random
      } else {
        done()
      }
    }
721031
function checkAccess({ accessToken, id, model, method, options, ctx }) {

     return new Promise((resolve, reject) => {
         // ignore checking if does not enable auth
         if (model.app.isAuthEnabled) {
             if (!model.app.models.ACL) {
                 console.log('ACL has not been setup, skipping access check.')
                 resolve(true);
             } else {
                 model.checkAccess(accessToken, id, method, ctx,
                     ((err, allowed) => {
                         if (err)
                             reject(err);
                         else if (allowed)
                             resolve(allowed);
                         else
                             reject(`ACCESS_DENIED`);
                     }));
             }
         } else {
             resolve(true);
         }
     })

 }
382369
def is_token_valid(self, token):
        

        try:
            _tinfo = self.handler.info(token)
        except KeyError:
            return False

        if is_expired(int(_tinfo['exp'])) or _tinfo['black_listed']:
            return False

        # Dependent on what state the session is in.
        session_info = self[_tinfo['sid']]

        if session_info["oauth_state"] == "authz":
            if _tinfo['handler'] != self.handler['code']:
                return False
        elif session_info["oauth_state"] == "token":
            if _tinfo['handler'] != self.handler['access_token']:
                return False

        return True
212988
def is_active(cache, token):
    
    profile = cache.get(token)
    if not profile:
        raise exceptions.NotAuthenticatedException(
            'The token is good, but you are not logged in. Please '
            'try logging in again.')
    return profile
577930
def validate_locked(self, authc_token, failed_attempts):
        
        if self.locking_limit and len(failed_attempts) > self.locking_limit:
            msg = ('Authentication attempts breached threshold.  Account'
                   ' is now locked for: ' + str(authc_token.identifier))
            self.locking_realm.lock_account(authc_token.identifier)
            self.notify_event(authc_token.identifier, 'AUTHENTICATION.ACCOUNT_LOCKED')
            raise LockedAccountException(msg)
1043046
public function validateAccessToken($accessToken = null)
	{
		$this->result = $this->http->get($this->getUrl('sns/auth', array(
			'access_token'	=>	null === $accessToken ? $this->accessToken : $accessToken,
			'openid'		=>	$this->openid,
		)))->json(true);
		return isset($this->result['errcode']) && 0 == $this->result['errcode'];
	}
558087
def SecurityCheck(self, func, request, *args, **kwargs):
    """"""
    request.user = u""

    authorized = False
    try:
      auth_type, authorization = request.headers.get("Authorization",
                                                     " ").split(" ", 1)

      if auth_type == "Basic":
        authorization_string = authorization.decode("base64").decode("utf-8")
        user, password = authorization_string.split(":", 1)

        if data_store.AFF4Enabled():

          token = access_control.ACLToken(username=user)

          fd = aff4.FACTORY.Open(
              "aff4:/users/%s" % user,
              aff4_type=aff4_users.GRRUser,
              token=token)
          crypted_password = fd.Get(fd.Schema.PASSWORD)
          if crypted_password and crypted_password.CheckPassword(password):
            authorized = True

            # The password is ok - update the user
            request.user = user

        else:

          try:
            user_obj = data_store.REL_DB.ReadGRRUser(user)
            if user_obj.password.CheckPassword(password):
              authorized = True

              # The password is ok - update the user
              request.user = user

          except db.UnknownGRRUserError:
            pass

    except access_control.UnauthorizedAccess as e:
      logging.warning("UnauthorizedAccess: %s for %s", e, request)
    except (IndexError, KeyError, IOError):
      pass

    if not authorized:
      result = werkzeug_wrappers.Response("Unauthorized", status=401)
      result.headers["WWW-Authenticate"] = "Basic realm='Secure Area'"
      return result

    # Modify this to implement additional checking (e.g. enforce SSL).
    return func(request, *args, **kwargs)
93192
public Authentication verifyAccessToken(String accessToken) throws InvalidTokenException, TokenExpiredException{
        CacheProvider cp = cp();

        Authentication authc = cp.get(accessToken);
        if(null != authc) {
            if(!authc.isExpired()) {
                return authc;
            }else{
                cp.remove(accessToken);
            }
        }

        boolean jwt = checkJwtToken(accessToken);
        if(jwt) {
            authc = tp().verifyJwtAccessToken(accessToken);
        }else{
            authc = tp().verifyBearerAccessToken(accessToken);
        }

        cp.put(accessToken, authc, authc.getExpires());

        return authc;
    }
1270208
@Override
    public OAuth2AccessToken readAccessToken(String accessToken) {
        TokenValidation tokenValidation =
                tokenValidationService.validateToken(accessToken, true).checkJti();

        Map<String, Object> claims = tokenValidation.getClaims();
        accessToken = tokenValidation.getJwt().getEncoded();

        // Expiry is verified by check_token
        CompositeToken token = new CompositeToken(accessToken);
        token.setTokenType(OAuth2AccessToken.BEARER_TYPE);
        token.setExpiration(new Date(Long.valueOf(claims.get(EXP).toString()) * 1000L));

        @SuppressWarnings("unchecked")
        ArrayList<String> scopes = (ArrayList<String>) claims.get(SCOPE);
        if (null != scopes && scopes.size() > 0) {
            token.setScope(new HashSet<>(scopes));
        }
        String clientId = (String)claims.get(CID);
        String userId = (String)claims.get(USER_ID);
        BaseClientDetails client = (BaseClientDetails) clientDetailsService.loadClientByClientId(clientId, IdentityZoneHolder.get().getId());
        // Only check user access tokens
        if (null != userId) {
            @SuppressWarnings("unchecked")
            ArrayList<String> tokenScopes = (ArrayList<String>) claims.get(SCOPE);
            approvalService.ensureRequiredApprovals(userId, tokenScopes, (String) claims.get(GRANT_TYPE), client);
        }

        return token;
    }
758864
private function checkAccess()
    {
        $tokenStorage = $this->get('security.token_storage');
        $configHandler = $this->get('claroline.config.platform_config_handler');
        $isSelfRegistrationAllowed = $configHandler->getParameter('allow_self_registration');

        if (!$tokenStorage->getToken()->getUser() instanceof User && $isSelfRegistrationAllowed) {
            return;
        }

        throw new AccessDeniedHttpException();
    }