【问题标题】:ASP.NET MVC - Refresh Auth Cookie on Anonymous Ajax RequestsASP.NET MVC - 在匿名 Ajax 请求上刷新 Auth Cookie
【发布时间】:2020-12-28 07:12:39
【问题描述】:

我正在尝试在向具有[AllowAnonymous] 属性的控制器发出 ajax 请求后刷新会话。由于某些原因,现在不可能删除此属性。正在通过 OWIN (Microsoft.Owin v4.1.0) 进行身份验证。

以下是身份验证的方式:

public class Startup_Auth
{
    public void Configuration(IAppBuilder app)
    {
        try
        {
            MyAuthenticationProvider provider = new MyAuthenticationProvider() { OnValidateIdentity = MyValidation };
            app.SetDefaultSignInAsAuthenticationType("ExternalCookie");
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ExternalCookie",
                AuthenticationMode = AuthenticationMode.Active,
                CookieName = "MyCookie",
                CookieSecure = CookieSecureOption.Always,
                LoginPath = new PathString(PATH),
                ExpireTimeSpan = TimeSpan.FromMinutes(EXPIRATION),
                Provider = provider,
                TicketDataFormat = new MyTicketDataFormat()
            });
        }
        ...
    }

    private static Task MyValidation(CookieValidateIdentityContext context)
    {
        ...
    }
}

控制器的OnActionExecuting我也试过了:

[AllowAnonymous]
public class MyController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // can't access cookies here
    }
}

欢迎提出任何建议。

【问题讨论】:

    标签: c# asp.net-mvc authentication cookies owin


    【解决方案1】:

    您需要创建一个声明身份并在 AuthenticationManager (SignInManager.SignInAsync) 上调用 SignIn,这样声明就会更新:

    // Get User and a claims-based identity
    ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
    var Identity = new ClaimsIdentity(User.Identity);
    
    // Remove existing claim and replace with a new value
    await UserManager.RemoveClaimAsync(user.Id, Identity.FindFirst("AccountNo"));
    await UserManager.AddClaimAsync(user.Id, new Claim("AccountNo", value));
    
    // Re-Signin User to reflect the change in the Identity cookie
    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
    
    // [optional] remove claims from claims table dbo.AspNetUserClaims, if not needed
    var userClaims = UserManager.GetClaims(user.Id);
    if (userClaims.Any())
    {
        foreach (var item in userClaims)
        {
            UserManager.RemoveClaim(user.Id, item);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 2011-08-26
      • 1970-01-01
      • 2016-12-19
      相关资源
      最近更新 更多