Skip to content

Commit

Permalink
Run7 URI postwork suggestion (#14)
Browse files Browse the repository at this point in the history
* remove old config not necessary anymore

* make modification needed better visible

* remove hardcoded URI prefix and introduce CLIENT_ID on episodes

* add redirect_uri to config

* make sure we use patched env in tests

* remove remnants

* Add two small clarifications

---------

Co-authored-by: Lars Kåre Skjørestad <[email protected]>
  • Loading branch information
steinsiv and larskaare authored Jan 23, 2024
1 parent 9d1950b commit 90abb39
Show file tree
Hide file tree
Showing 18 changed files with 25 additions and 44 deletions.
2 changes: 1 addition & 1 deletion ex-10/client/lib/app-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const msalConfig = {
file: tokenCacheFile,
},
scopes: {
gotApi: ['api://f6a763f4-932d-4784-8122-f2b526bb2364/Episodes.Read'],
gotApi: ['api://00000000-0000-0000-0000-000000000000/Episodes.Read'],
inbox: ['user.read', 'mail.read'],
},
};
Expand Down
1 change: 1 addition & 0 deletions ex-10/doc/configure_client_anda_api.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export NODE_ENV=development
export CLIENT_ID="the client id from the AD app object"
export TENANT_ID="then tenant id"
export PORT=3000
export REDIRECT_URI=$(aa-get-redirect-uri.sh)
export TOKEN_CACHE_FILE="${HOME}/.tcache/cache.json"
```
### Additional config
Expand Down
2 changes: 1 addition & 1 deletion ex-10/doc/swapping_tech_for_episodes_api.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Steps:
pytest
```
- In `./src/core/config.py` update the API audience to reflect your API (AppSettings)
- Follow the pattern in the code for this; use only the GUID not the whole URI
- Follow the pattern in the code for this; use the Application ID URI.
- Remember to save

--Now You--
Expand Down
2 changes: 1 addition & 1 deletion ex-10/got-episodes-api-python/src/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def get_settings():
port = os.environ.get('PORT', 3100),
host = os.environ.get('HOST', '127.0.0.1'),
jwks_uri = f"https://login.microsoftonline.com/{os.environ['TENANT_ID']}/discovery/v2.0/keys",
api_audience= f"api://{os.environ.get('EPISODES_API_URI', 'f6a763f4-932d-4784-8122-f2b526bb2364')}"
api_audience= f"{os.environ.get('EPISODES_API_URI', 'api://00000000-0000-0000-0000-000000000000')}"
)
except ValidationError as exc:
for err in exc.errors():
Expand Down
9 changes: 5 additions & 4 deletions ex-10/got-episodes-api-python/tests/core/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def patchenv(monkeypatch):
monkeypatch.setenv('TENANT_ID', 'test_tenant_id')
monkeypatch.setenv('PORT', '7777')
monkeypatch.setenv('HOST', 'test_host')

monkeypatch.setenv('EPISODES_API_URI', 'api://00000000-7e57-c0de-0000-000000000000')
yield monkeypatch

def test_valid_app_settings(patchenv):
Expand All @@ -22,10 +22,11 @@ def test_valid_app_settings(patchenv):
assert config.host == 'test_host'
# Generated
assert config.jwks_uri == HttpUrl(f"https://login.microsoftonline.com/{config.tenant_id}/discovery/v2.0/keys")
assert config.api_audience == f"api://f6a763f4-932d-4784-8122-f2b526bb2364"
assert config.api_audience == "api://00000000-7e57-c0de-0000-000000000000"
assert config.issuer == HttpUrl(f"https://sts.windows.net/{config.tenant_id}/")

def test_missing_environment_variables():
def test_missing_environment_variables(patchenv):
patchenv.delenv('TENANT_ID')
with pytest.raises(KeyError):
get_settings()

Expand All @@ -38,7 +39,7 @@ def test_get_uvicorn_config(patchenv):
def test_get_claims_options(patchenv):
expected_claims_options = {
"iss": {"essential": True, "value": f"https://sts.windows.net/{os.environ['TENANT_ID']}/",},
"aud": {"essential": True, "value": f"api://f6a763f4-932d-4784-8122-f2b526bb2364"},
"aud": {"essential": True, "value": "api://00000000-7e57-c0de-0000-000000000000"},
}
result_claims_options = get_claims_options()
assert result_claims_options == expected_claims_options
2 changes: 1 addition & 1 deletion ex-10/got-episodes-api/lib/app-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const host = process.env.HOST || 'localhost';
const swaggerHost = process.env.SWAGGER_HOST || host + ':' + port;

