Skip to content

Commit 2a34893

Browse files
Update readme based on internal redesign (#745)
* Update readme based on internal redesign * update * add coverage badge * Add banner * Avoid relative links * Use banner from CDN * Move API reference to API.md * Add title to examples * update banner
1 parent 8da9e64 commit 2a34893

File tree

3 files changed

+330
-335
lines changed

3 files changed

+330
-335
lines changed

API.md

+209
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
## API reference
2+
3+
- [JwtModule configuration options](#jwtmodule-configuration-options)
4+
- [JwtHelperService](#jwthelperservice)
5+
6+
### `JwtModule` configuration options
7+
8+
#### `tokenGetter: function(HttpRequest): string`
9+
10+
The `tokenGetter` is a function which returns the user's token. This function simply needs to make a retrieval call to wherever the token is stored. In many cases, the token will be stored in local storage or session storage.
11+
12+
```ts
13+
// ...
14+
JwtModule.forRoot({
15+
config: {
16+
// ...
17+
tokenGetter: () => {
18+
return localStorage.getItem("access_token");
19+
},
20+
},
21+
});
22+
```
23+
24+
If you have multiple tokens for multiple domains, you can use the `HttpRequest` passed to the `tokenGetter` function to get the correct token for each intercepted request.
25+
26+
```ts
27+
// ...
28+
JwtModule.forRoot({
29+
config: {
30+
// ...
31+
tokenGetter: (request) => {
32+
if (request.url.includes("foo")) {
33+
return localStorage.getItem("access_token_foo");
34+
}
35+
36+
return localStorage.getItem("access_token");
37+
},
38+
},
39+
});
40+
```
41+
42+
#### `allowedDomains: array`
43+
44+
Authenticated requests should only be sent to domains you know and trust. Many applications make requests to APIs from multiple domains, some of which are not controlled by the developer. Since there is no way to know what the API being called will do with the information contained in the request, it is best to not send the user's token to all APIs in a blind fashion.
45+
46+
List any domains you wish to allow authenticated requests to be sent to by specifying them in the `allowedDomains` array. **Note that standard http port 80 and https port 443 requests don't require a port to be specified. A port is only required in the allowed domains host name if you are authenticating against a non-standard port e.g. localhost:3001**
47+
48+
```ts
49+
// ...
50+
JwtModule.forRoot({
51+
config: {
52+
// ...
53+
allowedDomains: ["localhost:3001", "foo.com", "bar.com"],
54+
},
55+
});
56+
```
57+
58+
#### `disallowedRoutes: array`
59+
60+
If you do not want to replace the authorization headers for specific routes, list them here. This can be useful if your
61+
initial auth route(s) are on an allowed domain and take basic auth headers. These routes need to be prefixed with the correct protocol (`http://`, `https://`). If you want to add a route to the list of disallowed routes regardless of the protocol, you can prefix it with `//`.
62+
63+
```ts
64+
// ...
65+
JwtModule.forRoot({
66+
config: {
67+
// ...
68+
disallowedRoutes: [
69+
"http://localhost:3001/auth/",
70+
"https://foo.com/bar/",
71+
"//foo.com/bar/baz",
72+
/localhost:3001\/foo\/far.*/,
73+
], // strings and regular expressions
74+
},
75+
});
76+
```
77+
78+
**Note:** If requests are sent to the same domain that is serving your Angular application, you do not need to add that domain to the `allowedDomains` array. However, this is only the case if you don't specify the domain in the `Http` request.
79+
80+
For example, the following request assumes that the domain is the same as the one serving your app. It doesn't need to be allowed in this case.
81+
82+
```ts
83+
this.http.get('/api/things')
84+
.subscribe(...)
85+
```
86+
87+
However, if you are serving your API at the same domain as that which is serving your Angular app **and** you are specifying that domain in `Http` requests, then it **does** need to be explicitely allowed.
88+
89+
```ts
90+
// Both the Angular app and the API are served at
91+
// localhost:4200 but because that domain is specified
92+
// in the request, it must be allowed
93+
this.http.get('http://localhost:4200/api/things')
94+
.subscribe(...)
95+
```
96+
97+
#### `headerName: string`
98+
99+
The default header name is `Authorization`. This can be changed by specifying a custom `headerName` which is to be a string value.
100+
101+
```ts
102+
// ...
103+
JwtModule.forRoot({
104+
config: {
105+
// ...
106+
headerName: "Your Header Name",
107+
},
108+
});
109+
```
110+
111+
#### `authScheme: string | function(HttpRequest): string`
112+
113+
The default authorization scheme is `Bearer` followed by a single space. This can be changed by specifying a custom `authScheme`. You can pass a string which will prefix the token for each request.
114+
115+
```ts
116+
// ...
117+
JwtModule.forRoot({
118+
config: {
119+
// ...
120+
authScheme: "Basic ",
121+
},
122+
});
123+
```
124+
125+
If you want to change the auth scheme dynamically, or based on the request, you can configure a getter function which returns a string.
126+
127+
```ts
128+
// ...
129+
JwtModule.forRoot({
130+
config: {
131+
// ...
132+
authScheme: (request) => {
133+
if (request.url.includes("foo")) {
134+
return "Basic ";
135+
}
136+
137+
return "Bearer ";
138+
},
139+
},
140+
});
141+
```
142+
143+
#### `throwNoTokenError: boolean`
144+
145+
Setting `throwNoTokenError` to `true` will result in an error being thrown if a token cannot be retrieved with the `tokenGetter` function. Defaults to `false`.
146+
147+
```ts
148+
// ...
149+
JwtModule.forRoot({
150+
config: {
151+
// ...
152+
throwNoTokenError: true,
153+
},
154+
});
155+
```
156+
157+
#### `skipWhenExpired: boolean`
158+
159+
By default, the user's JWT will be sent in `HttpClient` requests even if it is expired. You may choose to not allow the token to be sent if it is expired by setting `skipWhenExpired` to true.
160+
161+
```ts
162+
// ...
163+
JwtModule.forRoot({
164+
config: {
165+
// ...
166+
skipWhenExpired: true,
167+
},
168+
});
169+
```
170+
171+
### `JwtHelperService`
172+
173+
This service contains helper functions:
174+
175+
#### isTokenExpired (old tokenNotExpired function)
176+
177+
```ts
178+
import { JwtHelperService } from '@auth0/angular-jwt';
179+
// ...
180+
constructor(public jwtHelper: JwtHelperService) {}
181+
182+
ngOnInit() {
183+
console.log(this.jwtHelper.isTokenExpired()); // true or false
184+
}
185+
```
186+
187+
#### getTokenExpirationDate
188+
189+
```ts
190+
import { JwtHelperService } from '@auth0/angular-jwt';
191+
// ...
192+
constructor(public jwtHelper: JwtHelperService) {}
193+
194+
ngOnInit() {
195+
console.log(this.jwtHelper.getTokenExpirationDate()); // date
196+
}
197+
```
198+
199+
#### decodeToken
200+
201+
```ts
202+
import { JwtHelperService } from '@auth0/angular-jwt';
203+
// ...
204+
constructor(public jwtHelper: JwtHelperService) {}
205+
206+
ngOnInit() {
207+
console.log(this.jwtHelper.decodeToken(token)); // token
208+
}
209+
```

EXAMPLES.md

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# Examples using angular2-jwt
2+
3+
- [Using a Custom Options Factory Function](#using-a-custom-options-factory-function)
4+
- [Configuration for Ionic 2+](#configuration-for-ionic-2)
5+
6+
## Using a Custom Options Factory Function
7+
8+
In some cases, you may need to provide a custom factory function to properly handle your configuration options. This is the case if your `tokenGetter` function relies on a service or if you are using an asynchronous storage mechanism (like Ionic's `Storage`).
9+
10+
Import the `JWT_OPTIONS` `InjectionToken` so that you can instruct it to use your custom factory function.
11+
12+
Create a factory function and specify the options as you normally would if you were using `JwtModule.forRoot` directly. If you need to use a service in the function, list it as a parameter in the function and pass it in the `deps` array when you provide the function.
13+
14+
```ts
15+
import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt';
16+
import { TokenService } from './app.tokenservice';
17+
18+
// ...
19+
20+
export function jwtOptionsFactory(tokenService) {
21+
return {
22+
tokenGetter: () => {
23+
return tokenService.getAsyncToken();
24+
},
25+
allowedDomains: ["example.com"]
26+
}
27+
}
28+
29+
// ...
30+
31+
@NgModule({
32+
// ...
33+
imports: [
34+
JwtModule.forRoot({
35+
jwtOptionsProvider: {
36+
provide: JWT_OPTIONS,
37+
useFactory: jwtOptionsFactory,
38+
deps: [TokenService]
39+
}
40+
})
41+
],
42+
providers: [TokenService]
43+
})
44+
```
45+
46+
**Note:**: If a `jwtOptionsFactory` is defined, then `config` is ignored. _Both configuration alternatives can't be defined at the same time_.
47+
48+
## Configuration for Ionic 2+
49+
50+
The custom factory function approach described above can be used to get a token asynchronously with Ionic's `Storage`.
51+
52+
```ts
53+
import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt';
54+
import { Storage } from '@ionic/storage';
55+
56+
export function jwtOptionsFactory(storage) {
57+
return {
58+
tokenGetter: () => {
59+
return storage.get('access_token');
60+
},
61+
allowedDomains: ["example.com"]
62+
}
63+
}
64+
65+
// ...
66+
67+
@NgModule({
68+
// ...
69+
imports: [
70+
JwtModule.forRoot({
71+
jwtOptionsProvider: {
72+
provide: JWT_OPTIONS,
73+
useFactory: jwtOptionsFactory,
74+
deps: [Storage]
75+
}
76+
})
77+
]
78+
})
79+
```
80+
81+
**Note:**: If a `jwtOptionsFactory` is defined, then `config` is ignored. _Both configuration alternatives can't be defined at the same time_.

0 commit comments

Comments
 (0)