Beispiel #1
0
    def parse_body(self, body: Any = None) -> bytes:
        """
        Returns a bytes representation of the JSON Encodable body of the Response.

        :param body: JSON Encodable object representing the body of the response,
            defaults to None.
        :type body: Any, optional

        :return: Byte-string of the JSON representation of the Response Body.
        :rtype: bytes
        """

        return to_bytes(json_dumps(body))
Beispiel #2
0
    def parse_body(self, body: Any = None) -> bytes:
        """
        Parses the body of the response.

        If no body is provided, it returns an empty byte-string.

        :param body: Object representing the body of the response, defaults to None.
        :type body: Any, optional

        :return: Parsed body as a byte-string.
        :rtype: bytes
        """

        return to_bytes(body) or b""
Beispiel #3
0
    def export(self, public: bool = False) -> bytes:
        """
        Exports the key in Base64 format.

        :param public: Exports the public info, defaults to False.
        :type public: bool, optional

        :return: Base64 encoded key data.
        :rtype: bytes
        """

        if public:
            warnings.warn("Secret keys do not have public info.",
                          RuntimeWarning)

        return base64.b64encode(base64url_decode(to_bytes(self._secret)))
Beispiel #4
0
    def decode(
        cls,
        token: bytes | str,
        key: JsonWebKey,
        algorithm: str = None,
        validate: bool = True,
        options: dict[str, dict] = None,
    ) -> JsonWebToken:
        """
        Decodes a token checking if its signature matches its content.

        Despite being optional, it is recommended to provide an algorithm
        to prevent the "none attack" and the misuse of a public key
        as secret key.

        The algorithm specified at the header of the token **MUST** match
        the provided algorithm, if any.

        If the token has an Issued At (`iat`) parameter, it will verify the
        validity of the token against the provided `expiration` argument.

        :param token: Token to be verified.
        :type token: Union[bytes, str]

        :param key: Key used to validate the token's signature.
        :type key: JsonWebKey

        :param algorithm: Expected algorithm of the token, defaults to None.
        :type algorithm: str, optional

        :param validate: Defines if the decoding should validate the signature.
            Defaults to True.
        :type validate: bool, optional

        :param options: Optional validation options for the claims of the token.
        :type options: dict[str, dict]

        :return: Instance of a JsonWebToken.
        :rtype: JsonWebToken
        """

        jws = JsonWebSignature.deserialize(to_bytes(token), key, algorithm, validate)
        claims = JsonWebTokenClaims(
            json_loads(jws.payload), options if validate else None
        )

        return cls(claims, jws.header)
Beispiel #5
0
def S256_challenge(challenge: str, verifier: str):
    hashed_verifier = to_string(
        base64url_encode(hashlib.sha256(to_bytes(verifier, "ascii")).digest()))
    return challenge == hashed_verifier
Beispiel #6
0
def _parse_raw(path_or_secret: os.PathLike | bytes) -> bytes:
    try:
        with open(path_or_secret, "rb") as f:
            return f.read()
    except (FileNotFoundError, IsADirectoryError):
        return to_bytes(path_or_secret)
Beispiel #7
0
 def __init__(self, k: str, **ignore) -> None:
     self._secret = base64url_decode(to_bytes(k))
Beispiel #8
0
 def __init__(self, claims: JsonWebTokenClaims, header: dict):
     self.header = JsonWebSignatureHeader(header)
     self.claims = JsonWebTokenClaims(claims)
     self._jws = JsonWebSignature(to_bytes(json_dumps(self.claims)), self.header)
Beispiel #9
0
from psion.oauth2.models import Scope
from psion.oauth2.providers import StarletteProvider
from psion.oidc import AuthorizationCodeFlow
from psion.webtools import to_bytes

from example.adapter import Adapter
from example.settings import SECRET_KEY

provider = StarletteProvider(
    "http://localhost:8000",
    adapter=Adapter,
    grants=[AuthorizationCodeGrant, ClientCredentialsGrant, RefreshTokenGrant],
    scopes=[
        Scope("openid", "OpenID of the User."),
        Scope("profile", "Returns the profile of the user."),
        Scope("email", "Returns the email information of the user."),
        Scope("phone", "Returns the phone information of the user."),
        Scope("address", "Returns the address information of the user."),
    ],
    keyset=JsonWebKeySet([
        JsonWebKey.parse(to_bytes(SECRET_KEY),
                         "oct",
                         False,
                         format="der",
                         kid="key1")
    ]),
    error_url="/connect/error",
)

provider.add_hook(AuthorizationCodeGrant, AuthorizationCodeFlow)