0

我們有這個自定義的授權方案,我試圖解決的能力,單元測試和在.NET核心中使用依賴注入。讓我解釋一下設置:.NET核心自定義授權依賴注入

我創建了一個接口IStsHttpClient和類StsHttpClient。此類連接到創建&解碼令牌的內部Web服務。這有一個方法「DecodeToken(字符串標記)」,構造函數非常簡單 - 它需要一個從DI加載的選項對象。

然後,我的AuthorizationHandler理論上會使用IStsHttpClient調用和解碼令牌。我的問題是,基於在線示例,我不知道如何正確指定/構建授權處理程序(請參閱下面的代碼)。

授權碼在這裏:

public class MyAuthorizationRequirement : AuthorizationHandler<MyAuthorizationRequirement >, IAuthorizationRequirement 
{ 
    const string Bearer = "Bearer "; 
    readonly IStsHttpClient _client; 

    public BuzzStsAuthorizationRequirement([FromServices]IStsHttpClient client) 
    { 
     _client = client;   
    } 

    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, MyStsAuthorizationRequirement requirement) 
    { 
     /* remaining code omitted - but this will call IStsHttpClient.Decode() */ 

我Startup.cs

public void ConfigureServices(IServiceCollection services) 
    { 
     services.Configure<StsHttpOptions>(Configuration.GetSection("StsConfigurationInfo")); 
     services.AddScoped<IStsHttpClient , StsHttpClient >(); 
     services.AddAuthorization(options => 
     { 
      options.AddPolicy("Authorize", policy => 
      { 
       /* initialize this differently?? */ 
       policy.AddRequirements(new MyStsAuthorizationRequirement(/* somethign is needed here?? */)); 
      }); 
     }); 

回答

1

尼古拉斯,

你有你的處理程序和要求在這裏分開。除此之外,你的DI的東西在處理程序。需求本身將是一個DTO或具有標記接口IAuthorizationRequirement的空類。

要求:

public class MyAuthorizationRequirement : IAuthorizationRequirement 
{ 

} 

處理程序:

public class MyAuthorizationHandler : AuthorizationHandler<MyAuthorizationRequirement> 
{ 
    const string Bearer = "Bearer "; 
    readonly IStsHttpClient _client; 

    public BuzzStsAuthorizationRequirement([FromServices]IStsHttpClient client) 
    { 
     _client = client;   
    } 

    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, MyAuthorizationRequirement requirement) 
    { 
    ... 
    } 
} 

配置:

services.Configure<StsHttpOptions>(Configuration.GetSection("StsConfigurationInfo")); 
     services.AddScoped<IStsHttpClient , StsHttpClient >(); 
     services.AddAuthorization(options => 
     { 
      options.AddPolicy("Authorize", policy => 
      {    
       policy.AddRequirements(new MyAuthorizationRequirement()); 
      }); 
     }); 
+0

我最終實現了兩天之後這個,我可以使用中間件做什麼我想。 –

相關問題