Ensure the Authorization Header has a valid Access Token.
483210
def _headers(self):
        """"""
        if not self.access_token or not self.access_token_expires:
            self._basic_login()

        elif datetime.now() > self.access_token_expires - timedelta(seconds=30):
            self._basic_login()

        return {'Accept': HEADER_ACCEPT,
                'Authorization': 'bearer ' + self.access_token}
42289
public int verify(Request request, Response response) {
		String authValue = request.getHeaders().getValues("Authorization");
		log.debug("Auth header value is: "+ authValue);
		if (authValue == null) {
			return Verifier.RESULT_MISSING;
		}
		String[] tokenValues = authValue.split(" ");
		if (tokenValues.length < 2) {
			return Verifier.RESULT_MISSING;
		}

		if (!"Bearer".equals(tokenValues[0])) {
			return Verifier.RESULT_INVALID;
		}
		String token = tokenValues[1];

		log.debug("Token: "+ token);
		return checkToken(token);
	}
913748
public boolean isAuthorizationRequired(int statusCode, Map<String, List<String>> headers) {

        if (headers.containsKey(WWW_AUTHENTICATE_HEADER_NAME)){
            String authHeader = headers.get(WWW_AUTHENTICATE_HEADER_NAME).get(0);
            return AuthorizationHeaderHelper.isAuthorizationRequired(statusCode, authHeader);
        } else {
            return false;
        }
    }
711477
def _authenticate(self):
        """"""
        self.cleanup_headers()
        url = LOGIN_ENDPOINT
        data = self.query(
            url,
            method='POST',
            extra_params={
                'email': self.__username,
                'password': self.__password
            })

        if isinstance(data, dict) and data.get('success'):
            data = data.get('data')
            self.authenticated = data.get('authenticated')
            self.country_code = data.get('countryCode')
            self.date_created = data.get('dateCreated')
            self.__token = data.get('token')
            self.userid = data.get('userId')

            # update header with the generated token
            self.__headers['Authorization'] = self.__token
1013649
def access_token(self, value, request):
        

        if self.validate(value, request) is not None:
            return None
        
        access_token = AccessToken.objects.for_token(value)
        
        return access_token
203254
def check_authorization(self, access_token):
        
        p = self._session.params
        auth = (p.get('client_id'), p.get('client_secret'))
        if access_token and auth:
            url = self._build_url('applications', str(auth[0]), 'tokens',
                                  str(access_token))
            resp = self._get(url, auth=auth, params={
                'client_id': None, 'client_secret': None
            })
            return self._boolean(resp, 200, 404)
        return False
705710
def is_authorized(hijack, hijacked):
    '''
    
    '''
    authorization_check = import_string(hijack_settings.HIJACK_AUTHORIZATION_CHECK)
    return authorization_check(hijack, hijacked)
546313
def get_authorization_header(request):
    
    auth = request.META.get('HTTP_AUTHORIZATION', b'')

    if isinstance(auth, type('')):
        # Work around django test client oddness
        auth = auth.encode('iso-8859-1')

    return auth
740859
def attempt_reauthorization(blink):
    """"""
    _LOGGER.info("Auth token expired, attempting reauthorization.")
    headers = blink.get_auth_token(is_retry=True)
    return headers
1025607
public function validateAccessToken($httpHeadersOnly = false, $accessToken = null)
    {
        return $this->checker->isValidRequest($httpHeadersOnly, $accessToken);
    }
1253446
def authenticate(self):
        
        if request.headers.get('Authorization') or request.args.get('access_token'):
            realm = 'Bearer realm="%s", error="invalid_token"' % __package__
        else:
            realm = 'Bearer realm="%s"' % __package__
        resp = Response(None, 401, {'WWW-Authenticate': realm})
        abort(401, description='Please provide proper credentials', response=resp)
92829
def validate_token_parameters(params):
    """"""
    if 'error' in params:
        raise_from_error(params.get('error'), params)

    if not 'access_token' in params:
        raise MissingTokenError(description="Missing access token parameter.")

    if not 'token_type' in params:
        if os.environ.get('OAUTHLIB_STRICT_TOKEN_TYPE'):
            raise MissingTokenTypeError()

    # If the issued access token scope is different from the one requested by
    # the client, the authorization server MUST include the "scope" response
    # parameter to inform the client of the actual scope granted.
    # https://tools.ietf.org/html/rfc6749#section-3.3
    if params.scope_changed:
        message = 'Scope has changed from "{old}" to "{new}".'.format(
            old=params.old_scope, new=params.scope,
        )
        scope_changed.send(message=message, old=params.old_scopes, new=params.scopes)
        if not os.environ.get('OAUTHLIB_RELAX_TOKEN_SCOPE', None):
            w = Warning(message)
            w.token = params
            w.old_scope = params.old_scopes
            w.new_scope = params.scopes
            raise w
