-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathexample-02.py
More file actions
50 lines (34 loc) · 1.38 KB
/
example-02.py
File metadata and controls
50 lines (34 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
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
"""
This example illustrates a basic use of the authentication strategy, using more than
one way to obtain the user's identity.
"""
import asyncio
from guardpost import AuthenticationHandler, AuthenticationStrategy, Identity
class MyAppContext:
"""
This represents a context for an application - it can be anything depending on
use cases and the user's notion of application context.
"""
def __init__(self) -> None:
self.identity: Identity | None = None
class CustomAuthenticationHandler(AuthenticationHandler):
def authenticate(self, context: MyAppContext) -> "Identity | None":
"""
In this example, we simulate a situation in which an identity cannot be
determined for a context. Another Authenticationhandler
"""
return None
class AlternativeAuthenticationHandler(AuthenticationHandler):
def authenticate(self, context: MyAppContext) -> "Identity | None":
return Identity({"sub": "002"})
async def main():
some_context = MyAppContext()
authentication = AuthenticationStrategy(
CustomAuthenticationHandler(), AlternativeAuthenticationHandler()
)
identity = await authentication.authenticate(some_context)
assert identity is not None
assert identity.sub == "002"
# the identity is set on the given context
assert some_context.identity is identity
asyncio.run(main())