0

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

2 Answers 2

0
HttpContext.Current.Response.Headers.Add("X-Token", employee.authenticationkey);

your putting X-Token on server and getting Token on frontend.

 x.headers.get('Token')

But should be same :)

Sign up to request clarification or add additional context in comments.

1 Comment

I did that that too but didn't work. Let me update it.
0

Since you are using ASP.NET for back-end development, you should directly set what Headers you want to read in Angular client , It mean you have to add the following header to your Response :

Access-Control-Expose-Headers

and its value should be the name of headers that you want to read in Angular Client;

Response.Headers.Add("Access-Control-Expose-Headers", "X-Token");

Now,you can access it in Angular Client;

For More Information

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.