修改CookieAuthenticationOptions登录路径OnRedirectToReturnUrl事件
本文关键字:OnRedirectToReturnUrl 事件 路径 登录 CookieAuthenticationOptions 修改 | 更新日期: 2024-09-27 05:39:54
我在MVC 6 ASP.NET 5项目中有以下设置:
配置方法中的Startup.cs:
app.UseCookieAuthentication(options =>
{
options.AuthenticationScheme = "Cookie";
options.LoginPath = new PathString("/<TENANT>/account/signin/");
options.AccessDeniedPath = new PathString("/<TENANT>/account/unauthorised/");
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.Events = new CookieAuthenticationEvents
{
OnRedirectToReturnUrl = MyClass.RedirectToReturnUrlAsync
};
});
事件类别:
public static class MyClass
{
public static async Task RedirectToReturnUrlAsync(CookieRedirectContext context)
{
context.Options.LoginPath = new PathString("/<HERE I PLAN TO PUT LOGIC TO FIGURE OUT TENANT FROM CONTEXT>/account/signin");
}
}
假设用户转到以下网址:
http://localhost/mycompany/securecontroller/secureaction
我希望Cookie中间件将用户重定向到:
http://localhost/mycompany/account/signin
问题是,当重定向到返回Url时,代码"MyClass.RRedirectToReturnUrlAsync"永远不会被命中,所以我找不到在运行时修改LoginPath的机会。
我怀疑我的设置有问题。有人遇到过这个问题吗?
Hooroo
好吧,我想我已经想通了。我从错误的角度看待这个问题(睡了一会儿之后!)
app.UseCookieAuthentication(options =>
{
options.AuthenticationScheme = "Cookie";
options.LoginPath = new PathString("/<TENANT>/account/signin/");
options.AccessDeniedPath = new PathString("/<TENANT>/account/unauthorised/");
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.Events = new MyCookieAuthenticationEvents();
});
创建自己的自定义Cookie验证事件的正确方法是从CookieAuthenticationEvents对象派生并覆盖您想要自定义的事件,类似于以下内容:
public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
{
public override Task RedirectToLogin(CookieRedirectContext context)
{
context.RedirectUri = <PUT LOGIC HERE TO REPLACE YOUR REDIRECT URI>
return base.RedirectToLogin(context);
}
}
在我之前的尝试中,我也瞄准了错误的事件。在我的案例中,要覆盖的正确方法是"RedirectToLogin"方法。
Hooroo