Skip to content

Авторизация

Эти классы используются для добавления информации по авторизации к запросам, отправляемым клиентом.

Bases: BaseAuth, BaseModel

Authorization using OAuth2 + grant_type=password.

Resulting access is passed in Authorization: Bearer ${token} header. Tokens can be refreshed.

Parameters

username : str User name

str

User password

Examples

from horizon.client.auth import LoginPassword auth = LoginPassword(login="me", password="12345")

Source code in horizon/client/auth/login_password.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class LoginPassword(BaseAuth, BaseModel):
    """Authorization using OAuth2 + ``grant_type=password``.

    Resulting access is passed in ``Authorization: Bearer ${token}`` header.
    Tokens can be refreshed.

    Parameters
    ----------
    username : str
        User name

    password : str
        User password

    Examples
    --------

    >>> from horizon.client.auth import LoginPassword
    >>> auth = LoginPassword(login="me", password="12345")
    """

    login: str
    password: SecretStr

    type: Literal["login_password"] = "login_password"

    def patch_session(self, session):
        return session

    def fetch_token_kwargs(self, base_url: AnyHttpUrl) -> dict[str, str]:
        # default path for token
        parsed_url = urlparse(str(base_url))
        token_url = parsed_url._replace(path=parsed_url.path + "/v1/auth/token")
        url = token_url.geturl()

        return {
            "url": str(url),
            "username": self.login,
            "password": self.password.get_secret_value(),
        }

login instance-attribute

password instance-attribute

Bases: BaseAuth, BaseModel

Authorization using access token.

Token is passed in Authorization: Bearer ${token} header, and does not support refreshing.

Parameters

token: str Access token

Examples

from horizon.client.auth import AccessToken auth = AccessToken(token="my.access.token")

Source code in horizon/client/auth/access_token.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class AccessToken(BaseAuth, BaseModel):
    """Authorization using access token.

    Token is passed in ``Authorization: Bearer ${token}`` header,
    and does not support refreshing.

    Parameters
    ----------
    token: str
        Access token

    Examples
    --------

    >>> from horizon.client.auth import AccessToken
    >>> auth = AccessToken(token="my.access.token")
    """

    token: str

    type: Literal["access_token"] = "access_token"

    def patch_session(self, session: Session) -> Session:
        if session.token:
            return session

        # AuthlibToken expiration is optional, and JWT token is not parsed.
        # We have to extract expiration time manually.
        claims = self._parse_token(self.token)
        session.token = AuthlibToken.from_dict(
            {
                "access_token": self.token,
                "token_type": "Bearer",
                "expires_at": claims["exp"],
            },
        )
        return session

    def fetch_token_kwargs(self, base_url: AnyHttpUrl) -> dict[str, str]:
        return {}

    @classmethod
    def _parse_token(cls, token) -> JWTClaims:
        try:
            # As client don't have private key used for signing JWT, this call will always raise this exception
            # https://github.com/lepture/authlib/issues/600
            jwt.decode(token, key="")
        except BadSignatureError as e:
            token_decoded = e.result.payload
            claims = JWTClaims(
                header=token_decoded,
                payload=token_decoded,
            )

        if "exp" not in claims:
            msg = "Missing expiration time in token"
            raise ExpiredTokenError(msg)

        claims.validate()
        return claims

    @validator("token")
    def _validate_access_token(cls, value):  # noqa: N805
        # AuthlibToken doesn't perform any validation, so we have to
        cls._parse_token(value)
        return value

token instance-attribute