【问题标题】:Asp.net core authorization for web-api firing redirect用于 web-api 触发重定向的 Asp.net 核心授权
【发布时间】:2016-12-09 02:51:53
【问题描述】:

我尝试开始使用带有 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。对于 MVC 和 WebApi 控制器,如何实现与 AuthorizeAttribute 不同的行为? 感谢您的任何提前。

【问题讨论】:

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


    【解决方案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 方法,如下所示:

    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;
                                        }
                };
        });
    

    【讨论】:

      猜你喜欢
      • 2019-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 2021-08-22
      • 2021-12-08
      • 1970-01-01
      相关资源
      最近更新 更多