Skip to main content

JWT Authentication (ASP.NET Core + Angular) - frontend


 key code snippets are following:

guards -> auth.guard


import { Injectable } from '@angular/core';

import { ActivatedRoute, ActivatedRouteSnapshot, CanActivate, Router, RouterState, RouterStateSnapshot, UrlTree } from '@angular/router';

import { Observable } from 'rxjs';

import { AuthService } from '../services/auth.service';

@Injectable({

  providedIn: 'root'

})

export class AuthGuard implements CanActivate {

  currentAccessingURL:string;

  constructor(public auth: AuthService, public router: Router) {

  }

 

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    this.currentAccessingURL = state.url;

    let canAccess = this.auth.checkRouteAccessPermission(this.currentAccessingURL);

    

    if (!this.auth.isAuthenticated()) {

      this.router.navigateByUrl('/user-login');

      return false;

    }

    else if(!canAccess)

    {

      this.router.navigateByUrl('/unauthorized');

       return false;

    }

    else if(canAccess)

    {

      return true;

    }

    else{

      this.router.navigateByUrl('/unauthorized');

      return false;

    }

  }

}


interceptor: -> token-interceptor


import { Injectable } from '@angular/core';

import {

  HttpRequest,

  HttpHandler,

  HttpEvent,

  HttpInterceptor

} from '@angular/common/http';

import { AuthService } from '../services/auth.service';

import { Observable } from 'rxjs';


@Injectable({

  providedIn: 'root'

})

export class TokenInterceptor implements HttpInterceptor {

  constructor(public auth: AuthService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    

    request = request.clone({

      setHeaders: {

        Authorization: `Bearer ${this.auth.getToken()}`

      }

    });

    

    return next.handle(request);

  }

}

auth.service:

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

import { environment } from 'src/environments/environment';

import { User } from '../models/user.model';

import { TokenResponse } from '../models/token-response.model';

import { Permission } from '../models/permission.model';


@Injectable({

  providedIn: 'root'

})

export class AuthService {


  private baseUrl : string = environment.apiBaseUrl;

  private routePermissions:Array<Permission>;

  public currentRoutePermissionDetails:Permission;

  

  constructor(private http:HttpClient)

  {

    if(localStorage.getItem('permissions'))

    {

      this.routePermissions = JSON.parse(localStorage.getItem('permissions'));

    }

    else

    {

      this.routePermissions= new Array<Permission>();

    }

    

  }


  public getToken(): string {

    return localStorage.getItem('accessToken');

  }


  public isAuthenticated(): boolean {

    const token = this.getToken();

    

    return token? true : false;

  }


  public AuthenticateUser(userLogin:User)

  {

    return this.http.post<TokenResponse>(`${this.baseUrl}Account/Authenticate`,userLogin);

  }


  public updateRoutePermission(permissions:Array<Permission>)

  {

    if(permissions)

    {

      localStorage.setItem('permissions',JSON.stringify(permissions));

      this.routePermissions = permissions;

    }

    

  }


  public checkRouteAccessPermission(routeUrl:string):boolean

  {

    let hasAuthorization = false;

    

    if(this.routePermissions && this.routePermissions.length >0)

    {

       let permissionDetailList = this.routePermissions.filter(rp=> rp.routeURL == routeUrl);

       this.currentRoutePermissionDetails = this.selectMaxPermissionForRoute(permissionDetailList);

       hasAuthorization = true;

    }


    return hasAuthorization;

  }


  private selectMaxPermissionForRoute(permissions:Array<Permission>):Permission

  {

    let maxPermission:Permission = new Permission();


    for(let permission of permissions) 

    {

      if(permission.canDelete)

      {

        maxPermission = permission;

        break;

      }

      else if(permission.canCreate)

      {

        maxPermission = permission;

        break;

      }

      else if(permission.canUpdate)

      {

        maxPermission = permission;

        break;

      }

      else{

        maxPermission = permission;

      }

    }


    return maxPermission;

  }


}


Appmodule:

