Mar*_*ris 4 c# asp.net asp.net-authorization asp.net-core-mvc asp.net-core
我尝试使用SPA开始使用asp.net核心Web应用程序.我已经通过教程构建了所有内容.所以我设置了这样的授权:
app.UseIdentity()
.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
Run Code Online (Sandbox Code Playgroud)
我有web-api控制器:
[Route("Somewhere")]
[Produces("application/json")]
[Authorize()]
public class MyControllerController : Controller
{
[HttpGet]
public async Task<IEnumerable<Something>> GetSomething()
{
//....
}
}
Run Code Online (Sandbox Code Playgroud)
和授权功能:
[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");
}
//...
}
Run Code Online (Sandbox Code Playgroud)
但是当我在JS中调用我的webapi端点时,我会收到重定向到登录页面而不是401
状态.
我已经开始进行调查,发现在计算器的答案,我要设置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;
}
};
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4163 次 |
最近记录: |