skip to Main Content

I have a HTTP only cookie Auth Method;
server:

export const checkCookie = async (req: Request, res: Response) => {
  const token = req.cookies["token"];
  if (!token) {
    return res.status(401).json({ message: "Unauthorized" });
  }
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    res.status(200).json({ success: true, userId: decoded.id });
  } catch (error) {
    res.status(401).json({ message: "Unauthorized" });
  }
};

the route for this API call is:
GET localhost:8000/api/v1/login

and router guard in Angular:

import { CanActivateFn } from '@angular/router';
import axios from 'axios';

export const loginAuthGuard: CanActivateFn = (route, state) => {
  return true;
};

How to send a request from this quard to this endpoint to check this Http only cookin using CanActivateFn that is modern and automaticly generated?

2

Answers


  1. I think the best choise for you is resolver

    Just keep in mind, that resolvers called after guards, so if you decided not only use resolver but the guard too, you will need to handle that problem manually.

    Login or Signup to reply.
  2. Its no possible to inject HttpClient directly into the loginAuthGuard, It would have been much cleaner. but you can use AuthService that will perform the http request an return true if succesfull, and easily inject it with inject(…).

    Just played with this example in the docs:

    class AuthService {
      constructor(private http: HttpClient) {}
    
      checkLoginStatus(): Observable<boolean> {
        //return true if http is successfull.
        );
      }
    }
    
    export const loginAuthGuard: CanActivateFn = (
      route: ActivatedRouteSnapshot,
      state: RouterStateSnapshot
    ) => {
      return inject(AuthService).checkLoginStatus();
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search