Val*_*rio 1 unauthorized angularjs asp.net-core-mvc
我正在使用AngularJs前端开发一个ASP.NET MVC 6 Web API应用程序.
当我离开会话十年,或者我试图未经授权调用Web API动作时,我希望收到401状态代码.相反,我得到302,并尝试重定向到登录的默认路径("/帐户/登录").
所以我需要在Angular中处理这个问题.
从这里的其他论坛帖子和谷歌搜索我发现有些人在startup.cs中解决他们的问题:
services.Configure<CookieAuthenticationOptions>(options =>
{
options.LoginPath = PathString.Empty;
});
Run Code Online (Sandbox Code Playgroud)
对我来说没有运气.
我使用Identity作为身份验证后端甚至添加
services.ConfigureIdentityApplicationCookie(options =>
{
options.LoginPath = PathString.Empty;
});
Run Code Online (Sandbox Code Playgroud)
没有给我预期的结果.ASP.NET文档建议这种方式返回401.
使用1.0.0-beta7 CLR x86,IIS Express.
编辑:@EZI提出的解决方案是正确的.在我的回答下面,这对最近的版本不起作用.
最后!我找到了解决方案!
为了完整起见,我开始在aspnet/Identity github上的源代码中找到这条评论.
// If the LoginPath is null or empty, the middleware will not look for 401 Unauthorized status codes, and it will not redirect automatically when a login occurs.
Run Code Online (Sandbox Code Playgroud)
这给了我错误的指示.
在ConfigureIdentityApplicationCookie'选项上进行调试,我发现在"Notifications"属性上有一个委托
OnApplyRedirect
Run Code Online (Sandbox Code Playgroud)
答对了!
现在我可以控制重定向.
services.ConfigureIdentityApplicationCookie(options =>
{
options.LoginPath = PathString.Empty;
options.Notifications = new CookieAuthenticationNotifications {
OnApplyRedirect = context => { context.Response.StatusCode = 401; }
};
});
Run Code Online (Sandbox Code Playgroud)
这可能不是处理问题的好方法,但最终我在没有身份验证的情况下调用web.api操作时收到401 Unauthorized.
| 归档时间: |
|
| 查看次数: |
855 次 |
| 最近记录: |