我尝试使用SPA开始使用asp.net核心Web应用程序 . 我已经通过教程构建了所有内容 . 所以我设置了这样的授权:
app.UseIdentity()
.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
我有web-api控制器:
[Route("Somewhere")]
[Produces("application/json")]
[Authorize()]
public class MyControllerController : Controller
{
[HttpGet]
public async Task<IEnumerable<Something>> GetSomething()
{
//....
}
}
和授权功能:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model)
{
//...
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return Redirect("somewhere");
}
//...
}
但是当我在JS中调用我的webapi endpoints 时,我会收到重定向到登录页面而不是 401
状态 .
我已经开始调查并在stackoverflow上找到答案,我必须将 false
设置为 AutomaticChallenge
并删除 .UseIdentity()
. 但当我这样做时,我的 [POST]AccountController.Login
方法停止在线工作 - var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe);
,异常 - No authentication handler is configured to handle the scheme: Identity.Application
.
我想在我的MVC控制器中接收重定向,但是在没有授权的情况下从Webapi endpoints 接收401/403 . 如何从 AuthorizeAttribute
为MVC和WebApi控制器实现不同的行为?谢谢你的任何进步 .
1 回答
MichałDymel撰写了一篇关于此事的博客文章:https://devblog.dymel.pl/2016/07/07/return-401-unauthorized-from-asp-net-core-api/
他没有将
AutomaticChallenge
设置为false
,而是使用IdentityOptions
拦截重定向到登录视图,并在请求URL以"/api/"段开头时拒绝它 . 要实现此目的,您应该修改Startup.ConfigureServices
方法,如下所示: