簡體   English   中英

ASP.Net Cookie 未保存到瀏覽器

[英]ASP.Net Cookies not being saved to the browser

我只是想保存包含安全令牌的 cookie,但它們不會保留在瀏覽器中。 這是我保存 cookie 的AuthController方法(簡化):

[AllowAnonymous]
[HttpPost("authorize")]
[ProducesResponseType((int)HttpStatusCode.OK)]
public async Task<IActionResult> AuthorizeAsync()
{
    //generating access token ommited for brevity
    SetTokenCookie(accessToken);
    return Ok(userIdentity);
}

SetTokenCookie方法:

private void SetTokenCookie(string accessToken)
    {
        var options = _jwtOptions.AccessToken;
        var cookieOptions = new CookieOptions()
        {
            HttpOnly = true,
            IsEssential = true,
            Secure = false,
            SameSite = SameSiteMode.Strict,
            Domain = options.Issuer, //http://localhost:3394 by default
            Expires = DateTime.UtcNow.AddDays(14)
        };

        Response.Cookies.Append(options.Name, accessToken, cookieOptions);
    }

現在,當我分析來自我的 Api 的響應時,我看到Set-Cookie標頭和令牌本身很好: 響應標頭 解碼令牌:

{
  "id": "70132f61-4d83-4772-9685-7a77a9204685",
  "name": "admin",
  "email": "xyz@xyz.pl",
  "role": "Administrator",
  "persist": "True",
  "nbf": 1646336045,
  "exp": 1646336945,
  "iat": 1646336045,
  "iss": "http://localhost:3394",
  "aud": [
    "blog.webgateway",
    "blog.blogging",
    "blog.comments",
    "blog.users"
  ]
}

但是當我檢查 cookie 時,什么都沒有保存。

我知道有很多與此問題相關的主題,但我已經用完了可以在網上找到的想法:

  1. 我在瀏覽器中擦除了本地主機的存儲空間
  2. 我在我的主機文件中添加了自定義條目並相應地更改了 cookie 域
  3. 我嘗試設置 cookie domain = null 或不同的路徑
  4. 我添加了 Cors 和允許的憑據、任何方法、任何標頭、任何來源
  5. 我在瀏覽器中嘗試了更多許可設置
  6. 我嘗試更改 cookie 選項( HttpOnlySecureSameSite
  7. 我從Startup.cs中刪除UseHttpsRedirection()並確保我通過HTTP連接

似乎沒有任何效果。 我正在使用 Firefox 97.0.1。 你知道我還能嘗試什么嗎?

您是否嘗試將Domain更改為localhost

根據我的測試,使用 `` 對我不起作用,然后我發現其他 cookie 顯示它們屬於域localhost ,所以我使用 localhost 代替,然后我可以看到新創建的 cookie。 我測試通過chrome中的工具調用api,所以我認為它應該類似於你的場景。

public string saveCookie() {
    var cookieOptions = new CookieOptions()
    {
        HttpOnly = true,
        IsEssential = true,
        Secure = false,
        SameSite = SameSiteMode.Strict,
        Domain = "localhost", //using https://localhost:44340/ here doesn't work
        Expires = DateTime.UtcNow.AddDays(14)
    };

    Response.Cookies.Append("testCookie", "Cookie content", cookieOptions);
    return "hello world";
}

在此處輸入圖像描述

我終於設法解決了這個問題......這是我所做的步驟:

  1. 將控制器方法更改為HttpGet ,所以現在看起來像這樣:
[AllowAnonymous]
[HttpGet("authorize")] // <-- notice the difference
[ProducesResponseType((int)HttpStatusCode.OK)]
public async Task<IActionResult> AuthorizeAsync()
{
    //generating access token ommited for brevity
    SetTokenCookie(accessToken);
    return Ok(userIdentity);
}

由於某種原因,直接從瀏覽器(至少在我的情況下是 Firefox)調用 Post 請求似乎不適用於設置 cookie,即使響應看起來不錯,但是當我將其更改為 Get 方法並以標准方式訪問時方式(URL)它的工作原理。 我將不得不仔細檢查 Post 方法是否適用於客戶端(JavaScript)。

  1. 應用 Tiny Wang 的上述解決方案,這意味着將 cookie 域更改為localhost 擁有完整的 URL 確實可以防止 cookie 被保存。

編輯:正如 SSchmid 在評論中指出的那樣,在 Firefox 中使用開發工具時,將方法更改為“Get”只是一種臨時解決方法。 對於進一步的開發或生產,不建議將其保留為“獲取”方法。

我設法通過使用[FromBody]屬性讓它運行。 這對我有用:

    [HttpPost("Login")]
    public async Task<IActionResult> Login([FromBody] LoginData data)
    {

        var user = await userManager.FindByEmailAsync(data.Email);
        if (user == null || !await userManager.CheckPasswordAsync(user, data.Password))
            return Unauthorized("Invalid Authentication");

        await signInManager.SignInAsync(user, data.rememberMe);
        var roles = (await userManager.GetRolesAsync(user)).ToList();
        var sUser = new Models.User(user, roles);
        return Ok(sUser);
    }

顯然,如果您將 HTTPPOST 與參數結合使用,則它不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM