#JwtHelperService implement problem

53 messages · Page 1 of 1 (latest)

fervent sky
#

I am trying to implement this to use my authguard.

//authservice
  constructor(private http: HttpClient, public jwtHelper: JwtHelperService) {}
 public isAuthenticated(): boolean {
    const token = localStorage.getItem('token');
    console.log(token);
    // controleer of er een token aanwezig is
    if (!token) {
      return false;
    }
    // controleer of de token is verlopen
    return !this.jwtHelper.isTokenExpired(token);
  }

}```
```ts
//my guard
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    if (!this.authService.isAuthenticated()) {
      this.router.navigate(['loginpage']);
    }
    return true;
  }
}

The error is only seen in the console. But i dont know how to handle this.

I do know it has something to do with jwthelperservice

rancid stone
#

You have to provide your jwtHelperService. So in your JwtHelperService you can say

@Injectable({providedIn: 'root'})
fervent sky
#

wait whut?

rancid stone
#

Well the error says there is no provider for the service 'JwtHelperService' .
So my first guess would be that you forgot to provide it somewhere?
You can add it in your app.module to the providers: [...] but would be to add it to your JwtHelperService self.

fervent sky
#

But jwthelperservice is a library its not something i created myself so if you say add it to your

rancid stone
#

Every service in angular has to be provided somewhere, most of them will just be providedIn: 'root', which means there will be one instance on root level

fervent sky
#

i dont understand what you mean, should i add it to the library

rancid stone
#

Aha okay I see

fervent sky
#

i provided it in app module but it does not change

rancid stone
#

it's from auth0/angular2-jwt ?

fervent sky
#

yes

rancid stone
#

In your app.module you have JwtModule.forRoot() ?

fervent sky
#

i thougt i just needed to provide it

#

let me try

#

like this?

rancid stone
rancid stone
#

And like the documentation says, don't forget to add HttpClientModule to your imports as well

deft venture
#

Yeah I guess you want a tokenGetter at the very least.

fervent sky
#

what can i put in disallowedroutes

#

just **?

deft venture
#

What's the reason you need this library, if I may ask ?

fervent sky
#

Well i am trying to make it so i get routed to loginpage when not logged in

deft venture
fervent sky
#

disallowedroutes not really nessasary
what is IDP?

deft venture
#

Identity Provider

fervent sky
#

JWT

#

token

deft venture
#

I mean, who gives you that JWT?

fervent sky
#

passport

#

in nestjs

deft venture
#

Ok. Asking because I'm the one maintaining that library and interested in the use-case.

#

Typically I would recommend to not use passport with nestjs in that way, but use an IDP like Auth0, or any of the competitors. That way, you can use SDKs that handle all of that for you.

#

But if you are rolling your own Auth (which I highly discourage), keep in mind you are not supposed to decode Access Tokens in the client.

fervent sky
#

Well i have a whole login system setup with passport cant just change it

#

and true shouldn't decode in client

#

but cant i just say something like

 public isAuthenticated(): boolean {
    const token = localStorage.getItem('token');
    console.log(token);
    // controleer of er een token aanwezig is
    if (!token) {
      return false;
    }
    // controleer of de token is verlopen
    return !this.jwtHelper.isTokenExpired(token);
  }
}```
if they do not have 'token'
go to login page
deft venture
#

You can.

fervent sky
#

well for the moment, i cant really log in anymore?

#

after i imported

deft venture
#

How did u import it ?

#

AuthGuard is not from angular2-jwt tho.

fervent sky
#
const routes: Routes = [
  { path: 'loginpage', component: LoginComponent },
  { path: 'registerpage', component: RegisterComponent },
  {
    path: '',
    component: ShellComponent,
// here i use the guard
    canActivate: [AuthGuard],
    children: [
      { path: 'home', component: HomeComponent },
      {
        path: 'invoicing',
        component: InvoicingComponent,
        children: [
          {
            path: 'purchase',
            component: PurchaseComponent,
          },```
and here ```ts
export function TokenGetter() {
  return localStorage.getItem('token');
}
@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    JwtModule.forRoot({
      config: {
        tokenGetter: TokenGetter,
        allowedDomains: ['loginpage'],
        disallowedRoutes: ['**'],
      },
    }),
    MytoastComponent,```
tokengetter
deft venture
#

Where is AuthGuard?

#

As the error is about that, not about our library.

fervent sky
#
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  Router,
  RouterStateSnapshot,
} from '@angular/router';
import { AuthService } from '@codex-ui/register';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    if (!this.authService.isAuthenticated()) {
      this.router.navigate(['loginpage']);
    }
    return true;
  }
}```
deft venture
#

@Injectable({providedIn: 'root'})

fervent sky
#

Well i guess it works now

#

i cant acces any page whitout logging in thats good

#

thank you Frederik, i can close this post now.