Skip to content

Commit 761b2ea

Browse files
author
Steve Hobbs
committed
Transferred tutorial for scenario 03
1 parent 3ca1c46 commit 761b2ea

File tree

3 files changed

+108
-71
lines changed

3 files changed

+108
-71
lines changed

01-Login/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ import authConfig from "../../auth_config.json";
137137

138138
const webAuth = new auth0.WebAuth({
139139
domain: authConfig.domain,
140-
redirectUri: `<%= "${window.location.origin}" %>/callback`,
140+
redirectUri: `${window.location.origin}/callback`,
141141
clientID: authConfig.clientId,
142142
responseType: "id_token",
143143
scope: "openid profile email"

03-Calling-an-API/README.md

Lines changed: 107 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,78 @@
1-
---
2-
title: Calling an API
3-
description: This tutorial demonstrates how to make calls to an external API
4-
budicon: 546
5-
topics:
6-
- quickstarts
7-
- spa
8-
- vuejs
9-
- apis
10-
github:
11-
path: 03-Calling-an-API
12-
sample_download_required_data:
13-
- client
14-
- api
15-
contentType: tutorial
16-
useCase: quickstart
17-
---
18-
19-
<!-- markdownlint-disable MD002 MD041 -->
1+
# Scenario #3 - Calling an External API
2+
3+
For this scenario, an API endpoint `/api/external` has been included in the Express server that requires a bearer token to be supplied as a bearer token in the `Authorization` header (as provided during the authentication flow). This uses the [`express-jwt`](https://github.com/auth0/express-jwt) middleware to validate the token against the identifier of your API as set up in the Auth0 dashboard, as well as checking that the signature is valid.
4+
5+
## Project setup
6+
7+
```bash
8+
npm install
9+
```
10+
11+
### Configuration
12+
13+
The project needs to be configured with your Auth0 domain and client ID in order for the authentication flow to work.
14+
15+
To do this, first copy `auth_config.sample.json` into a new file in the same folder called `auth_config.json`, and replace the values within with your own Auth0 application credentials:
16+
17+
```json
18+
{
19+
"domain": "<YOUR AUTH0 DOMAIN>",
20+
"audience": "<YOUR AUTH0 API IDENTIFIER>",
21+
"clientId": "<YOUR AUTH0 CLIENT ID>"
22+
}
23+
```
24+
25+
### Running in development
26+
27+
This compiles and serves the Vue app, and starts the backend API server on port 3001:
28+
29+
```bash
30+
npm run dev
31+
```
32+
33+
## Deployment
34+
35+
### Compiles and minifies for production
36+
37+
```bash
38+
npm run build
39+
```
40+
41+
### Docker build
42+
43+
To build the Docker image run `exec.sh`, or `exec.ps1` on Windows.
44+
45+
### Run your tests
46+
47+
```bash
48+
npm run test
49+
```
50+
51+
### Lints and fixes files
52+
53+
```bash
54+
npm run lint
55+
```
56+
57+
## Tutorial
2058

2159
Most single-page apps use resources from data APIs. You may want to restrict access to those resources, so that only authenticated users with sufficient privileges can access them. Auth0 lets you manage access to these resources using [API Authorization](/api-auth).
2260

2361
This tutorial shows you how to create a simple API using [Express](https://expressjs.com) that validates incoming JSON Web Tokens. You will then see how to call this API using an Access Token granted by the Auth0 authorization server.
2462

25-
## Create an API
63+
### Create an API
2664

27-
In the [APIs section](https://manage.auth0.com//#/apis) of the Auth0 dashboard, click **Create API**. Provide a name and an identifier for your API.
65+
In the [APIs section](https://manage.auth0.com/#/apis) of the Auth0 dashboard, click **Create API**. Provide a name and an identifier for your API.
2866
You will use the identifier later when you're configuring your Javascript Auth0 application instance.
2967
For **Signing Algorithm**, select **RS256**.
3068

31-
![Create API](/media/articles/api-auth/create-api.png)
69+
![Create API](../docs/create-api.png)
3270

33-
## Modify the Backend API
71+
### Modify the Backend API
3472

3573
For this tutorial, let's modify the API to include a new endpoint that expects an Access Token to be supplied.
3674

37-
> In a real scenario, this work would be done by the external API that is to be called from the frontend. This new endpoint is simply a convenience to serve as a learning exercise.
75+
> **Note** In a real scenario, this work would be done by the external API that is to be called from the frontend. This new endpoint is simply a convenience to serve as a learning exercise.
3876
3977
Open `server.js` and add a new Express route to serve as the API endpoint, right underneath the existing one:
4078

@@ -60,7 +98,7 @@ app.get("/api/external", checkJwt, (req, res) => {
6098

6199
Notice that it continues to use the same `checkJwt` middleware in order to validate the Access Token. The difference here is that the Access Token must be validated using the API identifier, rather than the client ID that we used for the ID Token.
62100

63-
> The API identifier is the identifer that was specified when the API was created in the [Auth0 dashboard](https://manage.auth0.com//#/apis).
101+
> **Note** The API identifier is the identifer that was specified when the API was created in the [Auth0 dashboard](https://manage.auth0.com/#/apis).
64102
65103
Therefore, modify the `checkJwt` function to include the API identifier value in the `audience` setting:
66104

@@ -70,25 +108,25 @@ const checkJwt = jwt({
70108
cache: true,
71109
rateLimit: true,
72110
jwksRequestsPerMinute: 5,
73-
jwksUri: `https://<%= "${authConfig.domain}" %>/.well-known/jwks.json`
111+
jwksUri: `https://${authConfig.domain}/.well-known/jwks.json`
74112
}),
75113

76114
// Modify the audience to include both the client ID and the audience from configuration in an array
77115
audience: [authConfig.clientID, authConfig.audience],
78-
issuer: `https://<%= "${authConfig.domain}" %>/`,
116+
issuer: `https://${authConfig.domain}/`,
79117
algorithm: ["RS256"]
80118
});
81119
```
82120

83-
> As the `audience` property accepts an array of values, both the client ID and the API identifier can be given, allowing both the ID Token and the Access Token to be verified using the same middleware.
121+
> **Note** As the `audience` property accepts an array of values, both the client ID and the API identifier can be given, allowing both the ID Token and the Access Token to be verified using the same middleware.
84122
85123
Finally, modify the `authConfig` object to include your `audience` value:
86124

87125
```js
88126
const authConfig = {
89-
domain: "${account.namespace}",
90-
clientID: "${account.clientId}",
91-
audience: "${apiIdentifier}"
127+
domain: "<YOUR AUTH0 DOMAIN>",
128+
clientID: "<YOUR AUTH0 CLIENT ID>",
129+
audience: "<YOUR AUTH0 API IDENTIFIER>"
92130
};
93131
```
94132

@@ -105,7 +143,7 @@ Finally, modify `package.json` to add two new scripts `dev` and `api` that can b
105143
"lint": "vue-cli-service lint",
106144
"dev": "npm-run-all --parallel serve api",
107145
"api": "node server.js"
108-
},
146+
}
109147

110148
// .. package dependencies and other JSON nodes
111149
}
@@ -131,21 +169,21 @@ module.exports = {
131169
};
132170
```
133171

134-
> This assumes that your project was created using [Vue CLI 3](https://cli.vuejs.org/guide/). If your project was not created in the same way, the above should be included as part of your Webpack configuration.
172+
> **Note** This assumes that your project was created using [Vue CLI 3](https://cli.vuejs.org/guide/). If your project was not created in the same way, the above should be included as part of your Webpack configuration.
135173
136174
With this in place, the frontend application can make a request to `/api/external` and it will be correctly proxied through to the backend API at `http://localhost:3001/api/external`.
137175

138-
## Modify the AuthService Class
176+
### Modify the AuthService Class
139177

140178
To start, open `authService.js` and make the necessary changes to the class to support retrieving an Access Token from the authorization server and exposing that token from a method.
141179

142180
First of all, open `auth_config.json` in the root of the project and make sure that a value for `audience` is exported along with the other settings:
143181

144182
```json
145183
{
146-
"domain": "${account.namespace}",
147-
"clientId": "${account.clientId}",
148-
"audience": "${apiIdentifier}"
184+
"domain": "<YOUR AUTH0 DOMAIN>",
185+
"clientId": "<YOUR AUTH0 CLIENT ID>",
186+
"audience": "<YOUR AUTH0 API IDENTIFIER>"
149187
}
150188
```
151189

@@ -156,15 +194,15 @@ Then, modify the `webAuth` creation to include `token` in the response type and
156194

157195
const webAuth = new auth0.WebAuth({
158196
domain: authConfig.domain,
159-
redirectUri: `<%= "${window.location.origin}" %>/callback`,
197+
redirectUri: `${window.location.origin}/callback`,
160198
clientID: authConfig.clientId,
161-
audience: authConfig.audience, // add the audience
162-
responseType: "token id_token", // request 'token' as well as 'id_token'
199+
audience: authConfig.audience, // add the audience
200+
responseType: "token id_token", // request 'token' as well as 'id_token'
163201
scope: "openid profile email"
164202
});
165203
```
166204

167-
> Setting the `responseType` field to "token id_token" will cause the authorization server to return both the Access Token and the ID Token in a URL fragment.
205+
> **Note** Setting the `responseType` field to "token id_token" will cause the authorization server to return both the Access Token and the ID Token in a URL fragment.
168206
169207
Next, modify the `AuthService` class to include fields to store the Access Token and the time that the Access Token will expire:
170208

@@ -215,7 +253,6 @@ Finally, add two methods to the class that validate the Access Token and provide
215253
// src/auth/authService.js
216254

217255
class AuthService extends EventEmitter {
218-
219256
// ... other methods
220257

221258
isAccessTokenValid() {
@@ -240,9 +277,9 @@ class AuthService extends EventEmitter {
240277
}
241278
```
242279

243-
> If `getAccessToken` is called and the Access Token is no longer valid, a new token will be retrieved automatically by calling `renewTokens`.
280+
> **Note** If `getAccessToken` is called and the Access Token is no longer valid, a new token will be retrieved automatically by calling `renewTokens`.
244281
245-
## Call the API Using an Access Token
282+
### Call the API Using an Access Token
246283

247284
The frontend Vue.js application should be modified to include a page that calls the API using an Access Token. Similar to the previous tutorial, this includes modifying the Vue router and adding a new view with a button that calls the API.
248285

@@ -294,13 +331,13 @@ export default {
294331
try {
295332
const { data } = await axios.get("/api/external", {
296333
headers: {
297-
Authorization: `Bearer <%= "${accessToken}" %>`
334+
Authorization: `Bearer ${accessToken}`
298335
}
299336
});
300337
301338
this.apiMessage = data.msg;
302339
} catch (e) {
303-
this.apiMessage = `Error: the server responded with '<%= "${ e.response.status }" %>: <%= "${e.response.statusText}" %>'`; }
340+
this.apiMessage = `Error: the server responded with '${ e.response.status }: ${e.response.statusText}'`; }
304341
}
305342
}
306343
};
@@ -363,30 +400,30 @@ Finally, modify the navigation bar to include a link to the new page:
363400
364401
Now you will be able to run the application, browse to the "External API" page and press the "Ping" button. The application will make a call to the external API endpoint and produce a message on the screen that says "Your Access Token was successfully validated!".
365402
366-
To run the sample follow these steps:
403+
## What is Auth0?
367404
368-
1) Set the **Callback URL** in the [Application Settings](https://manage.auth0.com//#/applications/) to
369-
```text
370-
http://localhost:3000/callback
371-
```
372-
2) Set **Allowed Web Origins** in the [Application Settings](https://manage.auth0.com//#/applications/) to
373-
```text
374-
http://localhost:3000
375-
```
376-
3) Set **Allowed Logout URLs** in the [Application Settings](https://manage.auth0.com//#/applications/) to
405+
Auth0 helps you to:
377406
378-
```text
379-
http://localhost:3000
380-
```
381-
4) Make sure [Node.JS LTS](https://nodejs.org/en/download/) is installed and execute the following commands in the sample's directory:
382-
```bash
383-
npm install && npm run serve
384-
```
385-
You can also run it from a [Docker](https://www.docker.com) image with the following commands:
407+
- Add authentication with [multiple authentication sources](https://docs.auth0.com/identityproviders), either social like **Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, among others**, or enterprise identity systems like **Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider**.
408+
- Add authentication through more traditional **[username/password databases](https://docs.auth0.com/mysql-connection-tutorial)**.
409+
- Add support for **[linking different user accounts](https://docs.auth0.com/link-accounts)** with the same user.
410+
- Support for generating signed [Json Web Tokens](https://docs.auth0.com/jwt) to call your APIs and **flow the user identity** securely.
411+
- Analytics of how, when and where users are logging in.
412+
- Pull data from other sources and add it to the user profile, through [JavaScript rules](https://docs.auth0.com/rules).
386413
387-
```bash
388-
# In Linux / macOS
389-
sh exec.sh
390-
# In Windows' Powershell
391-
./exec.ps1
392-
```
414+
## Create a Free Auth0 Account
415+
416+
1. Go to [Auth0](https://auth0.com/signup) and click Sign Up.
417+
2. Use Google, GitHub or Microsoft Account to login.
418+
419+
## Issue Reporting
420+
421+
If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.
422+
423+
## Author
424+
425+
[Auth0](https://auth0.com)
426+
427+
## License
428+
429+
This project is licensed under the MIT license. See the [LICENSE](../LICENSE) file for more info.

docs/create-api.png

201 KB
Loading

0 commit comments

Comments
 (0)