[英]How to set path for authentication cookie
在 ASP.NET 6 MVC 多租戶應用程序租戶具有不同的路徑基礎,如 /tenant1 和 /tenant2。 Middlevare 從請求 url 設置 HttpContext PathBase。 SignInAsync 方法始終將身份驗證 cookie 路徑設置為 root,/
嘗試使用從 PathBase 設置身份驗證 cookie 路徑
Path = Request.PathBase.HasValue ? Request.PathBase.Value : "/"
在下面的代碼中拋出編譯錯誤,因為 AuthenticationProperties 沒有 Path 屬性。
如何設置 Cookie Path 屬性,使不同的用戶可以在不同的路徑庫中進行身份驗證?
public class AccountController : Controller {
public async Task<IActionResult> LogOn(string user, string password ) {
if (password!="secret")
throw new ApplicationException("Bad password");
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, user )
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties {
IsPersistent = true,
AllowRefresh = true,
// TODO: This throws compile error since Path property does not exist
Path = Request.PathBase.HasValue ? Request.PathBase.Value : "/"
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
}
}
您應該能夠通過編寫自己的ICookieManager並在添加 cookie 身份驗證方案時設置它來實現這一點。 ICookieManager
方法獲取HttpContext
作為輸入,因此您可以從那里訪問PathBase
。
builder.Services.AddAuthentication()
.AddCookie("Cookie", options =>
{
options.CookieManager = CustomCookieManager();
});
下面是 ICookieManager 的默認實現: ChunkingCookieManager
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.