3

我嘗試開始與SPA的asp.net核心web應用程序。 我已經通過教程構建了一切。所以我設置的授權這樣的:Asp.net核心授權web-api發射重定向

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

而且我的WebAPI控制器:

[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"); 
     } 
     //... 
    } 

但是,當我把我的WebAPI端點JS,我收到重定向到登錄頁面而不是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控制器的不同行爲? 感謝您的任何提前。

回答

5

米哈爾Dymel寫了一篇博客文章認爲:https://devblog.dymel.pl/2016/07/07/return-401-unauthorized-from-asp-net-core-api/

而不是設置AutomaticChallengefalse的,他使用的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; 
            } 
      }; 
    });