You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
20
58
21
59
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).
22
60
23
61
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.
24
62
25
-
## Create an API
63
+
###Create an API
26
64
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.
28
66
You will use the identifier later when you're configuring your Javascript Auth0 application instance.
For this tutorial, let's modify the API to include a new endpoint that expects an Access Token to be supplied.
36
74
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.
38
76
39
77
Open `server.js` and add a new Express route to serve as the API endpoint, right underneath the existing one:
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.
62
100
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).
64
102
65
103
Therefore, modify the `checkJwt` function to include the API identifier value in the `audience` setting:
> 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.
84
122
85
123
Finally, modify the `authConfig` object to include your `audience` value:
86
124
87
125
```js
88
126
constauthConfig= {
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>"
92
130
};
93
131
```
94
132
@@ -105,7 +143,7 @@ Finally, modify `package.json` to add two new scripts `dev` and `api` that can b
105
143
"lint": "vue-cli-service lint",
106
144
"dev": "npm-run-all --parallel serve api",
107
145
"api": "node server.js"
108
-
},
146
+
}
109
147
110
148
// .. package dependencies and other JSON nodes
111
149
}
@@ -131,21 +169,21 @@ module.exports = {
131
169
};
132
170
```
133
171
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.
135
173
136
174
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`.
137
175
138
-
## Modify the AuthService Class
176
+
###Modify the AuthService Class
139
177
140
178
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.
141
179
142
180
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:
143
181
144
182
```json
145
183
{
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>"
149
187
}
150
188
```
151
189
@@ -156,15 +194,15 @@ Then, modify the `webAuth` creation to include `token` in the response type and
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'
163
201
scope:"openid profile email"
164
202
});
165
203
```
166
204
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.
168
206
169
207
Next, modify the `AuthService` class to include fields to store the Access Token and the time that the Access Token will expire:
170
208
@@ -215,7 +253,6 @@ Finally, add two methods to the class that validate the Access Token and provide
215
253
// src/auth/authService.js
216
254
217
255
classAuthServiceextendsEventEmitter {
218
-
219
256
// ... other methods
220
257
221
258
isAccessTokenValid() {
@@ -240,9 +277,9 @@ class AuthService extends EventEmitter {
240
277
}
241
278
```
242
279
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`.
244
281
245
-
## Call the API Using an Access Token
282
+
###Call the API Using an Access Token
246
283
247
284
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.
248
285
@@ -294,13 +331,13 @@ export default {
294
331
try {
295
332
const { data } = await axios.get("/api/external", {
296
333
headers: {
297
-
Authorization: `Bearer <%= "${accessToken}" %>`
334
+
Authorization: `Bearer ${accessToken}`
298
335
}
299
336
});
300
337
301
338
this.apiMessage = data.msg;
302
339
} 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}'`; }
304
341
}
305
342
}
306
343
};
@@ -363,30 +400,30 @@ Finally, modify the navigation bar to include a link to the new page:
363
400
364
401
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!".
365
402
366
-
To run the sample follow these steps:
403
+
## What is Auth0?
367
404
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:
377
406
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).
386
413
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.
0 commit comments