gal*_*mok 9 redirect identity unauthorized asp.net-core-mvc asp.net-core
当我从Controller返回NotAuthorized IActionResult时,我一直在尝试阻止重定向,但无论我的尝试如何,NotAuthorized都会转换为Redirect.
我已经尝试了这里提到的(同样的问题,使用旧的beta框架,我使用1.0.0-rc1-final).我没有Notifications命名空间(已在rc1-final中删除).
这是我的登录控制器:
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return Ok(model);
}
if (result.IsLockedOut)
{
return new HttpStatusCodeResult((int)HttpStatusCode.Forbidden);
}
else
{
return HttpUnauthorized();
}
}
return HttpUnauthorized();
}
Run Code Online (Sandbox Code Playgroud)
在Startup.cs中,我尝试了以下变体:
services.Configure<CookieAuthenticationOptions>(o =>
{
o.LoginPath = PathString.Empty;
o.ReturnUrlParameter = PathString.Empty;
o.AutomaticChallenge = false;
});
Run Code Online (Sandbox Code Playgroud)
每次登录失败时(请忽略密码在Ok上返回)并且应该导致空的401页面,我将重定向到/ Account/Login.这里的诀窍是什么?
解决方案不是直接配置CookieAuthenticationOptions,而是通过IdentityOptions这样做:
services.Configure<IdentityOptions>(o =>
{
o.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = ctx =>
{
if (ctx.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
return Task.FromResult<object>(null);
}
ctx.Response.Redirect(ctx.RedirectUri);
return Task.FromResult<object>(null);
}
};
});
Run Code Online (Sandbox Code Playgroud)
摘自此处(Shawn Wildermuth - > ASP.NET 5身份和REST API - >"Mehdi Hanafi"的评论)并使用Postman测试API
config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = ctx =>
{
if (ctx.Request.Path.StartsWithSegments("/api") &&
ctx.Response.StatusCode == 200)
{
ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Task.FromResult<object>(null);
}
else
{
ctx.Response.Redirect(ctx.RedirectUri);
return Task.FromResult<object>(null);
}
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3684 次 |
| 最近记录: |