const jwksUri = 'https://login.microsoftonline.com/' + tenantId + '/discovery/v2.0/keys';
const apiAudience = 'api://f6a763f4-932d-4784-8122-f2b526bb2364';
const apiAudience = 'api://00000000-0000-0000-0000-000000000000';

const rateLimitAllowList = function () {
return ['127.0.0.1','::1'];
Expand Down
2 changes: 1 addition & 1 deletion ex-11/client/lib/app-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const msalConfig = {
file: tokenCacheFile,
},
scopes: {
gotApi: ['api://' + process.env.EPISODES_API_URI + '/episodes.read'],
gotApi: [process.env.EPISODES_API_URI + '/episodes.read'],
inbox: ['user.read', 'mail.read'],
},
};
Expand Down
3 changes: 1 addition & 2 deletions ex-11/doc/client_code_config.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ Steps:

* New environment variables `EPISODES_API_URI` and `EPISODES_API_URL` that needs to be added to then env file
* Hint: Microsoft Entra ID -> App Registrations -> Episodes Api -> Expose An Api -> Application ID URI
* Hint: Exclude the prefix 'api://'
* Update the client env file (appsec-course-client-eq.env)
* Update the client env file (appsec-course-client-eq.env)
* Run `aa-save-env-files-to-github-user-secret.sh` in a terminal window to persist the new environment variables (don't __reload__)


Expand Down
2 changes: 2 additions & 0 deletions ex-11/doc/quotes_code_config.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Steps:
export PORT=3200
export QUOTES_API_URI=""
export EPISODES_API_URI=""
export EPISODES_API_CLIENT_ID=""
```

* The App
Expand Down Expand Up @@ -62,6 +63,7 @@ Using the procedure from [exercise-10](../../ex-10/doc/registering_api_in_azure_
export PORT=3200
export QUOTES_API_URI=""
export EPISODES_API_URI=""
export EPISODES_API_CLIENT_ID=""
```

### --Now You--
Expand Down
2 changes: 1 addition & 1 deletion ex-11/got-episodes-api-python/src/core/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def get_obo_token(assertion: str):
"client_id": config.client_id,
"client_secret": config.client_secret,
"assertion": assertion,
"scope": f"api://{config.quotes_api_uri}/Quote.Read",
"scope": f"{config.quotes_api_uri}/Quote.Read",
"requested_token_use": "on_behalf_of",
}
tokenEndpoint = get_token_endpoint(well_known_conf_url)
Expand Down
2 changes: 1 addition & 1 deletion ex-11/got-episodes-api-python/src/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def get_settings():
port = os.environ.get('PORT', 3100),
host = os.environ.get('HOST', '127.0.0.1'),
jwks_uri = f"https://login.microsoftonline.com/{os.environ['TENANT_ID']}/discovery/v2.0/keys",
api_audience= f"api://{os.environ.get('EPISODES_API_URI', '251bc275-eed7-49d6-83b3-9005c9779574')}"
api_audience= os.environ['EPISODES_API_URI']
)
except ValidationError as exc:
for err in exc.errors():
Expand Down
4 changes: 2 additions & 2 deletions ex-11/got-episodes-api-python/tests/core/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def test_valid_app_settings(patchenv):
assert config.host == 'test_host'
# Generated
assert config.jwks_uri == HttpUrl(f"https://login.microsoftonline.com/{config.tenant_id}/discovery/v2.0/keys")
assert config.api_audience == f"api://{config.episodes_api_uri}"
assert config.api_audience == f"{config.episodes_api_uri}"
assert config.issuer == HttpUrl(f"https://sts.windows.net/{config.tenant_id}/")

