2

我有使用ASP.NET Core開發的Web API,我需要能夠對同一服務使用Basic和承載身份驗證方案。 由於某種原因,它不起作用:它總是將呼叫視爲持票人。 這裏是我的代碼:在ASP.NET Core中使用多種身份驗證方案

這是屬性我在控制器:

[Authorize(ActiveAuthenticationSchemes = "Basic,Bearer")] 
[ResponseCache(NoStore = true, Duration = 0, VaryByHeader = "Authorization")] 

這是我startup.cs:

這部分是基本身份驗證:

app.UseBasicAuthentication(new BasicAuthenticationOptions 
     { 
      AutomaticAuthenticate = false, 
      AutomaticChallenge = false, 
      Realm = "test", 
      Events = new BasicAuthenticationEvents 
      { 
       OnValidateCredentials = context => 
       { 
        if (svc.IsValidCredential(context.Username, context.Password)) 
        { 
         var claims = new[] 
         { 
         new Claim(ClaimTypes.NameIdentifier, context.Username), 
         new Claim(ClaimTypes.Name, context.Username) 
         }; 

         context.Ticket = new AuthenticationTicket(
          new ClaimsPrincipal(
           new ClaimsIdentity(claims, context.Options.AuthenticationScheme)), 
          new AuthenticationProperties(), 
          context.Options.AuthenticationScheme); 
        } 

        return Task.FromResult<object>(null); 
       } 
      } 
     }); 

而這段代碼用於承載認證:

app.UseAPIKeyAuthentication(new BearerApiKeyOptions 
     { 
      AuthenticationScheme = BearerApiKeySchema, 
      AutomaticAuthenticate = false 
     });  
+0

沒有答覆爲止。沒有人知道如何使用多重身份驗證? –

回答

1

你可以看看this以獲得官方Microsoft GitHub的一些參考。

我的用例略有不同,我需要Cookie和Windows身份驗證的組合。您將需要使用PolicyBuilder執行「需要驗證」部分。

在ConfigureServices方法:

  // add additional authorisation for cookie 
      services.AddAuthorization(options => 
      { 
       options.AddPolicy("CookiePolicy", policy => 
       { 
        policy.AddAuthenticationSchemes("NTLM", "MyCookie"); // order does matter. The last scheme specified here WILL become the default Identity when accessed from User.Identity 
        policy.RequireAuthenticatedUser(); 
       }); 
      }); 

上配置方法:

  app.UseCookieAuthentication(new CookieAuthenticationOptions() 
      { 
       AuthenticationScheme = "MyCookie", 
       LoginPath = new PathString("/Account/Login/"), 
       AccessDeniedPath = new PathString("/Account/AccessDenied/"), 
       AutomaticAuthenticate = false, // this will be handled by the authorisation policy 
       AutomaticChallenge = false // this will be handled by the authorisation policy 
      }); 

在控制器:

 [Authorize("CookiePolicy")] // will check policy with the required authentication scheme (cookie in this case) 
     public IActionResult AuthorisedPageCookie() 
     { 
      return View(); 
     } 
相關問題