Unpacks a jwt token from a request header
979684
def _unpack_header(self, headers):
        
        jwt_header = headers.get(self.header_name)
        MissingTokenHeader.require_condition(
            jwt_header is not None,
            "JWT token not found in headers under '{}'",
            self.header_name,
        )

        match = re.match(self.header_type + r'\s*([\w\.-]+)', jwt_header)
        InvalidTokenHeader.require_condition(
            match is not None,
            "JWT header structure is invalid",
        )
        token = match.group(1)
        return token
866229
def parse_auth_token_from_request(self, auth_header):
        
        if not auth_header:
            raise falcon.HTTPUnauthorized(
                description='Missing Authorization Header')

        try:
            auth_header_prefix, _ = auth_header.split(' ', 1)
        except ValueError:
            raise falcon.HTTPUnauthorized(
                description='Invalid Authorization Header: Missing Scheme or Parameters')

        if auth_header_prefix.lower() != self.auth_header_prefix.lower():
            raise falcon.HTTPUnauthorized(
                description='Invalid Authorization Header: '
                            'Must start with {0}'.format(self.auth_header_prefix))

        return auth_header
1032534
def payload(self):
        
        _msg = as_unicode(self.part[1])

        # If not JSON web token assume JSON
        if "cty" in self.headers and self.headers["cty"].lower() != "jwt":
            pass
        else:
            try:
                _msg = json.loads(_msg)
            except ValueError:
                pass

        return _msg
197616
def get_payload_data(self, token, key):
        """"""
        if self.get_settings('OIDC_ALLOW_UNSECURED_JWT', False):
            header, payload_data, signature = token.split(b'.')
            header = json.loads(smart_text(b64decode(header)))

            # If config allows unsecured JWTs check the header and return the decoded payload
            if 'alg' in header and header['alg'] == 'none':
                return b64decode(payload_data)

        # By default fallback to verify JWT signatures
        return self._verify_jws(token, key)
569581
function validateAskPermission (token) {
  const header = jwt.decode(token)

  return validateToken(token) && header[ASK_CLAIM_KEY]
}
640378
def cleanup_headers(self):
        """"""
        headers = {'Content-Type': 'application/json'}
        headers['Authorization'] = self.__token
        self.__headers = headers
        self.__params = {}
227452
def _request_loader(self, request: Request) -> Union[User, AnonymousUser]:
        
        header_key = self.token_authentication_header
        args_key = self.token_authentication_key
        token = request.args.get(args_key, request.headers.get(header_key, None))
        if request.is_json:
            data = request.get_json(silent=True) or {}
            token = data.get(args_key, token)

        try:
            data = self.remember_token_serializer.loads(token, max_age=self.token_max_age)
            user = self.user_manager.get(data[0])
            if user and self.security_utils_service.verify_hash(data[1], user.password):
                return user
        except:
            pass

        return self.login_manager.anonymous_user()
1066720
def get_JWT(url, address=None):
    
    jwt_txt = None
    jwt = None

    log.debug("Try {}".format(url))

    # special case: handle file://
    urlinfo = urllib2.urlparse.urlparse(url)
    if urlinfo.scheme == 'file':
        # points to a path on disk
        try:
            with open(urlinfo.path, 'r') as f:
                jwt_txt = f.read()

        except Exception as e:
            if BLOCKSTACK_TEST:
                log.exception(e)

            log.warning("Failed to read {}".format(url))
            return None

    else:
        # http(s) URL or similar
        try:
            resp = requests.get(url)
            assert resp.status_code == 200, 'Bad status code on {}: {}'.format(url, resp.status_code)
            jwt_txt = resp.text

        except Exception as e:
            if BLOCKSTACK_TEST:
                log.exception(e)

            log.warning("Unable to resolve {}".format(url))
            return None

    try:
        # one of two things are possible:
        # * this is a JWT string
        # * this is a serialized JSON string whose first item is a dict that has 'token' as key,
        # and that key is a JWT string.
        try:
            jwt_txt = json.loads(jwt_txt)[0]['token']
        except:
            pass

        jwt = jsontokens.decode_token(jwt_txt)
    except Exception as e:
        if BLOCKSTACK_TEST:
            log.exception(e)

        log.warning("Unable to decode token at {}".format(url))
        return None

    try:
        # must be well-formed
        assert isinstance(jwt, dict)
        assert 'payload' in jwt, jwt
        assert isinstance(jwt['payload'], dict)
        assert 'issuer' in jwt['payload'], jwt
        assert isinstance(jwt['payload']['issuer'], dict)
        assert 'publicKey' in jwt['payload']['issuer'], jwt
        assert virtualchain.ecdsalib.ecdsa_public_key(str(jwt['payload']['issuer']['publicKey']))

    except AssertionError as ae:
        if BLOCKSTACK_TEST or BLOCKSTACK_DEBUG:
            log.exception(ae)

        log.warning("JWT at {} is malformed".format(url))
        return None

    if address is not None:
        public_key = str(jwt['payload']['issuer']['publicKey'])
        addrs = [virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.decompress(public_key)).address()),
                 virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.compress(public_key)).address())]

        if virtualchain.address_reencode(address) not in addrs:
            # got a JWT, but it doesn't match the address
            log.warning("Found JWT at {}, but its public key has addresses {} and {} (expected {})".format(url, addrs[0], addrs[1], address))
            return None

        verifier = jsontokens.TokenVerifier()
        if not verifier.verify(jwt_txt, public_key):
            # got a JWT, and the address matches, but the signature does not
            log.warning("Found JWT at {}, but it was not signed by {} ({})".format(url, public_key, address))
            return None

    return jwt
