How JWT token Works in Angular
User Login:
The user logs in with credentials (e.g., username and password).
The server verifies the credentials and responds with a JWT if authentication is successful.
Store Token:
The Angular application stores the token (e.g., in localStorage or sessionStorage).
onSubmit(){
this.service.loginUser(this.loginObj).subscribe((res:any)=>{
if(res.result){
alert("Login Sucessfully");
localStorage.setItem("loginToken",res.data.token);
this.route.navigateByUrl('/dashboard')
}else{
alert(res.message)
}
})
}
Attach Token to Requests:
An HTTP interceptor in Angular appends the JWT to outgoing requests as an Authorization header:
import { HttpInterceptorFn } from '@angular/common/http';
export const customInterceptor: HttpInterceptorFn = (req, next) => {
debugger;
const token = localStorage.getItem("loginToken");
const newReq = req.clone({
setHeaders:{
Authorization: `Bearer ${token}`
}
})
return next(newReq);
};
Server Verifies Token:
The server validates the token and grants or denies access based on its validity and claims.
Comments
Post a Comment