![](/img/trans.png)
[英]ASP.NET Web-api core: Handling client connections problems and find conflicts
[英]Asp.net core authorization for web-api firing redirect
我尝试使用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端点时,我会收到重定向到登录页面而不是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端点接收401/403。 如何从AuthorizeAttribute
为MVC和WebApi控制器实现不同的行为? 谢谢你的任何进步。
MichałDymel写了一篇关于这篇文章的博文: https : //devblog.dymel.pl/2016/07/07/return-401-unauthorized-from-asp-net-core-api/
他没有将AutomaticChallenge
设置为false
,而是使用IdentityOptions
拦截重定向到登录视图,并在请求URL以“/ api /”段开头时拒绝它。 要实现此目的,您应该修改Startup.ConfigureServices
方法,如下所示:
services.AddIdentity<User, Role>(identityOptions =>
{
identityOptions.Cookies.ApplicationCookie.Events =
new CookieAuthenticationEvents
{
OnRedirectToLogin = context =>
{
if (context.Request.Path.StartsWithSegments("/api") &&
context.Response.StatusCode == (int) HttpStatusCode.OK)
context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
else
context.Response.Redirect(context.RedirectUri);
return Task.CompletedTask;
}
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.