3.0.0 • Published 2 months ago

@badisi/ngx-auth v3.0.0

Weekly downloads
-
License
GPL-3.0-only
Repository
github
Last release
2 months ago

ngx-auth

Authentication and authorization support for angular based client applications.

The sources for this package are in the main ngx-auth repo.

License: GPL-3.0

Getting started

  1. Run yarn add @badisi/ngx-auth json-object-mapper to install the library.

  2. Import the AuthModule in your AppModule:

    import { AuthModule, AuthService } from '@badisi/ngx-auth/core';
    
    export function authServiceInitializerFactory(authService: AuthService): () => Promise<any> {
        return () => authService.init();
    });
    
    @NgModule({
        imports: [
            AuthModule.forRoot({
                serviceClass: AuthService,
                initializerFactory: authServiceInitializerFactory
            })
        ]
    })
    export class AppModule { }
  3. Choose an AuthService implementation:

    OIDCAuthService

    This implementation provides OpenID Connect (OIDC) and OAuth2 protocol support.

    It mainly relies on the oidc-client-js library as it is a Certified OpenID Connect Implementation.

    1. Run yarn add oidc-client to install the dependency.

    2. Specify the OIDCAuthService implementation and initialize it:

      import { OIDCAuthService } from '@badisi/ngx-auth/oidc';
      
      export function authServiceInitializerFactory(authService: OIDCAuthService): () => Promise<any> {
          return () => authService.init({
              authority: 'IDP_URL',
              client_id: 'CLIENT_ID'
          });
      });
      
      AuthModule.forRoot({
          serviceClass: OIDCAuthService,
          initializerFactory: authServiceInitializerFactory
      })
    3. Add the following to your angular.json:

      ...
      "architect": {
          "build": {
              "options": {
                  "assets": [
                      ...,
                      {
                          "glob": "**/*",
                          "input": "node_modules/@badisi/ngx-auth/oidc/assets",
                          "output": "oidc/callback"
                      }
                  ]
              }
          }
      }
    4. For DEBUGGING : you can enable log level as follow :

      import { Log } from 'oidc-client';
      
      authService.init({..., Log.DEBUG});

    Custom implementation

    Custom implementation can easily be made by simply inheriting from AuthService.

  4. Configure the AuthModule:

    The AuthModule can be configured to activate or deactivate interceptor fully or partially.

    By default the auth token will be injected to requests made to /api and 401 errors will trigger a new login process.

    If the default behavior does not suit you, you can use the following for greater ease:

    AuthModule.forRoot({
        ...
        autoLoginOn401: {true|false},
        autoInjectToken: {
            include: ['/api', '**/*.json'],
            exclude: ['**/data-*.json']
        }
        // autoInjectToken: {true|false}, /** will inject or not the token to any requests */
    })

Usage

  • An AuthGuard is available for routing

    import { AuthGuard } from '@badisi/ngx-auth/core';
    
    const routes: Routes = [{
        path: 'private',
        component: PrivateComponent,
        canLoad: [AuthGuard],
        canActivate: [AuthGuard]
    }];
  • An AuthService is available with the followings methods :

    login(redirectUrl?: string): Promise<void>
    logout(redirectUrl?: string): Promise<void>
    refresh(): Promise<void>
    isAuthenticated(): Observable<boolean>
    getUserProfile(): Observable<UserProfile>
    getUserSession(): Observable<UserSession>
    getAccessToken(): Observable<string>
    onChange(): Observable<AuthEvent>

    Example :

    import { Component, OnDestroy, OnInit } from '@angular/core';
    import { AuthService, AuthEvent, UserProfile, UserSession } from '@badisi/ngx-auth/core';
    import { Subscription } from 'rxjs';
    
    @Component()
    export class AppComponent implements OnInit, OnDestroy {
        private authSub$: Subscription;
    
        public userProfile: UserProfile;
        public userSession: UserSession;
        public accessToken: string;
        public isAuthenticated: boolean;
    
        constructor(
            private authService: AuthService
        ) { }
    
        ngOnInit() {
            // Observe authentication
            this.authSub$ = this.authService
                .onChange()
                .subscribe((event: AuthEvent) => {
                    this.isAuthenticated = event.isAuthenticated;
                    this.accessToken = event.accessToken;
                    this.userProfile = event.userProfile;
                    this.userSession = event.userSession;
                });
        }
    
        ngOnDestroy() {
            this.authSub$.unsubscribe();
        }
    
        login() {
            this.authService.login();
        }
    
        logout() {
            this.authService.logout('/');
        }
    }
  • An AuthImageComponent is available for displaying secured images

    import { AuthImageModule } from '@badisi/ngx-auth/auth-image';
    <auth-img [src]="IMAGE_URL"></auth-img>