-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathserver.py
More file actions
70 lines (56 loc) · 1.67 KB
/
server.py
File metadata and controls
70 lines (56 loc) · 1.67 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import json
import os
from blacksheep.server.application import Application
from blacksheep.server.authentication.jwt import JWTBearerAuthentication
from blacksheep.server.responses import html
from dotenv import load_dotenv
from guardpost.authentication import Identity
from guardpost.authorization import Policy
from guardpost.common import AuthenticatedRequirement
# read .env file into environment variables
load_dotenv()
app = Application()
aad_authority = os.environ["API_ISSUER"]
api_audience = os.environ["API_AUDIENCE"]
# configure the application to support authentication using JWT access tokens obtained
# from "Authorization: Bearer {...}" request headers;
# access tokens are validated using OpenID Connect configuration from the configured
# authority
app.use_authentication().add(
JWTBearerAuthentication(
authority=aad_authority,
valid_audiences=[api_audience],
)
)
# configure authorization with a default policy that requires an authenticated user for
# all endpoints, except when request handlers are explicitly decorated by
# @allow_anonymous
app.use_authorization().with_default_policy(
Policy("authenticated", AuthenticatedRequirement())
)
get = app.router.get
@get("/")
def home(user: Identity):
assert user.is_authenticated()
return html(
f"""
<!DOCTYPE html>
<html>
<head>
<style>
pre {{
border: 1px dotted darkred;
padding: 1rem;
}}
</style>
</head>
<body>
<h1>Welcome! These are your claims:</h1>
<pre>{json.dumps(user.claims, ensure_ascii=False, indent=4)}</pre>
</body>
</html>
"""
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=5000, log_level="debug")