1

我已經創建了通過自動化需求簡單自動化的web api。我的質量要求的代碼如下所示:錯誤的狀態代碼失敗的自動化需求在ASP.NET核心

public class TestRequirement : IAuthorizationRequirement { } 

public class TestHandler : AuthorizationHandler<TestRequirement> { 
    protected override Task 
     HandleRequirementAsync(AuthorizationHandlerContext context, TestRequirement requirement) { 
     //context.Succeed(requirement); --#1 
     //context.Fail(); --#2 
     /*if (context.Resource is AuthorizationFilterContext mvcContext) {--#3 
      mvcContext.Result = new UnauthorizedResult(); 
     }*/ 
     return Task.CompletedTask; 
    } 
} 

另外,我更新Startup.ConfigureServices(...)

 services.AddAuthorization(o => o.AddPolicy("Test", p => p.Requirements.Add(new TestRequirement()))); 
     services.AddSingleton<IAuthorizationHandler, TestHandler>(); 

我加入apropriate屬性控制器:[Authorize(Policy = "Test")]

如果我取消阻止#1 - 它按預期工作(我得到我的數據)。但是當我的代碼失敗requiremnt(我評論#1),我得到500 Internal Server Error

然後,我試圖顯式失敗的要求(取消註釋塊#2) - 相同的結果。我知道這不是建議,但我想嘗試。

之後,我嘗試了更醜陋的解決方法,我評論了#2和未註釋的塊#3。我有相同的500個狀態碼。

只是爲了好玩,我實現了資源過濾器相同的行爲:

public class TestResourceFilterAttribute : Attribute, IResourceFilter 
{ 
    public void OnResourceExecuting(ResourceExecutingContext context) { 
     context.Result = new UnauthorizedResult(); 
    } 

    public void OnResourceExecuted(ResourceExecutedContext context) { 
    } 
} 

然後,我更換了控制器我的授權屬性與[TestResourceFilter],得到了401 Unauthorized預期。但這是使用資源過濾器的壞方法。

我的需求實施有什麼問題?爲什麼我得到500而不是401(或403)?

編輯:我在我的日誌中發現InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found.。 我看到了Cookie方案的示例,但它不適合我。因爲我想實施無狀態呼叫。

+0

你正在編寫*服務器代碼*,有沒有這樣的作爲服務器代碼中的錯誤500。您會在客戶端看到錯誤500,但這不是出現問題的地方。看看你的日誌,看看服務器的實際錯誤。您可能會遇到異常,並且該異常會告訴您什麼是錯誤的。 – poke

+0

@poke好點,我會添加異常處理程序,並會看到發生了什麼。 – RredCat

+0

不,看看你的日誌!例外情況會自動記錄。 – poke

回答

1

poke的通信指出我以錯誤的方式實現了我的功能。我試圖處理授權級別的安全檢查,但我必須在認證級別上進行。所以,我最後的代碼如下所示:

public class TestHandlerOptions : AuthenticationSchemeOptions { } 

internal class TestHandler : AuthenticationHandler<TestHandlerOptions> { 
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { 
     if (await SomeCheckAsync()) { 
      var identity = new ClaimsIdentity(ClaimsName); 
      var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), null, ClaimsName); 
      return AuthenticateResult.Success(ticket); 
     } 

     return AuthenticateResult.Fail("Missing or malformed 'Authorization' header."); 
    } 
} 

下一個添加在ConfigureServicesStartup類:

services.AddAuthentication(options => options.AddScheme(SchemeName, o => o.HandlerType = typeof(TestHandler))); 

,並授權屬性看起來像[Authorize(AuthenticationSchemes = SchemeName)]

+1

記得爲'TestHandler'類添加** public **(not _protected_)構造函數。 VS自動生成受保護的構造函數,將無法被依賴注入系統使用。 (得到'xyz無法找到,確保類型是具體的,服務註冊爲公共構造函數的所有參數。「錯誤。) – wye

+0

感謝@wye的評論。我會考慮它。 – RredCat

相關問題