XsrfKey 是做什麼用的,我應該將 XsrfId 設置為其他值嗎?
在我的 MVC 5 Web 應用程序中,我有這個(在 AccountController.cs 中):
// Used for XSRF protection when adding external sign ins private const string XsrfKey = "XsrfId";和
public string SocialAccountProvider { get; set; } public string RedirectUri { get; set; } public string UserId { get; set; } public override void ExecuteResult(ControllerContext context) { var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; if (UserId != null) { properties.Dictionary[XsrfKey] = UserId; } context.HttpContext.GetOwinContext().Authentication.Challenge(properties, SocialAccountProvider); }它究竟是如何用於保護的?
我應該將 XsrfKey 的值設置為更隨機的值嗎?
看看
ManageController方法LinkLogin和LinkLoginCallback:// // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public ActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId()); } // // GET: /Manage/LinkLoginCallback public async Task<ActionResult> LinkLoginCallback() { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); if (loginInfo == null) { return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); } var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login); return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); }這些是處理外部帳戶(即 Google、Facebook 等)連結的方法。流程是這樣的:
- 使用者點擊“連結帳戶”按鈕,該按鈕呼叫 POST
LinkLogin方法。LinkLogin返回ChallengeResult對象,回調 url 設置為LinkLoginCallback方法。ChallengeResult.ExecuteResult由 MVC 框架呼叫,呼叫IAuthenticationManager.Challenge,這會導致重定向到特定的外部登錄提供程序(比方說:google)。- 使用者通過 google 進行身份驗證,然後 google 重定向到回調 url。
- 回呼叫 處理
LinkLoginCallback。在這裡,我們想要阻止 XSRF 並驗證呼叫是由使用者發起的,來自我們伺服器提供的頁面(而不是某些惡意站點)。
<input>通常,如果它是一個簡單的 GET-POST 序列,您將添加一個帶有防偽標記的隱藏欄位,並將其與相應的 cookie 值進行比較(這就是Asp.Net 防偽標記的工作方式)。在這裡,請求來自外部身份驗證提供程序(在我們的範例中為 google)。所以我們需要將防偽令牌提供給Google,Google應該將它包含在回調請求中。這正是OAuth2 中的狀態參數的設計目的。
回到我們的
XsrfKey:您輸入的所有內容都AuthenticationProperties.Dictionary將被序列化並包含在stateOAuth2 請求的參數中 - 因此,OAuth2 回調。現在,GetExternalLoginInfoAsync(this IAuthenticationManager manager, string xsrfKey, string expectedValue)將XsrfKey在接收狀態 Dictionary 中查找 並將其與expectedValue.ExternalLoginInfo僅當值相等時它才會返回。所以,回答你原來的問題:你可以設置
XsrfKey任何你想要的,只要在設置和閱讀時使用相同的鍵。將其設置為任何隨機值都沒有多大意義 -state參數是加密的,所以沒有人期望您無論如何都能讀取它。