-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathexample-01.py
More file actions
50 lines (32 loc) · 1.35 KB
/
example-01.py
File metadata and controls
50 lines (32 loc) · 1.35 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 a single
authentication handler.
"""
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":
"""
Obtains an identity for a context.
For example, this might read information from a user's folder, an HTTP Request
cookie or authorization header, or an external service. This method can be
either synchronous or asynchronous.
"""
return Identity({"sub": "example"})
# NOTE: a AuthenticationHandler.authenticate method can also be async!
async def main():
some_context = MyAppContext()
authentication = AuthenticationStrategy(CustomAuthenticationHandler())
identity = await authentication.authenticate(some_context)
assert identity is not None
assert identity.sub == "example"
# the identity is set on the given context
assert some_context.identity is identity
asyncio.run(main())