1201830
def verify_token(token, issuer:, audience:, client_id:)
      header, payload = token.split('.').first(2).map{|encoded| JSON.parse(Base64.decode64(encoded))}

      # validate claims
      raise InvalidToken.new('Invalid issuer')    if payload['iss'] != issuer
      raise InvalidToken.new('Invalid audience')  if payload['aud'] != audience
      raise InvalidToken.new('Invalid client')    if !Array(client_id).include?(payload['cid'])
      raise InvalidToken.new('Token is expired')  if payload['exp'].to_i <= Time.now.to_i

      # validate signature
      jwk = JSON::JWK.new(get_jwk(header, payload))
      JSON::JWT.decode(token, jwk.to_key)
    end
800670
def _validate_token(self, token, scopes_required=None):
        """"""
        if scopes_required is None:
            scopes_required = []
        scopes_required = set(scopes_required)

        token_info = None
        valid_token = False
        has_required_scopes = False
        if token:
            try:
                token_info = self._get_token_info(token)
            except Exception as ex:
                token_info = {'active': False}
                logger.error('ERROR: Unable to get token info')
                logger.error(str(ex))

            valid_token = token_info.get('active', False)

            if 'aud' in token_info and \
                    current_app.config['OIDC_RESOURCE_CHECK_AUD']:
                valid_audience = False
                aud = token_info['aud']
                clid = self.client_secrets['client_id']
                if isinstance(aud, list):
                    valid_audience = clid in aud
                else:
                    valid_audience = clid == aud

                if not valid_audience:
                    logger.error('Refused token because of invalid '
                                 'audience')
                    valid_token = False

            if valid_token:
                token_scopes = token_info.get('scope', '').split(' ')
            else:
                token_scopes = []
            has_required_scopes = scopes_required.issubset(
                set(token_scopes))

            if not has_required_scopes:
                logger.debug('Token missed required scopes')

        if (valid_token and has_required_scopes):
            g.oidc_token_info = token_info
            return True

        if not valid_token:
            return 'Token required but invalid'
        elif not has_required_scopes:
            return 'Token does not have required scopes'
        else:
            return 'Something went wrong checking your token'
66410
def authenticate(self, request):
        
        access_token = self.get_access_token(request)

        if not access_token:
            return None

        try:
            user = self.backend.get_or_create_user(access_token, None, None)
        except HTTPError as exc:
            resp = exc.response

            # if the oidc provider returns 401, it means the token is invalid.
            # in that case, we want to return the upstream error message (which
            # we can get from the www-authentication header) in the response.
            if resp.status_code == 401 and 'www-authenticate' in resp.headers:
                data = parse_www_authenticate_header(resp.headers['www-authenticate'])
                raise exceptions.AuthenticationFailed(data['error_description'])

            # for all other http errors, just re-raise the exception.
            raise
        except SuspiciousOperation as exc:
            LOGGER.info('Login failed: %s', exc)
            raise exceptions.AuthenticationFailed('Login failed')

        if not user:
            msg = 'Login failed: No user found for the given access token.'
            raise exceptions.AuthenticationFailed(msg)

        return user, access_token
117124
function isAuthenticated() {
  return compose()
    // Validate jwt
    .use(function (req, res, next) {
      // allow access_token to be passed through query parameter as well
      if (req.query && req.query.hasOwnProperty('access_token')) {
        req.headers.authorization = 'Bearer ' + req.query.access_token;
      }

      validateJwt(req, res, next);
    })

    .use(function (req, res, next) { // Attach userInfo to request
      // return if this request has already been authorized
      if (req.hasOwnProperty('userInfo')) {
        return next();
      }

      // load user model on demand
      var User = require('../../api/user/user.model').model;

      // read the user id from the token information provided in req.user
      User.findOne({_id: req.user._id, active: true}, function (err, user) {
        if (err) {
          return next(err);
        }

        if (!user) {
          res.unauthorized();
          return next();
        }

        // set the requests userInfo object as the authenticated user
        req.userInfo = user;
        next();
      });
    });
}
287153
def SecurityCheck(self, func, request, *args, **kwargs):
    """"""

    try:
      auth_header = request.headers.get("Authorization", "")
      if not auth_header.startswith(self.BEARER_PREFIX):
        raise ValueError("JWT token is missing.")

      token = auth_header[len(self.BEARER_PREFIX):]

      auth_domain = config.CONFIG["AdminUI.firebase_auth_domain"]
      project_id = auth_domain.split(".")[0]

      idinfo = id_token.verify_firebase_token(
          token, request, audience=project_id)

      if idinfo["iss"] != self.SECURE_TOKEN_PREFIX + project_id:
        raise ValueError("Wrong issuer.")

      request.user = idinfo["email"]
    except ValueError as e:
      # For a homepage, just do a pass-through, otherwise JS code responsible
      # for the Firebase auth won't ever get executed. This approach is safe,
      # because wsgiapp.HttpRequest object will raise on any attempt to
      # access uninitialized HttpRequest.user attribute.
      if request.path != "/":
        return self.AuthError("JWT token validation failed: %s" % e)

    return func(request, *args, **kwargs)