Angular withCredentials未发送Cookie

Hak*_*tık 9 c# cookies asp.net-mvc httpcookie angular

我正在使用带有旧后端的Angular 8(ASP.NET MVC 5框架),而不是核心。
我正在尝试发送网站的Cookie,因此来自角度网站的请求被认为已通过身份验证

我为此创建了一个拦截器

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);
  }

}
Run Code Online (Sandbox Code Playgroud)

这是请求的代码

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);
}
Run Code Online (Sandbox Code Playgroud)

我可以确认该拦截器正在通过一条console.log语句执行,
问题是我没有在请求中收到cookie(通过Http Get not Post的方式),并且我的请求被认为是未认证的。

我正在使用以下针对CORS问题的过滤器

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);
    }
}

Run Code Online (Sandbox Code Playgroud)

我在全局注册过滤器,

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

Run Code Online (Sandbox Code Playgroud)

这是我希望在标头中发送的cookie,此代码段来自login方法

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");

Run Code Online (Sandbox Code Playgroud)

这是Chrome中的Cookie

在此处输入图片说明 如果您需要更多信息,请在评论中问我,我会提供。

更新资料

  1. 我检查了这篇文章,并把的same-site属性应用set-cookienone,但这仍然不能解决问题。

  2. 我将其更新为[AllowCrossSiteAttribute]这样,因为完全是我收到的另一个问题

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);
    }
}

Run Code Online (Sandbox Code Playgroud)
  1. OnAuthorizationBaseController中存在的方法中,该方法在每个请求上都被调用,我测试了请求的标头。
    如果我从旧的MVC应用程序中请求了某些内容,则可以正确接收Cookie 在此处输入图片说明
    但是当我从角度项目提出请求时,我根本没有收到任何Cookie

在此处输入图片说明

  1. 这是Cookie在chrome inspector中的显示方式

    用于有角度的项目 在此处输入图片说明

    对于旧的MVC项目 在此处输入图片说明

Mic*_*ely 2

它与您的 ASP.NET 后端无关,它与您在端口 4200 上运行的 Angular 开发服务器有关,而您的后端服务器在端口 27309 上运行。不同的端口http://localhost:4200http://localhost:27309不同的主机,因此浏览器不会http://localhost:27309尽管有 Angular 的标志,但仍将 cookie 附加到请求中withCredentials: true

为了解决这个问题,请按照此SO 答案中的描述设置 Angular 的代理配置(Angular 中的内置功能)。