I am using Angular 9 and the CanAngular interface to protect a route being called when the user is not logged in. During login I set a cookie session_key
, but I don't know how I can read/get the cookie value again in the canActivate
function of the interface.
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private accountService: AccountService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (cookieExists("session_key")) { <----------------------
// authorised so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/account/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
What existing function would I use for cookieExists
?
If you are using ngx-cookie-service you need to import the Cookie Service in authguard.
import { CookieService } from 'ngx-cookie-service';
and in constructor inject the cookie service
constructor(private cookieService : CookieService){}
Then you can use the below code to access the cookie storage
if (cookieService.get("session_key")) {
return true;
}
You can set the cookie using below code
cookieService.set('session-key','some-value');
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments