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

Cannot access a disposed object. A common cause of this error is disposing a context that was

  Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'PropertyContext'.  public class CustomerHub : Hub     {         public readonly ICustomerService _customerService;         private readonly IServiceScopeFactory _serviceScopeFactory;         public CustomerHub(ICustomerService service, IServiceScopeFactory serviceScopeFactory)         {             _customerService = service;             _serviceScopeFactory = serviceSco...

ahara-nidra-bhaya-maithunam

आहर निद्रा भय मैथुनं च सामान्यमेतत पशुभिर्नराणाम् धर्मो हि तेषाम् अधिको विशेषो धर्मेण हीना पशुभिः समाना ahara-nidra-bhaya-maithunam ca samanyam etat pashubhih naranam dharmo hi tesham adhiko vishesho dharmena hina pashubhih samanah Hunger, sleep,fear and sexual desire are the instincts which are common between mankind and beasts (animals). .It is especially 'Dharma;' that mankind possesses additionally, and a person bereft of 'Dharma' is like a beast, “Eating, sleeping, fearing, and mating are the four principles of animal life. These are common both to animals and to human beings. But religion is the extra function of the human being. Without religion, human life is no better than animal life.” -from Mahabharata