JWT authentication utility for Angular & Angular Universal
npm install @ngx-auth/coreJWT authentication utility for Angular & Angular Universal





> Please support this project by simply putting a Github star. Share this library with friends on Twitter and everywhere else you can.
@ngx-auth/core is a basic JWT-based authentication utility used for logging in and out of the Angular application
and restrict unauthenticated access from accessing restricted routes.
- Getting started
- Installation - Examples - Recommended packages - Adding @ngx-auth/core to your project (SystemJS) - Route configuration
- app.module configuration
- Settings - Setting up AuthModule to use AuthStaticLoader
- SPA/Browser platform implementation
- Server platform implementation
- Usage
- License
You can install @ngx-auth/core using npm
```
npm install @ngx-auth/core --save
- [ng-seed/universal] and [fulls1z3/example-app] are officially maintained projects, showcasing common patterns and best
practices for @ngx-auth/core.
The following package(s) have no dependency for @ngx-auth/core, however may provide supplementary/shorthand functionality:
- [@ngx-config/core]: provides auth settings from the application settings loaded during application initialization
Add map for @ngx-auth/core in your systemjs.config
`javascript`
'@ngx-auth/core': 'node_modules/@ngx-auth/core/bundles/core.umd.min.js'
Import AuthGuard using the mapping '@ngx-auth/core' and append canActivate: [AuthGuard] or canActivateChild: [AuthGuard]
properties to the route definitions at app.routes (_considering the app.routes is the route definitions in Angular application_).
#### app.routes.ts
`TypeScript`
...
import { AuthGuard } from '@ngx-auth/core';
...
export const routes: Routes = [
{
path: '',
children: [
{
path: 'home',
component: HomeComponent
},
{
path: 'account',
children: [
{
path: 'profile',
component: ProfileComponent
},
{
path: 'change-password',
component: ChangePasswordComponent
}
],
canActivateChild: [AuthGuard]
},
{
path: 'purchases',
component: PurchasesComponent,
canActivate: [AuthGuard]
},
{
path: 'login',
component: LoginComponent
}
]
},
...
];
Import AuthModule using the mapping '@ngx-auth/core' and append AuthModule.forRoot({...}) within the imports property
of app.module (_considering the app.module is the core module in Angular application_).
You can call the [forRoot] static method using AuthStaticLoader. By default, it is configured to have no settings.
> You can customize this behavior (_and ofc other settings_) by supplying auth settings to AuthStaticLoader.
The following examples show the use of an exported function (_instead of an inline function_) for [AoT compilation].
`TypeScript
...
import { AuthModule, AuthLoader, AuthStaticLoader } from '@ngx-auth/core';
...
export function authFactory(): AuthLoader {
return new AuthStaticLoader({
backend: {
endpoint: '/api/authenticate',
params: []
},
storage: localStorage,
storageKey: 'currentUser',
loginRoute: ['login'],
defaultUrl: ''
});
}
@NgModule({
declarations: [
AppComponent,
...
],
...
imports: [
AuthModule.forRoot({
provide: AuthLoader,
useFactory: (authFactory)
}),
...
],
...
bootstrap: [AppComponent]
})
`
AuthStaticLoader has one parameter:
- providedSettings: AuthSettings : auth settingsBackend
- backend: : auth backend (_by default, using the endpoint '/api/authenticate'_)any
- storage: : storage (_by default, localStorage_)string
- storageKey: : storage key (_by default, 'currentUser'_)Array
- loginRoute: : login route, used to redirect guarded routes (_by default, ['login']_)string
- defaultUrl: : default URL, used as a fallback route after successful authentication (_by default, ''_)
> :+1: On it! @ngx-auth/core is now ready to perform JWT-based authentication regarding the configuration above.
Note: If your Angular application is performing server-side rendering (_Angular Universal_), then you should
follow the steps explained below.
- Remove the implementation from app.module (_considering the app.module is the core module in Angular application_).
- Import AuthModule using the mapping '@ngx-auth/core' and append AuthModule.forRoot({...}) within the imports property
of app.browser.module (_considering the app.browser.module is the browser module in Angular Universal application_).
#### app.browser.module.ts
`TypeScript
...
import { AuthModule, AuthLoader, AuthStaticLoader } from '@ngx-auth/core';
...
export function authFactory(): AuthLoader {
return new AuthStaticLoader({
backend: {
endpoint: '/api/authenticate',
params: []
},
storage: localStorage,
storageKey: 'currentUser',
loginRoute: ['login'],
defaultUrl: ''
});
}
@NgModule({
declarations: [
AppComponent,
...
],
...
imports: [
AuthModule.forRoot({
provide: AuthLoader,
useFactory: (authFactory)
}),
...
],
...
bootstrap: [AppComponent]
})
`
- Import AuthModule using the mapping '@ngx-auth/core' and append AuthModule.forServer() within the imports property
of app.server.module (_considering the app.server.module is the server module in Angular Universal application_).
#### app.server.module.ts
`TypeScript
...
import { AuthModule } from '@ngx-auth/core';
...
@NgModule({
declarations: [
AppComponent,
...
],
...
imports: [
AuthModule.forServer(),
...
],
...
bootstrap: [AppComponent]
})
`
AuthService has the authenticate and invalidate methods:
The authenticate method posts the credentials to the API (_configured at the AuthLoader_) using the parameters usernamepassword
and , and checks the response for a JWT token. If successful, then the authentication response is addedstorage
to the (_configured at the AuthLoader_) and the token property of AuthService is set.
That token might be used by other services in the application to set the authorization header of http requests made to secure endpoints.
As the name says, the invalidate method clears the JWT token, flushes the authentication response from the storage,login
and redirects to the page.
The following example shows how to log in and out of the Angular application.
#### login.component.ts
`TypeScript
...
import { AuthService } from '@ngx-auth/core';
@Component({
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent {
...
username: string;
password: string;
constructor(private readonly auth: AuthService) {
...
}
login(): void {
this.auth.authenticate(this.username, this.password)
.subscribe(() => {
if (!this.auth.isAuthenticated)
// display warning
});
}
logout(): void {
this.auth.invalidate();
}
}
``
The MIT License (MIT)
Copyright (c) 2019 [Burak Tasci]
[ng-seed/universal]: https://github.com/ng-seed/universal
[fulls1z3/example-app]: https://github.com/fulls1z3/example-app
[@ngx-config/core]: https://github.com/fulls1z3/ngx-config/tree/master/packages/@ngx-config/core
[forroot]: https://angular.io/docs/ts/latest/guide/ngmodule.html#!#core-for-root
[aot compilation]: https://angular.io/docs/ts/latest/cookbook/aot-compiler.html
[burak tasci]: https://github.com/fulls1z3