【问题标题】:How to set cookie path for AntiforgeryToken in case of asp.net mvc application?在 asp.net mvc 应用程序的情况下,如何为 AntiforgeryToken 设置 cookie 路径?
【发布时间】:2019-12-10 07:17:23
【问题描述】:

谁能帮我知道如何为 asp.net mvc4 应用程序设置 AntiforgeryToken cookie 路径?

我关注了 MSDN 文章:https://docs.microsoft.com/en-us/aspnet/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages

但其中没有提及如何设置 cookie 路径。

在这种情况下,任何代码示例都会有所帮助。

【问题讨论】:

标签: c# asp.net-mvc-4


【解决方案1】:

在我的应用程序 startup.cs 中,我可以如下设置我的 cookie 路径,这可能会对您有所帮助。

public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Home"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            },
            CookieDomain = "",
            CookieName = "cookieName",
            CookiePath = "/"


        });            
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

        // Uncomment the following lines to enable logging in with third party login providers
        //app.UseMicrosoftAccountAuthentication(
        //    clientId: "",
        //    clientSecret: "");

        //app.UseTwitterAuthentication(
        //   consumerKey: "",
        //   consumerSecret: "");

        //app.UseFacebookAuthentication(
        //   appId: "",
        //   appSecret: "");

        //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        //{
        //    ClientId = "",
        //    ClientSecret = ""
        //});
    }

【讨论】:

  • 上面的代码 sn-p 是关于作为身份验证过程的一部分生成的 cookie。而在我的情况下,我正在尝试为作为 Antiforgerytoken 的一部分生成的 cookie 设置路径。
【解决方案2】:

可以通过封装配置cookie路径。

public static class AntiForgeryTokenExtensions
{
    ///<summary>
    ///Generates a hidden form field (anti-forgery token) that is 
    ///validated when the form is submitted. Furthermore, this extension 
    ///applies custom settings on the generated cookie. 
    ///</summary>
    ///<returns>Generated form field (anti-forgery token).</returns>
    public static MvcHtmlString AntiForgeryTokenExtension(this HtmlHelper html)
    {
        // Call base AntiForgeryToken and save its output to return later.
        var output = html.AntiForgeryToken();
        
        // Check that cookie exists
        if(HttpContext.Current.Response.Cookies.AllKeys.Contains(AntiForgeryConfig.CookieName))
        {
            // Set cookie into the variable
            var antiForgeryTokenCookie = HttpContext.Current.Response.Cookies.Get(AntiForgeryConfig.CookieName);
            
            // Set cookie configuration
            antiForgeryTokenCookie.Path = "/Path";
            // antiForgeryTokenCookie.HttpOnly = true;
            // ...
        }
        
        return output;
    }
}

如果需要更多详细信息,请在我的 this question 帖子中进行更深入的解释。

来源

How to set the AntiForgeryToken cookie path

【讨论】:

    猜你喜欢
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    相关资源
    最近更新 更多