Sunday, 22 September 2019

Angular withCredentials is not sending cookies

I am using Angular 8, with old backend (ASP.NET MVC 5 Framework) NOT CORE
I am trying to send the cookies of the website so the request from the angular website considered authenticated

I created an interceptor for this

import { HttpInterceptor, HttpHandler, HttpEvent, HttpRequest } 
from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor() { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const newRequest = request.clone({
      withCredentials: true,
    });
    return next.handle(newRequest);
  }

}

here is the code of the request

private getDefaultConfiguration(): configurationsType {
  return {
    observe: 'response',
    responseType: 'json',
    headers: new HttpHeaders().set('Content-Type', 'application/json')
  };
}

public async get(endpoint: string, params: HttpParams = undefined) {
  const options = this.getDefaultConfiguration();
  if (params !== undefined)
    options.params = params;

  const response: HttpResponse<object> = await this.http.get(endpoint, options).toPromise();
  return await this.errorCheck(response);
}

I can confirm that the interceptor is executing by a console.log statement
the problem is that I am not receiving the cookies in the request (by the way Http Get not Post) and my request is considered to be unauthenticated.

I am using the following Filter for CORS problem

public class AllowCrossSiteAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpResponseBase response = filterContext.RequestContext.HttpContext.Response;

        response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        response.AddHeader("Access-Control-Allow-Headers", "*");
        response.AddHeader("Access-Control-Allow-Methods", "*");
        response.AddHeader("Access-Control-Allow-Credentials", "true");

        base.OnActionExecuting(filterContext);
    }
}


I register the filter globally,

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new AllowCrossSiteAttribute());
    }
}


here is the cookie that I expect to be sent in the header, this snippet is from the login method

var ticket = new FormsAuthenticationTicket(SessionHelper.DefaultSession().KullaniciAdi, model.RememberMe, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted)
{
    Expires = DateTime.Now.AddMinutes(timeout),
    HttpOnly = true // cookie not available in javascript.
};

Response.Cookies.Add(cookie);

return RedirectToAction("Index", "Home");


and here is the cookie in the chrome

enter image description here if you need any more information please ask me in the comment and I will provide that.

Update

  1. I check it out this article and I applied the same-site attribute of the set-cookie to none, but this still does not solve the problem.

  2. I updated the [AllowCrossSiteAttribute] to be like this, because of completely another problem I was receiving in angular

public class AllowCrossSiteAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpResponseBase response = filterContext.RequestContext.HttpContext.Response;

        response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        response.AddHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        response.AddHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
        response.AddHeader("Access-Control-Allow-Credentials", "true");

        base.OnActionExecuting(filterContext);
    }
}


  1. In the OnAuthorization method which exists in the BaseController and which is called on each request, I tested the header of the request.
    if I requested something from the old MVC application I receive the cookies correctly enter image description here
    but when I make a request from the angular project I receive no Cookies at all

enter image description here

  1. here is how the cookies appear in chrome inspector

    for the angular project enter image description here

    and for the old MVC project enter image description here



from Angular withCredentials is not sending cookies

No comments:

Post a Comment