We need a guardian for a reason

I added a guard today to my Angular app, which looked like this.

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

@Injectable({
  providedIn: 'root'
})
export class LoginGuard implements CanActivate {
  constructor(
    private _authService: AuthService,
    private _router: Router
  ) { }

  canActivate(): boolean {
    if (this._authService.loggedIn()) {
      return true
    } else {
      this._router.navigate(['/login'])
      return false
    }
  }
}

And then I added Http Interceptor, which is below:


import { Injectable, Injector } from '@angular/core';
import { HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { AuthService } from '../_services/auth.service'

@Injectable({
  providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor  {

  constructor(private injector: Injector) { }

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    let authService = this.injector.get(AuthService)
    let tokenizedReq = req.clone({
      setHeaders: {
        Authorization: `Bearer ${authService.getToken()}`
      }
    })
    return next.handle(tokenizedReq)
  }
}

I don’t know if these apply to setting cookie to store tokens, because that’s my ultimate goal. Right now, to make everything easier, I store my jwt token in localStorage. I know this is bad practice, but most of the help I found on the Internet were focusing on this, so I want to follow along to know how it works first, and then I can make it better later, right?

I learned that with Http Interceptor, I can add custom header to my request, and I added authorization. I am not 100% sure if this is why I couldn’t add my Cookie as aforementioned, and I don’t think I’ll try it out anytime soon, but Http Interceptor is life saver.

Angular is interesting, and there are so many things to learn. Right now, I’m at the tip of the iceberg and I’m not even close to knowing it all. When I’m done with the basic functions, I’d like to edit my form to Angular form, and learn more about this frameworks to apply them in future projects. Fighting!!!

Published by Thi Le

Human.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: