@auth0/angular-jwt
. If you're looking for the pre-v1.0 version of this library, it can be found in the pre-v1.0
branch and on npm as angular2-jwt
.Version v5 of this library has some breaking changes concerning the allowedDomains
and disallowedRoutes
.
@auth0/angular-jwt v5 is to be used with Angular v10+ and RxJS v6+. For Angular v6+ to v9, use @auth0/angular-jwt v4
This library provides an HttpInterceptor
which automatically attaches a JSON Web Token to HttpClient
requests.
This library does not have any functionality for (or opinion about) implementing user authentication and retrieving JWTs to begin with. Those details will vary depending on your setup, but in most cases, you will use a regular HTTP request to authenticate your users and then save their JWTs in local storage or in a cookie if successful.
Note: This library can only be used with Angular 4.3 and higher because it relies on an
HttpInterceptor
from Angular'sHttpClient
. This feature is not available on lower versions.
If you want to quickly add secure token-based authentication to your Angular projects, feel free to check Auth0's Angular SDK and free plan at auth0.com/developers |
# installation with npm
npm install @auth0/angular-jwt
# installation with yarn
yarn add @auth0/angular-jwt
This library relies on the URL interface which is not supported in IE11.To solve the IE11 compatibility, you can add a polyfill.
npm i --save url-polyfill
import 'url-polyfill';
to polyfills.ts
in your projectIf you are only interested in the JWT Decoder, and are not interested in extendedinjectable features, you can simply create an instance of the utility and use itdirectly:
import { JwtHelperService } from "@auth0/angular-jwt";
const helper = new JwtHelperService();
const decodedToken = helper.decodeToken(myRawToken);
const expirationDate = helper.getTokenExpirationDate(myRawToken);
const isExpired = helper.isTokenExpired(myRawToken);
Import the JwtModule
module and add it to your imports list. Call the forRoot
method and provide a tokenGetter
function. You must also add any domains to the allowedDomains
, that you want to make requests to by specifying an allowedDomains
array.
Be sure to import the HttpClientModule
as well.
import { JwtModule } from "@auth0/angular-jwt";
import { HttpClientModule } from "@angular/common/http";
export function tokenGetter() {
return localStorage.getItem("access_token");
}
@NgModule({
bootstrap: [AppComponent],
imports: [
// ...
HttpClientModule,
JwtModule.forRoot({
config: {
tokenGetter: tokenGetter,
allowedDomains: ["example.com"],
disallowedRoutes: ["http://example.com/examplebadroute/"],
},
}),
],
})
export class AppModule {}
Any requests sent using Angular's HttpClient
will automatically have a token attached as an Authorization
header.
import { HttpClient } from "@angular/common/http";
export class AppComponent {
constructor(public http: HttpClient) {}
ping() {
this.http.get("http://example.com/api/things").subscribe(
(data) => console.log(data),
(err) => console.log(err)
);
}
}
tokenGetter: function(HttpRequest): string
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.
// ...
JwtModule.forRoot({
config: {
// ...
tokenGetter: () => {
return localStorage.getItem("access_token");
},
},
});
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.
// ...
JwtModule.forRoot({
config: {
// ...
tokenGetter: (request) => {
if (request.url.includes("foo")) {
return localStorage.getItem("access_token_foo");
}
return localStorage.getItem("access_token");
},
},
});
allowedDomains: array
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.
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
// ...
JwtModule.forRoot({
config: {
// ...
allowedDomains: ["localhost:3001", "foo.com", "bar.com"],
},
});
disallowedRoutes: array
If you do not want to replace the authorization headers for specific routes, list them here. This can be useful if yourinitial 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 //
.
// ...
JwtModule.forRoot({
config: {
// ...
disallowedRoutes: [
"http://localhost:3001/auth/",
"https://foo.com/bar/",
"//foo.com/bar/baz",
/localhost:3001\/foo\/far.*/,
], // strings and regular expressions
},
});
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.
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.
this.http.get('/api/things')
.subscribe(...)
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.
// Both the Angular app and the API are served at
// localhost:4200 but because that domain is specified
// in the request, it must be allowed
this.http.get('http://localhost:4200/api/things')
.subscribe(...)
headerName: string
The default header name is Authorization
. This can be changed by specifying a custom headerName
which is to be a string value.
// ...
JwtModule.forRoot({
config: {
// ...
headerName: "Your Header Name",
},
});
authScheme: string | function(HttpRequest): string
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.
// ...
JwtModule.forRoot({
config: {
// ...
authScheme: "Basic ",
},
});
If you want to change the auth scheme dynamically, or based on the request, you can configure a getter function which returns a string.
// ...
JwtModule.forRoot({
config: {
// ...
authScheme: (request) => {
if (request.url.includes("foo")) {
return "Basic ";
}
return "Bearer ";
},
},
});
throwNoTokenError: boolean
Setting throwNoTokenError
to true
will result in an error being thrown if a token cannot be retrieved with the tokenGetter
function. Defaults to false
.
// ...
JwtModule.forRoot({
config: {
// ...
throwNoTokenError: true,
},
});
skipWhenExpired: boolean
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.
// ...
JwtModule.forRoot({
config: {
// ...
skipWhenExpired: true,
},
});
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
).
Import the JWT_OPTIONS
InjectionToken
so that you can instruct it to use your custom factory function.
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.
import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt';
import { TokenService } from './app.tokenservice';
// ...
export function jwtOptionsFactory(tokenService) {
return {
tokenGetter: () => {
return tokenService.getAsyncToken();
},
allowedDomains: ["example.com"]
}
}
// ...
@NgModule({
// ...
imports: [
JwtModule.forRoot({
jwtOptionsProvider: {
provide: JWT_OPTIONS,
useFactory: jwtOptionsFactory,
deps: [TokenService]
}
})
],
providers: [TokenService]
})
Note:: If a jwtOptionsFactory
is defined, then config
is ignored. Both configuration alternatives can't be defined at the same time.
The custom factory function approach described above can be used to get a token asynchronously with Ionic's Storage
.
import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt';
import { Storage } from '@ionic/storage';
export function jwtOptionsFactory(storage) {
return {
tokenGetter: () => {
return storage.get('access_token');
},
allowedDomains: ["example.com"]
}
}
// ...
@NgModule({
// ...
imports: [
JwtModule.forRoot({
jwtOptionsProvider: {
provide: JWT_OPTIONS,
useFactory: jwtOptionsFactory,
deps: [Storage]
}
})
]
})
Note:: If a jwtOptionsFactory
is defined, then config
is ignored. Both configuration alternatives can't be defined at the same time.
JwtHelperService: service
This service contains helper functions:
import { JwtHelperService } from '@auth0/angular-jwt';
// ...
constructor(public jwtHelper: JwtHelperService) {}
ngOnInit() {
console.log(this.jwtHelper.isTokenExpired()); // true or false
}
import { JwtHelperService } from '@auth0/angular-jwt';
// ...
constructor(public jwtHelper: JwtHelperService) {}
ngOnInit() {
console.log(this.jwtHelper.getTokenExpirationDate()); // date
}
import { JwtHelperService } from '@auth0/angular-jwt';
// ...
constructor(public jwtHelper: JwtHelperService) {}
ngOnInit() {
console.log(this.jwtHelper.decodeToken(token)); // token
}
Auth0 helps you to:
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 details the procedure for disclosing security issues.
This project is licensed under the MIT license. See the LICENSE file for more info.
问题内容: 我正在使用angular2和gulp开发一个节点应用程序。我编写了一个组件文件login.ts,如下所示: 我的bootstrap.ts文件是: 但是当我编译这些文件时,出现以下错误: 这是我的tsconfig.json: 我已经使用以下命令安装了angular2的类型: 请帮助纠正错误。 问题答案: @simon错误说的是输入错误。但是对于其他进口商品,我已经发布了此答案,可能对其他
Angular2 (Beta) -> Angular4 开发语言:ECMAScript6 的标准已经完成。浏览器可以支持模块、类、lambda 表达式、generator 等新特性。 开发模式:Web组件将很快实现。 移动化:针对移动优化,如:缓存预编译、触控支持。 ES6工具链 Angular2是面向未来的技术,浏览器需要支持ES6+,由于目前浏览器尚未实现ES6,需要使用垫片。 angular
jackblog-angular2 Jackblog 是使用 Node.js + MongoDB + 其它客户端框架开发的个人博客系统,前后端分离,仿简书模板. 服务端有: express 版 , koa 版 客户端有: angular1.x 版 , angular2.x 版 , react 版 , vue 版 移动端有: react native 版, ionic2.0 版 此为客户端angul
angular2-cookie DEPRECATED => ngx-cookie This library is deprecated and please use ngx-cookie instead. Implementation of Angular 1.x $cookies service to Angular 2 v1.2.6 Please use >=1.2.4 for Angular
angular 2+ Spring Boot Integration This example shows how to do a paginated table with Angular and Spring Boot (RestController ) Installation The Back End You'll need Maven 3+ and Java 8 The Front End
Angular2 Tutorial This repository is an example application for angular2 tutorial. Demo Ahead-of-time compilation Lazy Loading Preloading CSS in JS by using Aphrodite Hot module reload Getting Started