3

私はSPAを使用してasp.netコアWebアプリケーションを開始しようとします。 私はチュートリアルですべてを構築しました。だから、そのような私のセットアップの許可:WebアプリケーションのリダイレクトのためのAsp.netコア認可

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

しかし、私はJSで私WEBAPIエンドポイントを呼び出すときに、 401ステータスの代わりにログインページにリダイレクトされます。

私は調査を始めて、falseAutomaticChallengeに設定し、.UseIdentity()を削除しなければならないというstackoverflowに関する回答が見つかりました。しかし、私がそれをするとき、私の[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? ありがとうございます。

答えて

5

のMichałDymelが、そのことについてブログ記事を書いた:https://devblog.dymel.pl/2016/07/07/return-401-unauthorized-from-asp-net-core-api/

代わりfalseAutomaticChallengeを設定するので、彼はログインビューにリダイレクトをインターセプトし、リクエストURLは「/ APIを開始したときに、それを拒否するIdentityOptionsを使用しています/ "セグメント。これを達成するには、次のようにしてメソッドを変更する必要があります。

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; 
            } 
      }; 
    }); 
関連する問題