561214
def unpack(cls, msg, client, server, request_id):
        
        flags, = _UNPACK_INT(msg[:4])
        namespace, pos = _get_c_string(msg, 4)
        num_to_return, = _UNPACK_INT(msg[pos:pos + 4])
        pos += 4
        cursor_id, = _UNPACK_LONG(msg[pos:pos + 8])
        return OpGetMore(namespace=namespace, flags=flags, _client=client,
                         num_to_return=num_to_return, cursor_id=cursor_id,
                         request_id=request_id, _server=server)
545965
def jwt_required(func):
    
    if inspect.isclass(func):
        apply_function_to_members(func, jwt_required)
        return func
    else:
        @functools.wraps(func)
        def deco(*a, **kw):
            if not "Authorization" in request.headers:
                abort(401, "Not Authorized")
            return func(*a, **kw)

        return deco
1321517
def unpack(cls, msg, client, server, request_id):
        
        payload_document = OrderedDict()
        flags, = _UNPACK_UINT(msg[:4])
        pos = 4
        if flags != 0 and flags != 2:
            raise ValueError('OP_MSG flag must be 0 or 2 not %r' % (flags,))

        while pos < len(msg):
            payload_type, = _UNPACK_BYTE(msg[pos:pos + 1])
            pos += 1
            payload_size, = _UNPACK_INT(msg[pos:pos + 4])
            if payload_type == 0:
                doc = bson.decode_all(msg[pos:pos + payload_size],
                                      CODEC_OPTIONS)[0]
                payload_document.update(doc)
                pos += payload_size
            elif payload_type == 1:
                section_size, = _UNPACK_INT(msg[pos:pos + 4])
                pos += 4
                identifier, pos = _get_c_string(msg, pos)
                # Section starts w/ 4-byte size prefix, identifier ends w/ nil.
                documents_len = section_size - len(identifier) - 1 - 4
                documents = bson.decode_all(msg[pos:pos + documents_len],
                                            CODEC_OPTIONS)
                payload_document[identifier] = documents
                pos += documents_len

        database = payload_document['$db']
        return OpMsg(payload_document, namespace=database, flags=flags,
                     _client=client, request_id=request_id,
                     _server=server)
1000792
public Result<Jwt> getJwt(ClientRequest clientRequest) {
        HeaderValues scope = clientRequest.getRequestHeaders().get(OauthHelper.SCOPE);
        if(scope != null) {
            String scopeStr = scope.getFirst();
            Set<String> scopeSet = new HashSet<>();
            scopeSet.addAll(Arrays.asList(scopeStr.split(" ")));
            return getJwt(new Jwt.Key(scopeSet));
        }
        HeaderValues serviceId = clientRequest.getRequestHeaders().get(OauthHelper.SERVICE_ID);
        if(serviceId != null) {
            return getJwt(new Jwt.Key(serviceId.getFirst()));
        }
        return getJwt(new Jwt.Key());
    }
