Angular JWT Authentication module
yarn add @ngsm/auth
or npm i @ngsm/auth --save
app.module.ts
import { AuthInterceptor, ErrorInterceptor } from '@ngsm/auth';
@NgModule({
...,
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
],
};
app-routing.module.ts
import { AuthGuard, AuthGuestGuard } from '@ngsm/auth';
...
{
path: 'sign-in',
canActivate: [AuthGuestGuard],
loadChildren: () => import('./+sign-in/sign-in.module').then(m => m.SignInModule),
}
...
{
path: 'homepage',
canActivate: [AuthGuard],
component: HoemapgeComponent,
}
Example how to use auth service (based on @ngsm/query module):
import { AuthService } from '@ngsm/auth';
...
export class ExampleComponent implements ngOnInit {
signInQuery$ = this.authFacade.signInQuery$;
get user(): User {
return this.authService.user;
}
constructor(
private authService: AuthService,
private authFacade: AuthFacade,
) {}
ngOnInit() {
this.login();
}
logout(): void {
this.authService.logout();
}
login(): void {
this.signInQuery$
.pipe(filter(query => hasQuerySucceeded(query)))
.subscribe(({ response }) => this.authService.loginSuccess(response));
}
...
}
Sebastian Musiał |