Authentication library to integrate jwt with Angular2 utilizing 'Authorization' header. There are several Angular2 guards and an '@angular/common/http' interceptor.
This is a Node.js module available through the
npm registry. Installation is done using the
npm install
command:
$ npm install ng-jwt-auth
Modify your main app module:
import { NgJwtAuthModule, AbstractAuthenticationConfig } from '@scomith/ng-jwt-auth';
export class AuthenticationConfig extends AbstractAuthenticationConfig {
apiLoginUrl = 'api/authenticate/endpoint';
loginRedirectUrl = '/user/login';
heartbeatUrl = '/ping';
}
@NgModule({
imports: [
BrowserModule,
HttpModule,
NgJwtAuthModule.forRoot(AuthenticationConfig),
...
]
...
})
AppModule {}
The authentication endpoint accepts ICredentials
:
import { Component } from '@angular/core';
import { ICredentials, IToken, AuthenticationService } from '@scomith/ng-jwt-auth';
// Login Component on AbstractAuthenticationConfig.loginRedirectUrl
@Component({...})
export class LoginComponent {
constructor(
private _authService: AuthenticationService
) {
public onLogin(): void {
let credentials: ICredentials = {email: '[email protected]', password: 'some-password'};
this._authService.attemptLogin(credentials)
.then((token: IToken) => {
// do something with token
},
(err: string) => {
// do something with error
});
}
public onLogout(): void {
this._authService.logout();
}
public isAuthenticated(): boolean {
return this._authService.isAuthenticated();
}
}
The API endpoint is configurable via the AbstractAuthenticationConfig in the Setup section. It should expect the following JSON request:
{
"username": "some-user",
"password": "some-password"
}
and expects the response to be in the format:
{
"token": "actual.jwt.token"
}
The heartbeat guard can be added to routes to send a ping to the API to get a refresh token.
To use the hearbeat guard you must set the heartbeatUrl
on AbstractAuthenticationConfig
in the Setup section.
Then you can add it to the routes:
const appRoutes: Routes = [
{
path: '',
component: AppComponent,
canActivate: [HearbeatGuard],
canActivateChild: [HearbeatGuard],
children: [
{
// ...
}
]
}
];