Esempio n. 1
0
def _transform_raw_key(raw):
    if isinstance(raw, str) and \
            raw.startswith('{') and raw.endswith('}'):
        return json_loads(raw)
    elif isinstance(raw, (tuple, list)):
        return {'keys': raw}
    return raw
Esempio n. 2
0
 def client_metadata(self):
     if 'client_metadata' in self.__dict__:
         return self.__dict__['client_metadata']
     if self._client_metadata:
         data = json_loads(self._client_metadata)
         self.__dict__['client_metadata'] = data
         return data
     return {}
Esempio n. 3
0
def decode_payload(bytes_payload):
    try:
        payload = json_loads(to_unicode(bytes_payload))
    except ValueError:
        raise DecodeError('Invalid payload value')
    if not isinstance(payload, dict):
        raise DecodeError('Invalid payload type')
    return payload
Esempio n. 4
0
def _load_jwk(key, header):
    if not key and 'jwk' in header:
        key = header['jwk']
    if isinstance(key, (tuple, list, dict)):
        return jwk.loads(key, header.get('kid'))
    if isinstance(key, text_types) and \
            key.startswith('{') and key.endswith('}'):
        return jwk.loads(json_loads(key), header.get('kid'))
    return key
Esempio n. 5
0
	def get_client(self):
		csp = CloudServiceProvider.query.get(self.csp_id)
		client = oauth.create_client(csp.name + "_" + self.scope)
		if not client:
			client = register_oauth_client(self, csp.name)

		db_token = Oauth2Token.query.filter_by(client_id=self.id).first()
		if db_token:
			client.token = json_loads(db_token.token)
		return client
Esempio n. 6
0
def prepare_raw_key(raw):
    if isinstance(raw, KeySet):
        return raw

    if isinstance(raw, str) and \
            raw.startswith('{') and raw.endswith('}'):
        raw = json_loads(raw)
    elif isinstance(raw, (tuple, list)):
        raw = {'keys': raw}
    return raw
Esempio n. 7
0
def extract_header(header_segment, error_cls):
    header_data = extract_segment(header_segment, error_cls, 'header')

    try:
        header = json_loads(header_data.decode('utf-8'))
    except ValueError as e:
        raise error_cls('Invalid header string: {}'.format(e))

    if not isinstance(header, dict):
        raise error_cls('Header must be a json object')
    return header
Esempio n. 8
0
def _ensure_dict(s):
    if not isinstance(s, dict):
        try:
            s = json_loads(to_unicode(s))
        except (ValueError, TypeError):
            raise DecodeError('Invalid JWS')

    if not isinstance(s, dict):
        raise DecodeError('Invalid JWS')

    return s
Esempio n. 9
0
def ensure_dict(s, structure_name):
    if not isinstance(s, dict):
        try:
            s = json_loads(to_unicode(s))
        except (ValueError, TypeError):
            raise DecodeError('Invalid {}'.format(structure_name))

    if not isinstance(s, dict):
        raise DecodeError('Invalid {}'.format(structure_name))

    return s
Esempio n. 10
0
def get_oauth2_client(csp_name, user):
    csp = CloudServiceProvider.query.filter_by(name=csp_name).first()
    user = current_user()
    if not user:
        return render_template('login.html', message="Login failed")
    scope = user.get_plan().get_scope(csp.name)
    client = OAuth2Client.query.filter_by(csp_id=csp.id, scope=scope).first()
    db_token = Oauth2Token.query.filter_by(user_id=user.id,
                                           client_id=client.id).first()
    token = json_loads(db_token.token)
    client.token = token
    return client
Esempio n. 11
0
    def import_key_set(cls, raw):
        if isinstance(raw, text_types) and \
                raw.startswith('{') and raw.endswith('}'):
            raw = json_loads(raw)
            keys = raw.get('keys')
        elif isinstance(raw, dict) and 'keys' in raw:
            keys = raw.get('keys')
        elif isinstance(raw, (tuple, list)):
            keys = raw
        else:
            return None

        return KeySet([cls.import_key(k) for k in keys])
Esempio n. 12
0
def create_oauth_request(request, request_cls, use_json=False):
    if isinstance(request, request_cls):
        return request

    if request.method == 'POST':
        if use_json:
            body = json_loads(request.body)
        else:
            body = request.POST.dict()
    else:
        body = None

    url = request.get_raw_uri()
    return request_cls(request.method, url, body, request.headers)
