c# - 编辑 Cookie 选项后身份验证不起作用
问题描述
在具有授权属性的 ajax 请求的控制器方法中。当我在未登录时发出请求时,我会重定向到登录页面。我需要未经授权的而不是登录页面数据。为了改变这一点,我重写了“OnRedirectToLogin”事件。
这是代码:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.LoginPath = "/Identity/Account/Login";
options.Events.OnRedirectToLogin = ctx => Test(ctx);
});
private Task Test(RedirectContext<CookieAuthenticationOptions> ctx)
{
if (ctx.Request.ContentType != null && ctx.Response.StatusCode == (int) HttpStatusCode.OK)
{
if (ctx.Request.ContentType.Contains("application/json"))
{
ctx.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
}
}
else
{
ctx.Response.Redirect(ctx.RedirectUri);
}
return Task.CompletedTask;
}
所有更改都有效,但是当我尝试在默认登录页面上登录时,什么也没有发生。
那里的问题是什么,或者您有更好的选择来在没有这个问题的情况下达到相同的结果吗?
谢谢你的帮助!
更新:自从帖子上线以来,我一直在寻找时间。现在我发现登录有效,但控制器上的身份验证显然不再有效。
解决方案
经过更多调查,我找到了这个解决方案:
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
options.LoginPath = "/Identity/Account/Login";
options.Events.OnRedirectToLogin = ctx =>
{
if (ctx.Request.ContentType != null && ctx.Response.StatusCode == (int) HttpStatusCode.OK)
{
if (ctx.Request.ContentType.Contains("application/json"))
{
ctx.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
}
}
else
{
ctx.Response.Redirect(ctx.RedirectUri);
}
return Task.CompletedTask;
};
});
决定性因素是仅设置“DefaultChallengeScheme”
推荐阅读
- android - 在 Fragment 中打开 ViewPager 使应用程序崩溃
- vue.js - 来自html的相同vue代码在刀片文件中不起作用
- javascript - CastError:模型“customer”的路径“_id”中的值“customers”转换为 ObjectId 失败
- python - Django模板:访问模板中的自定义表单字段属性
- sqlite - 如何将 sqllite 中的数据放入列表视图?
- python - 使用python ldap3,通过userid获取memberof
- java - 无法访问在 gcp 计算引擎中部署在 tomcat8 上的 RESTful Web 服务应用程序
- node.js - nodejs如何在单个nodejs进程的多个不同端口上运行单个tcp服务器实例
- php - 我的项目中的更新语句不更新表中的数据
- python - 在 Python Selenium 中遍历列表元素