I'm brand new in angular. I'm trying to create a auth-guard which send a post request to the backend, and validate the JWT. If JWT is valid guard should allow the access of the requested component. This is how my auth.guard.ts looks like:
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.loginService.isLoggedIn() && this.loginService.isValidateJwt() == 1) {
console.log("AuthGuard return to requestet page!")
return true;
}
else {
console.log("AuthGuard redirect to login page!")
this.router.navigate(['login']);
return false;
}
}
This is how the loginService relevant part looks like:
isLoggedIn(){
let token=localStorage.getItem("jwt");
let username=localStorage.getItem("username");
if(token==undefined || token=='' || token==null || username==undefined || username == '' || username==null){
console.log("LoginService isLoggedIn token and username NOT FOUND in local storage!");
return false;
}
else {
console.log("LoginService isLoggedIn token and username FOUND in local storage! Stat validate JWT!");
return true;
}
}
isValidateJwt() : number {
console.log("isValidateJwt invoked!")
var isvalid = 0
this.http.post(this.validate_url, new ValidateRequest(localStorage.getItem("jwt") , localStorage.getItem("username"))).subscribe(
(response:any)=>{
// success
console.log("isValidateJwt isValid: " + response.isValid);
isvalid = response.isValid;
},
error=>{
// error
console.error(error);
//window.location.href="/dashboard"
}
)
console.log("isValidateJwt returning: " + isvalid)
return isvalid;
}
This is how my backend response looks like:
{
"isValid": 1,
"message": "JWT is VALID!"
}
- I created two Item in the local storage while login process (username / jwt)
- When the user would like to access a component that is protected, the guard calls the
isLoggidInandisValidateJwtfunctions. - The
isLoggedinfunction reads the localStorage and if username and jwt exists then it returnstrue - The
isValidateJwtfunction calls the backend and validate the jwt - If the
JWTis valid, backend returns isValid = 0 in the response object and I store it to theisValidvariable inside theisValidateJwtfunction, but when the function finally returns the value ofisValidvariable will be 0 again. - I set up the backend it's always return isValid = 0
I think it is something related to variables scope, but i don't understand why my isValid variable set back to zero.
Thank you!