Skip to content

Commit 24687a8

Browse files
committed
Implemented client and updated README
1 parent efdd681 commit 24687a8

File tree

55 files changed

+233
-242
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

55 files changed

+233
-242
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/.env_oauth
1+
client/.env_oauth
22
/infra/terraform.tfvars
33
/.idea/.gitignore
44
/infra/.terraform.lock.hcl

README.md

Lines changed: 100 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,54 @@ The file structure is as follows:
2828
![screenshot](images/terraform_tfvars.png)
2929

3030

31+
## Register server on Azure Entra ID
32+
33+
Before deploying our server we need to create an app registration that we have deployed our API to Azure Web Apps, we need to register it on Microsoft Entra ID.
34+
35+
### Create a new app registration
36+
37+
Navigate to the **App registrations** blade and click on **New registration** button in the top left tab
38+
39+
![screenshot](images/azuread_app_registrations.png)
40+
41+
Choose a fitting name. Here I have set the name to "Hvalfangst Server" as the registration will be utilized by the API we just deployed to Azure Web Apps. The client which is to interact with our server resource will **NOT** be deployed. It will merely run locally. The fact that
42+
both the newly deployed server and the not-to-be-deployed local client are both APIs may seem confusing, but this is just for demonstration purposes. We do not need to set up a redirect URI for our server as it merely validates token received in the authentication header and calls the underlying
43+
service if the associated token had the necessary scopes. We will set the redirect URL for our client in later sections, as it will have to execute a callback from browser to a specified endpoint.
44+
45+
46+
![screenshot](images/azure_entra_id_register_hvalfangst_server_api.png)
47+
48+
Once the app registration has been created, store the application and tenant id for later use. We will make use of these when setting up the CI/CD pipeline - which deploys the server API to Azure Web Apps.
49+
50+
![screenshot](images/hvalfangst_server_api_app_registration.png)
51+
52+
53+
### Create Scope
54+
55+
We will now proceed to create scopes. Scopes are in essence fully customizable access right labels, meaning that you may are free to pick any name. It is, however common to conform to the following pattern: **{RESOURCE}.{ACCESS_LEVEL}**.
56+
Say that you for sake of argument have implemented a CRUD API in the domain of wines. Since the domain is wine, the prefix would naturally be **Wines**. Access levels could be **READ**, **WRITE**, **UPDATE** and **DELETE**.
57+
For instance, the scope **Wines.Read** grants you access to **read** wines - which in the API translates to the right to perform any **HTTP GET** requests, which commonly would be actions such as listing all heroes or to get a specific hero.
58+
59+
Click on the **Add a scope** button under the **Expose an API** section, which is accessible from the **Expose an API** blade under **Manage**.
60+
61+
![screenshot](images/hvalfangst_server_api_expose_api.png)
62+
63+
Set the scope name to **Heroes.Read**. Clients which has this scope grants the ability to list and view heroes. Choose **Admins only** for consent.
64+
Choose something relevant to the scope name for the remainder of fields.
65+
66+
![screenshot](images/hvalfangst_server_api_add_scope.png)
67+
68+
Do the same for **Heroes.Write** and **Heroes.Delete**.
69+
70+
![screenshot](images/hvalfangst_server_api_all_scopes.png)
71+
72+
It goes without saying that the chosen scopes are just simple examples that does not necessarily conform to best practices when it comes to naming and even usages of scopes.
73+
Feel free to adapt the scopes in the app registration and code as you see fit. It is also important to mention, now that we venture into the more technical aspects, that
74+
the newly created scopes are absolutely junk in and of itself. You **must** reference the scopes exactly as defined in your server code for it to have any effect whatsoever.
75+
That is, you must implement logic in your endpoints which verifies the signature associated with the token included in the auth header, ensures that the
76+
audience is the client id associated with the server app registration and that the scopes included in the claims (after the token's signature has been verified)
77+
matches that of what is required by said endpoint.
78+
3179
## Set up CI/CD via Deployment Center
3280

3381
Now that we have our new Web App resource up and running on Azure, we may proceed to set up our means of deploying our code to the
@@ -56,7 +104,17 @@ For the CI/CD workflow script to actually work, we have to make some adjustments
56104
which are located in their own directories. The autogenerated script assumes that the files are located in the root folder, which is not the case here.
57105
Thus, we need to change the script to reference files located under the server directory, as we are to deploy our server.
58106

59-
The final pipeline definition should look like [this](.github/workflows/main_hvalfangstlinuxwebapp.yml).
107+
We are storing configuration values for our API in a class named [AzureConfig](server/config/config.py). Notice how the values for fields **TENANT_ID**
108+
and **SERVER_CLIENT_ID** are retrieved from the runtime environment - which means that these environment variables must be set somehow. When running the
109+
API locally for sake of testing one should **NOT** hardcode the associated values due to the risk of accidentally committing to SCM. Instead, you should
110+
either set the environment values on your system or retrieve them from an .env file, which, naturally, **HAS** to be added your .gitignore.
111+
112+
Proceed to add two new GitHub Action secrets. These should be your tenant ID and the client ID associated with your newly created **Hvalfangst Server API** app registration.
113+
114+
![screenshot](images/github_actions_hvalfangst_secrets.png)
115+
116+
We now need to modify our GitHub Actions Workflow script to set the environment variables in our Azure Web App itself. We do so by the use of the az CLI
117+
command **az webapp config appsettings set** where the associated values are retrieved from our repository secrets we set above.
60118

61119
## Deploy API
62120

@@ -72,42 +130,72 @@ Navigate to the **Deployment Center** section of your Azure Web App. A new deplo
72130

73131
![screenshot](images/deployment_center_post_action.png)
74132

133+
Click on the **Environment variables** section of your Web App to ensure that the App setting environment variables **HVALFANGST_TENANT_ID** and **HVALFANGST_SERVER_CLIENT_ID**
134+
have been set. The environment variable **SCM_DO_BUILD_DURING_DEPLOYMENT** was set by our [Terraform script](infra/terraform.tf) when creating the Azure Web App. It instructs our container to
135+
build the virtual environment based on our [requirements](server/requirements.txt) file on deploy as opposed to utilizing some pre-built virtual environment that has been transmitted.
136+
137+
![screenshot](images/hvalfangstlinuxwebapp_environment_variables.png)
138+
75139
Now that we know that it deployed successfully it is finally time to access the API. Click on URI associated with **Default Domain**
76140

77141
![screenshot](images/overview_default_domain.png)
78142

79-
You will be prompted with the following default page, which indicates that the API is up and running.
143+
You will be prompted with the following index page, which indicates that the API is up and running.
80144

81145
![screenshot](images/firefox_api_home.png)
82146

147+
The index page is available for all users and as such is not protected by any token validation logic. What is protected by token validation logic is our [heroes route](server/routers/heroes.py).
148+
This route exposes 4 endpoints: "POST /heroes/", "GET /heroes/", "GET /heroes{hero_id}" and "DELETE /heroes/{hero_id}".
149+
Notice how one in each endpoint always start by awaiting a function called [authorize](server/security/auth.py), passing in a token and a scope.
150+
The scope names referenced in aforementioned function call are exactly what was defined earlier. Hence, my little
151+
rant about scopes in and of itself being useless unless there is logic in place in the server code to actually enforce
152+
this. The token is a bearer token, which should be passed in the authorization header. The authorize function will first and foremost attempt to verify the signature associated with the token by
153+
utilizing public keys by use of the keys discovery endpoint exposed by Azure. A handful of keys unique to our tenant will be retrieved when calling the discovery endpoint. The Key ID used to sign the token
154+
is actually included in the header of the token (remember that clients calling the server API first has to get a token from Azure Entra ID authorization server)
83155

84-
## Register API on Azure AD
85156

86-
Now that we have deployed our API to Azure Web Apps, we need to register it on Microsoft Entra ID.
157+
## Register server on Azure Entra ID
87158

88159
### Create a new app registration
89160

90-
Navigate to the **App registrations** blade and click on **New registration** button in the top left tab
161+
In order for our client to be abl
91162

92-
![screenshot](images/azuread_app_registrations.png)
163+
![screenshot](images/hvalfangst_api_client_app_reg.png)
93164

94-
![screenshot](images/azure_entra_id_register_hvalfangst_server_api.png)
165+
![screenshot](images/hvalfangst_client.png)
95166

96-
![screenshot](images/hvalfangst_server_api_app_registration.png)
167+
### Create Secret
97168

169+
![screenshot](images/hvalfangst_client_new_secret.png)
98170

99-
### Expose API
171+
![screenshot](images/hvalfangst_client_add_secret.png)
100172

173+
![screenshot](images/hvalfangst_client_secrets.png)
101174

102-
![screenshot](images/hvalfangst_server_api_expose_api.png)
175+
### Add Redirect URL
103176

177+
![screenshot](images/hvalfangst_client_authentication.png)
104178

105-
![screenshot](images/hvalfangst_server_api_add_scope.png)
179+
![screenshot](images/hvalfangst_client_api_configure_web.png)
106180

107-
![screenshot](images/hvalfangst_server_api_all_scopes.png)
181+
### Add API permissions
182+
183+
![screenshot](images/hvalfangst_client_api_permissions.png)
184+
185+
![screenshot](images/hvalfangst_client_request_permission_graph.png)
186+
187+
![screenshot](images/hvalfangst_client_api_permissions_graph_openid.png)
188+
189+
![screenshot](images/hvalfangst_client_api_permissions_hvalfangst_search.png)
190+
191+
192+
![screenshot](images/hvalfangst_client_api_permissions_hvalfangst_server_heroes_read.png)
108193

194+
![screenshot](images/hvalfangst_client_all_permissions_added.png)
109195

196+
![screenshot](images/hvalfangst_client_grant_admin_consent_prompt.png)
110197

198+
![screenshot](images/hvalfangst_client_permissions_granted_admin_consent_for.png)
111199

112200

113201
## Running API

client/__init__.py

Lines changed: 0 additions & 1 deletion
This file was deleted.

client/config/oauth.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
from dotenv import load_dotenv
44
from fastapi import HTTPException
55
from pydantic_settings import BaseSettings
6-
from client import logger
6+
from logger import logger
77

88
load_dotenv()
99

10+
1011
class OAuthSettings(BaseSettings):
1112
AZURE_CLIENT_ID: str
1213
AZURE_CLIENT_SECRET: str
@@ -21,21 +22,22 @@ class Config:
2122
def initialize_oauth_settings():
2223
try:
2324
# Create an instance of OAuthSettings
24-
internal_oauth_settings = OAuthSettings()
25+
settings = OAuthSettings()
2526

2627
# Check if the required OAuth fields are set
27-
if not internal_oauth_settings.AZURE_CLIENT_ID or not internal_oauth_settings.AZURE_CLIENT_SECRET or not internal_oauth_settings.AZURE_TENANT_ID or not internal_oauth_settings.API_SCOPE:
28-
logger.logger.error("One or more required OAuth environment variables are missing.")
28+
if not settings.AZURE_CLIENT_ID or not settings.AZURE_CLIENT_SECRET \
29+
or not settings.AZURE_TENANT_ID or not settings.API_SCOPE:
30+
logger.error("One or more required OAuth environment variables are missing.")
2931
raise HTTPException(status_code=500,
3032
detail="Configuration error: Required OAuth environment variables are missing.")
3133

32-
logger.logger.info("OAuth settings loaded successfully.")
33-
return internal_oauth_settings
34+
logger.info("OAuth settings loaded successfully.")
35+
return settings
3436
except FileNotFoundError:
35-
logger.logger.critical(".env file not found.")
37+
logger.critical(".env file not found.")
3638
raise HTTPException(status_code=500, detail="Configuration error: .env file not found.")
3739
except Exception as e:
38-
logger.logger.critical(f"Error loading OAuth settings: {e}")
40+
logger.critical(f"Error loading OAuth settings: {e}")
3941
raise HTTPException(status_code=500,
4042
detail="Configuration error: An error occurred while loading OAuth settings.")
4143

client/logger/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from .logger import logger
2+
3+
__all__ = ["logger"]
Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# client/logger.py
2-
31
import logging
42

53
# Configure logging
@@ -8,5 +6,4 @@
86
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
97
)
108

11-
# Create a logger object that can be imported across the application
12-
logger = logging.getLogger(__name__)
9+
logger = logging.getLogger("logger")

client/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# client/main.py
22

33
from fastapi import FastAPI
4-
from client.routers import auth, heroes
4+
from routers import auth, heroes
55

66
app = FastAPI(
77
title="Hero API",

client/models/__init__.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# client/models/__init__.py
1+
from .hero import Hero
22

3-
from .dnd_hero import DnDHero, AbilityScores, SkillProficiencies, Equipment, Spell
4-
5-
__all__ = ["DnDHero", "AbilityScores", "SkillProficiencies", "Equipment", "Spell"]
3+
__all__ = ["Hero"]

client/models/ability_scores.py

Lines changed: 0 additions & 12 deletions
This file was deleted.

client/models/dnd_hero.py

Lines changed: 0 additions & 34 deletions
This file was deleted.

client/models/equipment.py

Lines changed: 0 additions & 10 deletions
This file was deleted.

client/models/hero.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from typing import Optional
2+
from pydantic import BaseModel
3+
4+
5+
class Hero(BaseModel):
6+
id: str
7+
name: str
8+
race: str
9+
class_: str # Avoids conflict with the Python `class` keyword
10+
level: int
11+
background: Optional[str] = None
12+
alignment: Optional[str] = None
13+
14+
# Core combat stats
15+
hit_points: int
16+
armor_class: int
17+
speed: int
18+
19+
# Optional personality fields
20+
personality_traits: Optional[str] = None
21+
ideals: Optional[str] = None
22+
bonds: Optional[str] = None
23+
flaws: Optional[str] = None

client/models/skill_proficiencies.py

Lines changed: 0 additions & 24 deletions
This file was deleted.

client/models/spell.py

Lines changed: 0 additions & 13 deletions
This file was deleted.

client/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,5 @@ config~=0.5.1
55
dotenv~=0.0.5
66
python-dotenv==1.0.1
77
httpx==0.27.2
8-
jwt==1.3.1
8+
pyjwt==2.9.0
99
pydantic_settings==2.6.0

0 commit comments

Comments
 (0)