Esempio n. 13
0
    def import_key_set(cls, raw):
        """Import KeySet from string, dict or a list of keys.

        :return: KeySet instance
        """
        if isinstance(raw, str) and \
                raw.startswith('{') and raw.endswith('}'):
            raw = json_loads(raw)
            keys = raw.get('keys')
        elif isinstance(raw, dict) and 'keys' in raw:
            keys = raw.get('keys')
        elif isinstance(raw, (tuple, list)):
            keys = raw
        else:
            return None

        return KeySet([cls.import_key(k) for k in keys])
Esempio n. 14
0
def prepare_raw_key(raw, header):
    if isinstance(raw, KeySet):
        return raw.find_by_kid(header.get('kid'))

    if isinstance(raw, str) and \
            raw.startswith('{') and raw.endswith('}'):
        raw = json_loads(raw)
    elif isinstance(raw, (tuple, list)):
        raw = {'keys': raw}

    if isinstance(raw, dict) and 'keys' in raw:
        keys = raw['keys']
        kid = header.get('kid')
        for k in keys:
            if k.get('kid') == kid:
                return k
        raise ValueError('Invalid JSON Web Key Set')
    return raw
Esempio n. 15
0
    def parse_response_token(self, status_code, text):
        if status_code >= 400:
            message = ("Token request failed with code {}, "
                       "response was '{}'.").format(status_code, text)
            self.handle_error('fetch_token_denied', message)

        try:
            text = text.strip()
            if text.startswith('{'):
                token = json_loads(text)
            else:
                token = dict(url_decode(text))
        except (TypeError, ValueError) as e:
            error = ("Unable to decode token from token response. "
                     "This is commonly caused by an unsuccessful request where"
                     " a non urlencoded error message is returned. "
                     "The decoding error was {}").format(e)
            raise ValueError(error)
        return token
Esempio n. 16
0
 def client_metadata(self):
     if self._client_metadata:
         return json_loads(self._client_metadata)
     return {}
Esempio n. 17
0
def test_keys():
    """Try to store/get/remove keys"""
    # JWS
    jws = JsonWebSignature(algorithms=["RS256"])
    code_payload = {
        "user_id": "user",
        "scope": "scope",
        "client_id": "client",
        "redirect_uri": "redirect_uri",
        "code_challenge": "code_challenge",
    }

    # Token metadata
    header = {"alg": "RS256"}
    payload = {
        "sub": "user",
        "iss": "issuer",
        "scope": "scope",
        "setup": "setup",
        "group": "my_group"
    }

    # Remove all keys
    result = db.removeKeys()
    assert result["OK"], result["Message"]

    # Check active keys
    result = db.getActiveKeys()
    assert result["OK"], result["Message"]
    assert result["Value"] == []

    # Create new one
    result = db.getPrivateKey()
    assert result["OK"], result["Message"]

    private_key = result["Value"]
    assert isinstance(private_key, RSAKey)

    # Sign token
    header["kid"] = private_key.thumbprint()

    # Find key by KID
    result = db.getPrivateKey(header["kid"])
    assert result["OK"], result["Message"]
    # as_dict has no arguments for authlib < 1.0.0
    # for authlib >= 1.0.0:
    assert result["Value"].as_dict(True) == private_key.as_dict(True)

    # Sign token
    token = jwt.encode(header, payload, private_key)
    # Sign auth code
    code = jws.serialize_compact(header, json_b64encode(code_payload),
                                 private_key)

    # Get public key set
    result = db.getKeySet()
    keyset = result["Value"]
    assert result["OK"], result["Message"]
    # as_dict has no arguments for authlib < 1.0.0
    # for authlib >= 1.0.0:
    assert bool([
        key for key in keyset.as_dict(True)["keys"]
        if key["kid"] == header["kid"]
    ])

    # Read token
    _payload = jwt.decode(token, JsonWebKey.import_key_set(keyset.as_dict()))
    assert _payload == payload
    # Read auth code
    data = jws.deserialize_compact(code, keyset.keys[0])
    _code_payload = json_loads(urlsafe_b64decode(data["payload"]))
    assert _code_payload == code_payload
Esempio n. 18
0
 def jwt_decode(s: str) -> dict:
     from authlib.common.encoding import urlsafe_b64decode, json_loads
     return json_loads(urlsafe_b64decode(s.encode('ascii')))
Esempio n. 19
0
	def get_scope(self, csp):
		return json_loads(self.oauth2_scopes)[csp]
Esempio n. 20
0
	def add_scope(self, csp, scope):
		scopes = json_loads(self.oauth2_scopes)
		scopes[csp] = scope
		self.oauth2_scopes = json_dumps(scopes)