gpt4 book ai didi

asp.net-mvc-5 - XsrfKey 的用途是什么?我应该将 XsrfId 设置为其他值吗?

转载 作者:太空宇宙 更新时间:2023-11-03 14:55:21 25 4
gpt4 key购买 nike

在我的 MVC 5 网络应用程序中,我有这个(在 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方法 LinkLoginLinkLoginCallback :

    //
// 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 等)链接的方法。流程是这样的:

  1. 用户点击“链接帐户”按钮,调用 POST 到 LinkLogin方法。
  2. LinkLogin返回 ChallengeResult对象,回调 url 设置为 LinkLoginCallback方法。
  3. ChallengeResult.ExecuteResult由 MVC 框架调用,调用 IAuthenticationManager.Challenge ,这会导致重定向到特定的外部登录提供程序(比方说:google)。
  4. 用户通过 google 进行身份验证,然后 google 重定向到回调 url。
  5. 回调由 LinkLoginCallback 处理.在这里,我们要防止 XSRF 并验证调用是由用户从我们服务器提供的页面(而不是某些恶意站点)发起的。

通常,如果它是一个简单的 GET-POST 序列,您会添加一个隐藏的 <input>带有防伪 token 的字段并将其与相应的 cookie 值进行比较(这就是 Asp.Net Anti-Forgery Tokens 的工作方式)。

此处,请求来自外部身份验证提供商(在我们的示例中为 google)。所以我们需要将防伪 token 交给谷歌,谷歌应该将其包含在回调请求中。这正是state parameter在 OAuth2 中专为。

回到我们的XsrfKey :你输入的所有内容 AuthenticationProperties.Dictionary将被序列化并包含在 state 中OAuth2 请求的参数 - 因此,OAuth2 回调。现在,GetExternalLoginInfoAsync(this IAuthenticationManager manager, string xsrfKey, string expectedValue)将寻找 XsrfKey在接收状态字典中并将其与 expectedValue 进行比较.它将返回 ExternalLoginInfo仅当值相等时。

因此,回答您最初的问题:您可以设置 XsrfKey任何你想要的,只要在设置和读取时使用相同的键。将它设置为任何随机值没有多大意义 - state参数是加密的,因此没有人期望您无论如何都能读取它。

关于asp.net-mvc-5 - XsrfKey 的用途是什么?我应该将 XsrfId 设置为其他值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49606527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com