274941
private AuthenticationResult handleJwtSSO(HttpServletRequest req, HttpServletResponse res) {
        String jwtCookieName = JwtSSOTokenHelper.getJwtCookieName();
        if (jwtCookieName == null) { // jwtsso feature not active
            return null;
        }

        String encodedjwtssotoken = ssoCookieHelper.getJwtSsoTokenFromCookies(req, jwtCookieName);

        if (encodedjwtssotoken == null) { //jwt sso cookie is missing, look at the auth header
            encodedjwtssotoken = getJwtBearerToken(req);
        }
        if (encodedjwtssotoken == null) {
            return null;
        } else {
            if (LoggedOutJwtSsoCookieCache.contains(encodedjwtssotoken)) {
                String LoggedOutMsg = "JWT_ALREADY_LOGGED_OUT";
                if (req.getAttribute(LoggedOutMsg) == null) {
                    Tr.audit(tc, LoggedOutMsg, new Object[] {});
                    req.setAttribute(LoggedOutMsg, "true");
                }

                return new AuthenticationResult(AuthResult.FAILURE, Tr.formatMessage(tc, LoggedOutMsg));
            }
            return authenticateWithJwt(req, res, encodedjwtssotoken);
        }
    }
276458
@Override
	public Map<String, String> convert(String token) {
		Map<String, String> headers;

		int headerEndIndex = token.indexOf('.');
		if (headerEndIndex == -1) {
			throw new InvalidTokenException("Invalid JWT. Missing JOSE Header.");
		}

		byte[] decodedHeader;

		try {
			decodedHeader = Codecs.b64UrlDecode(token.substring(0, headerEndIndex));
		} catch (IllegalArgumentException ex) {
			throw new InvalidTokenException("Invalid JWT. Malformed JOSE Header.", ex);
		}

		JsonParser parser = null;

		try {
			parser = this.factory.createParser(decodedHeader);
			headers = new HashMap<String, String>();
			if (parser.nextToken() == JsonToken.START_OBJECT) {
				while (parser.nextToken() == JsonToken.FIELD_NAME) {
					String headerName = parser.getCurrentName();
					parser.nextToken();
					String headerValue = parser.getValueAsString();
					headers.put(headerName, headerValue);
				}
			}

		} catch (IOException ex) {
			throw new InvalidTokenException("An I/O error occurred while reading the JWT: " + ex.getMessage(), ex);
		} finally {
			try {
				if (parser != null) parser.close();
			} catch (IOException ex) { }
		}

		return headers;
	}
439494
def read_request_headers(request)
      headers = {}
      request.env.keys.each do |key|
        if EXCLUDE_REQUEST_HEADER_PATTERNS.all? { |p| !key.starts_with? p }
          headers.merge!(cleanup_header(key) => request.env[key])
        end
      end
      headers
    end
63671
def _unpack_token_json(token):
    
    if not isinstance(token, dict):
        raise DecodeError("Not a dict")

    if not token.has_key('payload'):
        raise DecodeError("Missing 'payload' field")

    for k in ['header', 'signature']:
        if not token.has_key(k):
            raise DecodeError("Missing '{}' field".format(k))

        if not isinstance(token[k], list):
            raise DecodeError("Field '{}' is not a string".format(k))

    headers = []
    signatures = []
    signing_inputs = []
    payload = None

    try:
        headers = [base64url_decode(str(h)) for h in token['header']]
    except (TypeError, binascii.Error):
        raise DecodeError("Invalid header padding")

    try:
        payload_data = base64url_decode(str(token['payload']))
    except (TypeError, binascii.Error):
        raise DecodeError("Invalid payload padding")

    try:
        payload = json.loads(payload_data.decode('utf-8'))
    except ValueError as e:
        raise DecodeError('Invalid payload string: {}'.format(e))

    try:
        signatures = [base64url_decode(str(s)) for s in token['signature']]
    except (TypeError, binascii.Error):
        raise DecodeError("Invalid crypto padding")

    for header_b64 in token['header']:
        signing_inputs.append( b'{}.{}'.format(header_b64, token['payload']) )

    return (headers, payload, signatures, signing_inputs)
423263
def info(self, token):
        
        verifier = JWT(key_jar=self.key_jar, allowed_sign_algs=[self.alg])
        _payload = verifier.unpack(token)
        if is_expired(_payload['exp']):
            raise ToOld('Token has expired')
        return _payload['sid'], _payload['ttype']