def test_missing_environment_variables(patchenv):
Expand All @@ -55,7 +55,7 @@ def test_get_well_known_conf_url(patchenv):
def test_get_claims_options(patchenv):
expected_claims_options = {
"iss": {"essential": True, "value": f"https://sts.windows.net/{os.environ['TENANT_ID']}/",},
"aud": {"essential": True, "value": f"api://{os.environ['EPISODES_API_URI']}"},
"aud": {"essential": True, "value": f"{os.environ['EPISODES_API_URI']}"},
}
result_claims_options = get_claims_options()
assert result_claims_options == expected_claims_options
4 changes: 2 additions & 2 deletions ex-11/got-episodes-api/lib/app-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ const host = process.env.HOST || 'localhost';
const swaggerHost = process.env.SWAGGER_HOST || host + ':' + port;

const jwksUri = 'https://login.microsoftonline.com/' + tenantId + '/discovery/v2.0/keys';
const apiAudience = 'api://' + process.env.EPISODES_API_URI;
const apiAudience = process.env.EPISODES_API_URI;
const quoteApiUrl = process.env.QUOTES_API_URL + '/api/quote';
const quoteApiScope = 'api://' + process.env.QUOTES_API_URI + '/quote.read';
const quoteApiScope = process.env.QUOTES_API_URI + '/quote.read';

const rateLimitAllowList = function () {
return ['127.0.0.1','::1'];
Expand Down
24 changes: 0 additions & 24 deletions ex-11/got-quote-api-dotnet/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,30 +28,6 @@ Expects the following environment variables to execute properly
export EPISODES_API_URI=""
```

Also visit application important settings in `appsettings.json` and correct all fieds for validation of JWT token

```json
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "<TENANT_ID>",
"ClientId": "<QUOTE_CLIENT_ID>",
"Jwt": {
"Authority": "https://login.microsoftonline.com/<TENANT_ID>/v2.0/",
"TokenValidationParameters": {
"ValidateIssuer": true,
"ValidIssuer": "https://sts.windows.net/<TENANT_ID>/",
"ValidateAudience": true,
"ValidAudience": "api://<QUOTE_URI>",
"ValidateLifetime": true,
"ValidateIssuerSigningKey": true
}
},
},
}

```

### Execute

```sh
Expand Down
2 changes: 1 addition & 1 deletion ex-11/got-quote-api-dotnet/src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
} else {
builder.Configuration["AzureAd:Jwt:Authority"] = $"https://login.microsoftonline.com/{TENANT_ID}/v2.0/";
builder.Configuration["AzureAd:Jwt:TokenValidationParameters:ValidIssuer"] = $"https://sts.windows.net/{TENANT_ID}/";
builder.Configuration["AzureAd:Jwt:TokenValidationParameters:ValidAudience"] = $"api://{QUOTES_API_URI}";
builder.Configuration["AzureAd:Jwt:TokenValidationParameters:ValidAudience"] = $"{QUOTES_API_URI}";
}

builder.Services.AddEndpointsApiExplorer();
Expand Down
4 changes: 2 additions & 2 deletions ex-11/got-quote-api/lib/app-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ const host = process.env.HOST || 'localhost';
const swaggerHost = process.env.SWAGGER_HOST || host + ':' + port;

const jwksUri = 'https://login.microsoftonline.com/' + tenantId + '/discovery/v2.0/keys';
const apiAudience = 'api://' + process.env.QUOTES_API_URI; // This API
const quoteApiApprovedCallingApps = [process.env.EPISODES_API_URI];
const apiAudience = process.env.QUOTES_API_URI; // This API
const quoteApiApprovedCallingApps = [process.env.EPISODES_API_CLIENT_ID];

const rateLimitAllowList = function () {
return ['127.0.0.1', '::1'];
Expand Down
1 change: 1 addition & 0 deletions ex-11/got-quote-api/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ Expects the following environment variables to execute properly
export PORT=3200
export QUOTES_API_URI=""
export EPISODES_API_URI=""
export EPISODES_API_CLIENT_ID=""


Other config, like ratelimiting and **apiAudience** , is defined in './lib/app-config.js' and also needs to be verified.
Expand Down
1 change: 1 addition & 0 deletions src/templates/quote.env.template
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export TENANT_ID=''
export PORT=3200
export HOST=127.0.0.1
export EPISODES_API_URI=''
export EPISODES_API_CLIENT_ID=''
export QUOTES_API_URI=''

0 comments on commit 90abb39

Please sign in to comment.