c# - 用于 web-api 触发重定向的 Asp.net 核心授权

标签 c# asp.net asp.net-core asp.net-core-mvc asp.net-authorization

我尝试开始使用带有 SPA 的 asp.net 核心 Web 应用程序。 我已经按照教程构建了所有内容。所以我像这样设置授权:

            app.UseIdentity()
            .UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationScheme = "MyCookieMiddlewareInstance",
                AutomaticAuthenticate = true,
                AutomaticChallenge = true
            });

我有 web-api Controller :

[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); 异常(exception) - 没有配置身份验证处理程序来处理方案:Identity.Application

我想在我的 MVC Controller 中接收重定向,但在没有授权的情况下从 Webapi 端点接收到 401/403。如何从 AuthorizeAttribute 为 MVC 和 WebApi Controller 实现不同的行为? 感谢您的任何预付款。

最佳答案

Michał Dymel 写了一篇关于此的博文:https://devblog.dymel.pl/2016/07/07/return-401-unauthorized-from-asp-net-core-api/

他没有将 AutomaticChallenge 设置为 false,而是使用 IdentityOptions 拦截到登录 View 的重定向,并在请求 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;
                                    }
            };
    });

关于c# - 用于 web-api 触发重定向的 Asp.net 核心授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38742648/

相关文章:

asp.net - 如何添加管理员角色(我的解决方案)

c# - 与时间复杂度有关的疑问!

c# - 停止引发 Filewatcher 控件的创建事件以自动生成原始内容的临时文件

.net - 获取远程名称地址(非 IP)

asp.net - ListView 的项目有 DropDownList : How to get the DataItem when selection changes?

asp.net - NopContext.Current.User 始终为 null

asp.net-core - 从 ASP.NET 5 调用 ADODB COM 对象

.net - 在.NET Core RC2中构建.exe文件

c# - 没有可用于编码 1252 的数据 - Xamarin

c# - 如何使用 include in 子查询进行左外连接?