Git Product home page Git Product logo

ngx-auth's Introduction

Angular 7+ Authentication

This package provides authentication module with interceptor

npm install ngx-auth --save

For older versions of angular see Older Versions section.

Full example

Full example you can find in this repo serhiisol/ngx-auth-example

Authentication module

Authentication modules provides ability to attach authentication token automatically to the headers (through http interceptors), refresh token functionality, guards for protected or public pages and more.

Usage

  1. Import AuthService interface to implement it with your custom Authentication service, e.g.:
import { AuthService } from 'ngx-auth';

@Injectable()
export class AuthenticationService implements AuthService {

  private interruptedUrl: string;

  constructor(private http: Http) {}

  public isAuthorized(): Observable<boolean> {
    const isAuthorized: boolean = !!sessionStorage.getItem('accessToken');

    return Observable.of(isAuthorized);
  }

  public getAccessToken(): Observable<string> {
    const accessToken: string = sessionStorage.getItem('accessToken');

    return Observable.of(accessToken);
  }

  public refreshToken(): Observable<any> {
    const refreshToken: string = sessionStorage.getItem('refreshToken');

    return this.http
      .post('http://localhost:3001/refresh-token', { refreshToken })
      .catch(() => this.logout())
  }

  public refreshShouldHappen(response: HttpErrorResponse): boolean {
    return response.status === 401;
  }

  public verifyRefreshToken(req: HttpRequest<any>): boolean {
    return req.url.endsWith('refresh-token');
  }

  public skipRequest(req: HttpRequest<any>): boolean {
    return req.url.endsWith('third-party-request');
  }

  public getInterruptedUrl(): string {
    return this.interruptedUrl;
  }

  public setInterruptedUrl(url: string): void {
    this.interruptedUrl = url;
  }

}
  1. Specify PublicGuard for public routes and ProtectedGuard for protected respectively, e.g.:
const publicRoutes: Routes = [
  {
    path: '',
    component: LoginComponent,
    canActivate: [ PublicGuard ]
  }
];
const protectedRoutes: Routes = [
  {
    path: '',
    component: ProtectedComponent,
    canActivate: [ ProtectedGuard ],
    children: [
      { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule' }
    ]
  }
];
  1. Create additional AuthenticationModule and provide important providers and imports, e.g.:
import { NgModule } from '@angular/core';
import { AuthModule, AUTH_SERVICE, PUBLIC_FALLBACK_PAGE_URI, PROTECTED_FALLBACK_PAGE_URI } from 'ngx-auth';

import { AuthenticationService } from './authentication.service';

@NgModule({
  imports: [ AuthModule ],
  providers: [
    { provide: PROTECTED_FALLBACK_PAGE_URI, useValue: '/' },
    { provide: PUBLIC_FALLBACK_PAGE_URI, useValue: '/login' },
    { provide: AUTH_SERVICE, useClass: AuthenticationService }
  ]
})
export class AuthenticationModule {

}

where,

  • PROTECTED_FALLBACK_PAGE_URI - main protected page to be redirected to, in case if user will reach public route, that is protected by PublicGuard and will be authenticated

  • PUBLIC_FALLBACK_PAGE_URI - main public page to be redirected to, in case if user will reach protected route, that is protected by ProtectedGuard and won't be authenticated

  • AUTH_SERVICE - Authentication service token providers

  1. Provide your AuthenticationModule in your AppModule

Customizing authentication headers

By default, requests are intercepted and a { Authorization: 'Bearer ${token}'} header is injected. To customize this behavior, implement the getHeaders method on your AuthenticationService

After login redirect to the interrupted URL

The AuthService has an optional method setInterruptedUrl which saves the URL that was requested before the user is redirected to the login page. This property can be used in order to redirect the user to the originally requested page after he logs in. E.g. in your login.component.ts (check also AuthService implementation above):

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html'
})
export class LoginComponent {

  constructor(
    private router: Router,
    private authService: AuthenticationService,
  ) { }

  public login() {
    this.authService
      .login()
      .subscribe(() =>
        this.router.navigateByUrl(this.authService.getInterruptedUrl())
      );
  }
}

Older Versions

For angular 6, use version 4.1.0

npm install [email protected] --save

For angular 5, use version 3.1.0

npm install [email protected] --save

For angular 4, use version 2.2.0

npm install [email protected] --save

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.