I am using angular 7 to make simple auth app. I have set token in header through asp.net wep api 2. Here is the code for this
[Route("api/AuthEmployees")]
[AcceptVerbs("POST")]
public IHttpActionResult Login(string userName, string password)
{
try
{
Employee employee = Saloon.Employees.FirstOrDefault(x => x.UserName.Equals(userName) && x.Password.Equals(password));
if (employee != null && !(bool) employee.isAuthenticated)
{
employee.isAuthenticated = true;
employee.authenticationkey = Guid.NewGuid().ToString().Replace("-", "");
HttpContext.Current.Response.Headers.Add("X-Token", employee.authenticationkey);
Saloon.SaveChanges();
employee.Password = "";
return Json(employee.authenticationkey);
}
else if(employee != null && (bool) employee.isAuthenticated)
{
employee.authenticationkey = RefreshToken(employee.authenticationkey);
HttpContext.Current.Response.Headers.Add("X-Token", employee.authenticationkey);
return Json(employee.authenticationkey);
}
else
{
return InternalServerError();
}
}
catch (Exception)
{
throw;
}
}
In my angular app I have tried "Response" class to get the header value but it returns null every time. Here is the service class for authentication
public authEmployee(userName:string,password:string) :Observable<any>
{
console.log('Auth employee service called');
return this.http.post<any>(this.API_ADDRESS + '/api/AuthEmployees',
{httpOptions:this.httpOptions} ,
{
params:
{
username: userName, password: password
}
}
);
}
where as httpOptions is
httpOptions ={ headers: new HttpHeaders({ 'Content-Type': 'application/json'})};
and Here is my component.
getAuth():void
{
this.authService.authEmployee(this.username,this.password).subscribe(
(x:Response) =>
{
console.log('Success Called')
console.log(x.headers.get('X-Token')) //Always returns null
this.callRedirect();
},
(error)=>
{
console.log('Error Called')
console.log(error)
this.callRedirect();
},
() => {
});
}
I have also tried to use observe: "response" in my httpOptions but it did not work also. Please help me to solve this problem. Thanks