2016-08-31 31 views
2

我有一個可以工作的Asp.NET核心WebApi服務和一個可以從ASP.NET核心MVC應用程序調用的服務。該服務使用AutoRest生成的包裝來調用。該服務目前沒有安全層,而使用OAuth2保護網站。使用OAuth2保護和訪問.NET核心WebApi服務

我已經添加了以下的服務:

public void ConfigureServices(IServiceCollection services) 
    { 
     // Add framework services. 
     services.AddApplicationInsightsTelemetry(Configuration); 

     services.AddMvc(); 

     // NEW Authorisation 
     services.AddAuthorization(options => 
     { 
      options.AddPolicy("ApiAccess", policy => policy.RequireClaim("email")); 
     }); 

    } 

我的控制器固定這樣:

[Authorize(Policy = "ApiAccess")] 
public class StatusController : Controller 

不過,我得到一個「未授權」的例外,當我打電話AutoRest包裝:

try 
     { 
      var service = new StatusAPI(new Uri("http://localhost:17237/")); 
      ViewData["State"] = service.ApiStatusGet(); 
     } 
     catch (Exception ex) 
     { 
      ViewData["State"] = new[] { new ServiceStatus { Name = "Health API", Message = "Is unreachable " + ex.Message } }; 
     } 

我不確定問題在於我需要一種方法來傳遞呼叫中的索賠包裝或如果它在我的服務設置和它如何檢測索賠。

+0

是否有認證的中間件或填寫主要的電子郵件要求一些自定義代碼? – ycrumeyrolle

+0

理想情況下,我正在尋找一個示例顯示如何配置事件 – Mark

+0

我沒有看到您提供任何類型的包含電子郵件聲明的令牌。這是'StatusAPI'爲你照顧的嗎? –

回答

0

請嘗試指定索賠的價值,如允許的電子郵件地址。由於這裏建議 - https://docs.asp.net/en/latest/security/authorization/claims.html

重複碼

options.AddPolicy("Founders", policy => policy.RequireClaim("EmployeeNumber", "1", "2", "3", "4", "5"));

+0

據我所知,只是限制了索賠的有效價值,並且據我所知,我沒有任何索賠通過 – Mark

0

Autorization不能在沒有認證完成。 您需要先認證用戶,然後查看其身份以授予訪問權限。

如果您的OAuth2 AS提供了JWT,則可以使用JWT身份驗證中間件。

public void ConfigureServices(IServiceCollection services) 
{ 
    // add the authentication dependencies 
    services.AddAuthentication(); 
} 

public void Configure(IApplicationBuilder app) 
{ 
    app.UseJwtBearerAuthentication(new JwtBearerOptions 
    { 
    // configure your JWT authentication here 
    }); 
} 

當然,JWT應該包含一個「email」聲明。

你可以看一下在ASPNET核心樣本: https://github.com/aspnet/Security/blob/dev/samples/JwtBearerSample/Startup.cs#L67