import { InjectionToken, NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { FormsModule }   from '@angular/forms';

import { ToastrModule } from 'ngx-toastr';

import { ModalModule } from 'ngx-bootstrap/modal';

import { BsDatepickerConfig, BsDatepickerModule } from 'ngx-bootstrap/datepicker';

import { TypeaheadModule  } from 'ngx-bootstrap/typeahead';


import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { HttpClientModule,HttpInterceptor,HTTP_INTERCEPTORS } from '@angular/common/http';

import { UserModule } from './user/user.module';

import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

import { UserLoginComponent } from './user-login/user-login.component';

import { CompanyModule } from './company/company.module';

import { AddModuleComponent } from './add-module/add-module.component';

import { ForgetPasswordComponent } from './forget-password/forget-password.component';

import { ResetPasswordComponent } from './reset-password/reset-password.component';

import { TokenInterceptor } from './interceptor/token-interceptor';

import { UnauthorizedComponent } from './unauthorized/unauthorized.component';

import { AuthGuard } from './guards/auth.guard';

import { NotFoundComponent } from './not-found/not-found.component';

import { ConfirmDialogComponent } from './confirm-dialog/confirm-dialog.component';

import { InvoiceComponent } from './reports/invoice/invoice.component';

import { CurrencyPipe, DatePipe, DecimalPipe } from '@angular/common';

import { BsModalRef } from 'ngx-bootstrap/modal';



@NgModule({

  declarations: [

    AppComponent,

    UserLoginComponent,

    AddModuleComponent,

    ForgetPasswordComponent,

    ResetPasswordComponent,

    UnauthorizedComponent,

    NotFoundComponent,

    ConfirmDialogComponent,

    InvoiceComponent

  ],

  imports: [

    BrowserModule,

    FormsModule,

    HttpClientModule,

    BrowserAnimationsModule,

    ToastrModule.forRoot(),

    BsDatepickerModule.forRoot(),

    TypeaheadModule.forRoot(),

    ModalModule.forRoot(),

    UserModule,

    CompanyModule,

    AppRoutingModule

  ],

  entryComponents:[

    ConfirmDialogComponent,

    InvoiceComponent

  ],

  providers: [

    {

      provide: HTTP_INTERCEPTORS,

      useClass: TokenInterceptor,

      multi: true

    },

    AuthGuard,

    DatePipe,BsModalRef,CurrencyPipe,DecimalPipe,

    BsDatepickerConfig

  ],

  bootstrap: [AppComponent]

})

export class AppModule { }



routes:
const routes: Routes = [
  {path: '', component:UserLoginComponent},
  {path: 'user-login', component:UserLoginComponent},
  {path: 'add-module', component:AddModuleComponent,canActivate:[AuthGuard]},
  {path: 'forgot-password', component:ForgetPasswordComponent},
  {path: 'reset-password', component:ResetPasswordComponent,canActivate:[AuthGuard]},
  {path: 'unauthorized', component:UnauthorizedComponent},
  {path: '404', component: NotFoundComponent},
  {path: '**', redirectTo: '/404'}
];

Comments

Popular posts from this blog

update your package-lock.json according to what you have specified in the package.json file

  The objective of the   npm update   command is to update your   package-lock.json   according to what you have specified in the   package.json   file. This is the normal behavior. If you want to update your package.json file, you can use  npm-check-updates :  npm install -g npm-check-updates . You can then use these commands: ncu  Checks for updates from the package.json file ncu -u  Update the package.json file npm update --save  Update your package-lock.json file from the package.json file

Limit Upload File Type Extensions ASP.NET MVC 5

  //-----------------------------------------------------------------------    // <copyright file="AllowExtensionsAttribute.cs" company="None">    //     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.    // </copyright>    // <author>Asma Khalid</author>    //-----------------------------------------------------------------------       namespace  ImgExtLimit.Helper_Code.Common   {        using  System;        using  System.Collections.Generic;        using  System.ComponentModel.DataAnnotations;        using  System.Linq;      ...

Referenced assembly does not have a strong name

  Steps to create strong named assembly Step 1 : Run visual studio command prompt and go to directory where your DLL located.   For Example my DLL located in  D:/hiren/Test.dll Step 2 : Now create  il file using below command.    D:/hiren> ildasm /all /out=Test.il Test.dll   (this command generate code library) Step 3 : Generate new Key for sign your project.    D:/hiren> sn -k mykey.snk Step 4 : Now sign your library using ilasm command.    D:/hiren> ilasm /dll /key=mykey.snk Test.il so after this step your assembly contains strong name and signed. Jjust add reference this new assembly in your project and compile project its running now. codeproject.com/Tips/341645/Referenced-assembly-does-not-have-a-strong-name