【问题标题】:ASP.NET Identity Cookie not being saved/set in subdomainASP.NET 身份 Cookie 未在子域中保存/设置
【发布时间】:2017-07-27 05:03:05
【问题描述】:

编辑以添加额外的细节。

我有一个有效地用作授权服务器的 Web 项目(例如 example.com)。然后,我有一些网站作为子域(例如 sub1.example.com、sub2.example.com)。登录授权服务器时,我目前无法将.AspNet.Cookies cookie 保存在子域中。我可以看到 cookie 在响应中返回,但它没有被设置。

我已经搜索并尝试了各种解决方案,例如设置CookiePathCookieDomain。我已经验证了 Web.config 文件中的机器密钥在所有站点之间匹配。这就是我目前启用 Cookie 身份验证的方式:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    LoginPath = new PathString("/Account/Login"),
    CookieDomain = ".example.com",
});

我在授权服务器上启用了 CORS,并且我在登录时能够接收 Bearer 令牌,但我似乎无法保存要保存的 cookie。

提前致谢。

编辑:我在某处读到 ARRAffinity cookie 可能会弄乱一些东西,所以我也禁用了它。我仍然无法在子域中看到 cookie。

编辑 2: 根据 cmets 中的要求添加 ajax 调用(密码和域已更改以与帖子保持一致):

$.ajax({
    url: 'https://example.com/auth/token',
    method: 'POST',
    data: {
        grant_type: 'password',
        username: 'admin@example.com',
        password: '************'
    },
    crossDomain: true
});

【问题讨论】:

  • 嗨!当你说没有设置 cookie 时,你是在说浏览器没有发送它,对吗?您尝试在CookieDomain 中设置什么值?你试过mydomain.com.mydomain.com(注意开头的点)?
  • 当我在 fiddler 中查看响应时,我可以看到从服务器返回的 cookie。但是浏览器忽略了那个 specific cookie 的 Set-Cookie 标头。我试过mydomain.com.mydomain.com,两者都没有区别。
  • 您能否提供一个代码示例来说明您是如何创建 cookie 的?
  • 我在上面的帖子中添加了代码。
  • 您执行什么类型的身份验证?您是否尝试在 CookieAuthenticationOptions 中设置 AuthenticationType ?例如AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie.

标签: c# authentication cookies asp.net-identity


【解决方案1】:

我将在这里试一试答案。

默认情况下,当进行跨站 ajax 请求时,浏览器会忽略 cookie。有关此here 的更多信息。

要允许使用 cookie,您必须在请求中将 withCredentials 设置为 true,如下所示(更多信息 here):

$.ajax({
   url: 'https://example.com/auth/token',
   method: 'POST',
   data: {
      grant_type: 'password',
      username: 'admin@example.com',
      password: '************'
   },
   crossDomain: true,
   xhrFields: {
       withCredentials: true
   }
});

我已经在本地对此进行了测试,如果您唯一需要的是通过 example.com 进行身份验证,然后在与 sub1.example.com 交互时继续使用 cookie,这应该足够了。

如果您还想使用 cookie 向example.com 发出请求,并且不希望浏览器忽略您的响应,根据this link,您应该确保example.com 也返回标头@987654331 @。

【讨论】:

  • 是的!这正是问题所在。将withCredentials 添加到请求中并在我的CorsPolicy 中设置SupportsCredentials = true 将所有内容组合在一起。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
相关资源
最近更新 更多