Skip to content

Commit 6531029

Browse files
Move credentials to env file
1 parent a9c1748 commit 6531029

File tree

5 files changed

+29
-35
lines changed

5 files changed

+29
-35
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ labs-in-progress/
2222
*.log
2323

2424
# Exclude sensitive or generated files
25-
.env
25+
.env*
2626

2727
# Coverage data and reports
2828
.coverage

samples/oauth-3rd-party/README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ Sets up a 3rd party integration via [Azure API Management Credential Manager](ht
1919

2020
## 📝 Scenario
2121

22-
We chose Spotify as it provides an extensive REST API and has relatively generous limits on free API access. This makes for a relatively straight-forward experience for this sample.
22+
We chose Spotify as it provides an extensive [REST API](https://developer.spotify.com/documentation/web-api) and has relatively generous limits on free API access. This makes for a relatively straight-forward experience for this sample.
2323
Specifically, this sample uses Spotify's REST API to obtain information about its deep music and artist catalog. API Management is registered as an application in Spotify's applications with its own client ID and client secret for a given scope. This application is then set up as a generic OAuth 2.0 integration in Credential Manager.
2424
Furthermore, we build on the knowledge gained from the _AuthX_ and _AuthX-Pro_ samples to authentication callers and authorize their use of the Spotify integration.
2525

@@ -58,8 +58,8 @@ In order for API Management to gain access to Spotify's API, we need to create a
5858
- **Redirect URIs**: https://localhost:8080/callback
5959
We will update this placeholder once we have the APIM URL.
6060
- **Which API/SDKs are you planning to use?** _Web API_
61-
1. Once the app has been created, **note the _Client ID_ and _Client secret_**. We will need them for the Credential Manager setup.
62-
1. Leave the Dashboard page open in your browser, as we will need to replaec the Redirect URI shortly.
61+
1. Once the app has been created, copy the _Client ID_ and _Client secret_ into the root `.env` file. We will need them for the Credential Manager setup.
62+
1. Leave the Dashboard page open in your browser, as we will need to replace the Redirect URI shortly.
6363
1. Proceed to the [create](./create.ipynb) Jupyter notebook and follow directions there.
6464

6565
## Acknowledgement

samples/oauth-3rd-party/create.ipynb

Lines changed: 17 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@
2020
"outputs": [],
2121
"source": [
2222
"import utils\n",
23-
"import time\n",
2423
"from apimtypes import *\n",
24+
"import os\n",
2525
"\n",
2626
"# 1) User-defined parameters (change these as needed)\n",
2727
"rg_location = 'eastus2'\n",
@@ -30,14 +30,18 @@
3030
"tags = ['oauth-3rd-party', 'jwt', 'credential-manager', 'policy-fragment'] # ENTER DESCRIPTIVE TAG(S)\n",
3131
"api_prefix = 'oauth-3rd-party-' # OPTIONAL: ENTER A PREFIX FOR THE APIS TO REDUCE COLLISION POTENTIAL WITH OTHER SAMPLES\n",
3232
"# OAuth\n",
33-
"client_id = 'your-spotify-client-id' # ENTER THE OAUTH CLIENT ID FOR THE BACKEND API\n",
34-
"client_secret = 'your-spotify-client-secret' # ENTER THE OAUTH CLIENT SECRET FOR THE BACKEND API\n",
33+
"client_id = os.getenv('SPOTIFY_CLIENT_ID') # ENTER THE OAUTH CLIENT ID FOR THE BACKEND API\n",
34+
"client_secret = os.getenv('SPOTIFY_CLIENT_SECRET') # ENTER THE OAUTH CLIENT SECRET FOR THE BACKEND API\n",
3535
"\n",
3636
"# 2) Service-defined parameters (please do not change these)\n",
3737
"rg_name = utils.get_infra_rg_name(deployment, index)\n",
3838
"sample_folder = \"oauth-3rd-party\"\n",
3939
"nb_helper = utils.NotebookHelper(sample_folder, rg_name, rg_location, deployment, [INFRASTRUCTURE.AFD_APIM_PE, INFRASTRUCTURE.APIM_ACA, INFRASTRUCTURE.SIMPLE_APIM], True)\n",
4040
"\n",
41+
"if len(client_id) == 0 or len(client_secret) == 0:\n",
42+
" utils.print_error('Please set the SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET environment variables in the root .env file before running this notebook.')\n",
43+
" raise ValueError('Missing Spotify OAuth credentials')\n",
44+
"\n",
4145
"# 3) Set up the named values\n",
4246
"nvs: List[NamedValue] = [\n",
4347
" NamedValue(nb_helper.jwt_key_name, nb_helper.jwt_key_value_bytes_b64, True),\n",
@@ -107,10 +111,7 @@
107111
"if output.json_data:\n",
108112
" apim_name = output.get('apimServiceName', 'APIM Service Name')\n",
109113
" apim_gateway_url = output.get('apimResourceGatewayURL', 'APIM API Gateway URL')\n",
110-
"\n",
111-
" # TODO: This should be retrieved from an output; however, the format is static.\n",
112-
" apim_oauth_redirect_url = f'https://authorization-manager.consent.azure-apim.net/redirect/apim/{apim_name}'\n",
113-
" utils.print_val('APIM OAuth Redirect URL', apim_oauth_redirect_url)\n",
114+
" spotify_oauth_redirect_url = output.get('spotifyOAuthRedirectUrl', 'Spotify OAuth Redirect URL')\n",
114115
"\n",
115116
"utils.print_ok('Deployment completed')"
116117
]
@@ -175,27 +176,15 @@
175176
"encoded_jwt_token_marketing_member = AuthFactory.create_symmetric_jwt_token_for_user(UserHelper.get_user_by_role(Role.MARKETING_MEMBER), nb_helper.jwt_key_value)\n",
176177
"print(f'\\nJWT token for Marketing Member:\\n{encoded_jwt_token_marketing_member}') # this value is used to call the APIs via APIM\n",
177178
"\n",
178-
"# Issue requests against Front Door.\n",
179-
"utils.print_message('Checking if the infrastructure architecture deployment uses Azure Front Door.', blank_above = True)\n",
180-
"afd_endpoint_url = utils.get_frontdoor_url(deployment, rg_name)\n",
181-
"\n",
182-
"if afd_endpoint_url:\n",
183-
" artist_id = '06HL4z0CvFAxyc27GXpf02' # Taylor Swift's Spotify Artist ID\n",
184-
" reqsAfd = ApimRequests(afd_endpoint_url)\n",
185-
" reqsAfd.headers['Authorization'] = f'Bearer {encoded_jwt_token_marketing_member}'\n",
186-
" output = reqsAfd.singleGet(f'/oauth-3rd-party-spotify/artists/{artist_id}', msg = 'Calling the Spotify Artist API via API Management Gateway URL.')\n",
187-
" artist = json.loads(output)\n",
188-
" tests.verify(artist['name'], 'Taylor Swift')\n",
189-
" utils.print_info(f'{artist[\"name\"]} has a popularity rating of {artist[\"popularity\"]} with {artist[\"followers\"][\"total\"]:,} followers on Spotify.')\n",
190-
"else:\n",
191-
" # Issue a direct request to API Management\n",
192-
" artist_id = '6XpaIBNiVzIetEPCWDvAFP' # Whitney Houston's Spotify Artist ID\n",
193-
" reqsApim = ApimRequests(apim_gateway_url)\n",
194-
" reqsApim.headers['Authorization'] = f'Bearer {encoded_jwt_token_marketing_member}'\n",
195-
" output = reqsApim.singleGet(f'/oauth-3rd-party-spotify/artists/{artist_id}', msg = 'Calling the Spotify Artist API via API Management Gateway URL.')\n",
196-
" artist = json.loads(output)\n",
197-
" tests.verify(artist['name'], 'Whitney Houston')\n",
198-
" utils.print_info(f'{artist[\"name\"]} has a popularity rating of {artist[\"popularity\"]} with {artist[\"followers\"][\"total\"]:,} followers on Spotify.')\n",
179+
"# Preflight: Check if the infrastructure architecture deployment uses Azure Front Door. If so, assume that APIM is not directly accessible and use the Front Door URL instead.\n",
180+
"endpoint_url = utils.test_url_preflight_check(deployment, rg_name, apim_gateway_url)\n",
181+
"reqs = ApimRequests(endpoint_url)\n",
182+
"reqs.headers['Authorization'] = f'Bearer {encoded_jwt_token_marketing_member}'\n",
183+
"artist_id = '06HL4z0CvFAxyc27GXpf02' # Taylor Swift's Spotify Artist ID\n",
184+
"output = reqs.singleGet(f'/oauth-3rd-party-spotify/artists/{artist_id}', msg = 'Calling the Spotify Artist API via API Management Gateway URL.')\n",
185+
"artist = json.loads(output)\n",
186+
"tests.verify(artist['name'], 'Taylor Swift')\n",
187+
"utils.print_info(f'{artist[\"name\"]} has a popularity rating of {artist[\"popularity\"]} with {artist[\"followers\"][\"total\"]:,} followers on Spotify.')\n",
199188
"\n",
200189
"tests.print_summary()\n",
201190
"\n",

samples/oauth-3rd-party/main.bicep

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,3 +155,4 @@ module apisModule '../../shared/bicep/modules/apim/v1/api.bicep' = [for api in a
155155
output apimServiceId string = apimService.id
156156
output apimServiceName string = apimService.name
157157
output apimResourceGatewayURL string = apimService.properties.gatewayUrl
158+
output spotifyOAuthRedirectUrl string = spotifyAuthorizationProvider.properties.oauth2.redirectUrl

setup/setup_python_path.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,8 @@ def generate_env_file() -> None:
9999
env_content = f"""# Auto-generated PYTHONPATH for VS Code - Run 'python setup/setup_python_path.py' to regenerate
100100
PROJECT_ROOT={project_root}
101101
PYTHONPATH={shared_python_path}
102+
SPOTIFY_CLIENT_ID=
103+
SPOTIFY_CLIENT_SECRET=
102104
"""
103105

104106
env_file_path = project_root / '.env'
@@ -109,9 +111,11 @@ def generate_env_file() -> None:
109111
f.write(env_content)
110112

111113
print()
112-
print(f"Generated .env file : {env_file_path}")
113-
print(f"PROJECT_ROOT : {project_root}")
114-
print(f"PYTHONPATH : {shared_python_path}\n")
114+
print(f"Generated .env file : {env_file_path}")
115+
print(f"PROJECT_ROOT : {project_root}")
116+
print(f"PYTHONPATH : {shared_python_path}")
117+
print(f"SPOTIFY_CLIENT_ID : ")
118+
print(f"SPOTIFY_CLIENT_SECRET : \n")
115119

116120

117121
def install_jupyter_kernel():

0 commit comments

Comments
 (0)