Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement CanActivate in angular 5 using angular2-jwt?

Tags:

angular

jwt

I'm trying to implement canActivate class to control the access to urls. For loading the token I'm using these functions :

saveToken(jwt:string){
    this.jwtToken = jwt;
    localStorage.setItem('token',jwt);
    let jwtHelper = new JwtHelper();
    this.roles = jwtHelper.decodeToken(this.jwtToken).roles;
}

loadToken(){
    this.jwtToken = localStorage.getItem('token');
}

And in every function I added the headers as:

updateUser(appuser: AppUser) {
    return this.http.put('http://localhost:8080/users/' + appuser.id , appuser,{headers: new HttpHeaders({'Authorization':this.jwtToken})});
}

Now I want to control access. Does anyone know how to implement that? Without using url?

like image 433
SS_FStuck Avatar asked Aug 15 '26 20:08

SS_FStuck


1 Answers

So for implementing the canActivate, you need to make an AuthGuard.

What is AuthGuard: It ensures whether a user is authenticated to access a particular URL or not.

Here, I created a sample code so that you can get the idea for implementing guards.

I created a service. Inside it, there is one method isAuthenticated which checks for the token, if the token is available then it will return true otherwise false.

And I used that service method inside the guard.

In the routing, I put my guard which will handle whether to activate that route or not.

auth.service.ts

import { Injectable } from '@angular/core';
import { JwtHelper } from '@auth0/angular-jwt';

@Injectable()
export class AuthService {

  constructor(public jwtHelper: JwtHelper) {}

  // ...
  public isAuthenticated(): boolean {

    const token = localStorage.getItem('token');

    // Check whether the token is expired and return
    // true or false
    return !!token; (will return either true or false based on the token availability)
  }

}

auth-guard.service.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuardService implements CanActivate {

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

  canActivate(): boolean {
    if (!this.auth.isAuthenticated()) {
      this.router.navigate(['login']);
      return false;
    }
    return true;
  }

}

app.routes.ts

import { Routes, CanActivate } from '@angular/router';
import { ProfileComponent } from './profile/profile.component';
import { AuthGuardService as AuthGuard } from './auth/auth-guard.service';

export const ROUTES: Routes = [
  { path: '', component: HomeComponent },
  { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
  { path: '**', redirectTo: '' }
];

For more:

https://codecraft.tv/courses/angular/routing/router-guards/

https://ryanchenkie.com/angular-authentication-using-route-guards

like image 165
Surjeet Bhadauriya Avatar answered Aug 17 '26 17:08

Surjeet Bhadauriya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!