我們已經在StackOverflow上找了很多關于這個問題的資料,但是我們似乎不能讓它發揮作用。
我們的情況是這樣的。我們有服務器A和服務器B。 服務器A是一個Web API,與同樣是Web API的服務器B進行通信。 服務器 B 應該只為來自服務器 A 的 http 請求提供服務,而拒絕所有其他請求。 我們正試圖通過使用cors來強制實作這一點
。public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>)
{
options.AddPolicy(name: "AllowSpecificOrigin", builder =>
{
builder.WithOrigins(new string[0]); //空串列作為測驗。
});
});
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
app.UseRouting()。
app.UseCors("AllowSpecificOrigin"/span>)。
app.UseEndpoints(endpoints =>)
{
endpoints.MapControllers()。
});
...
但是現在在我們的一個控制器中,有兩個方法。一個需要 CORS,另一個則不需要。
[ApiController]
[Route("api/Server")]
public sealed class ServerController : ControllerBase
{
[HttpGet] 。
[Route("ServerCheck")]
[DisableCors[/span]]
public IActionResult ServerCheck()
{
return Ok(true)。
}
[HttpGet]
[Route("Version")]
[EnableCors("AllowSpecificOrigin")]
public IActionResult Version()
{
return Ok(GetType().Assembly.GetName().Version.ToString() )。)
}
}
如果我知道通過Postman向這兩個方法發出請求,這兩個方法都會提供一個答案。但是,由于我們不允許任何來源,我們的請求怎么會在控制器中被提供呢?
CORS是解決這個問題的錯誤方法嗎? 什么才是最好的方法? 還是我們的配置根本就錯了?
在我們的appsettings.json或appsettings.Development.json中,沒有任何地方有 "AllowedHosts "一行。
uj5u.com熱心網友回復:
你可以創建一個自定義的授權過濾器,通過授權過濾器驗證該主機是否被允許
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
使用Microsoft.AspNetCore.Mvc.Filters。
public class ValidateDomainAttribute : Attribute, IAuthorizationFilter
{
private IEnumerable<string> AllowedDomains { get; }
public ValidateDomainAttribute(params string[] domains){
AllowedDomains = domains;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var host = context.HttpContext.Request.Host;
if (!AllowedDomains。 Contains(host, StringComparer.OrdinalIgnoreCase)
{
context.Result = new BadRequestObjectResult("域名不允許!")。
}
}
并且通過在StartUp類中注冊這個屬性來對所有控制器和動作進行全域應用:
。public class Startup
{
公共 void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options =>)
{
options.Filters. Add(new ValidateDomainAttribute("you-allowed-domain-1", "your-allowed-domain-2")。)
)};
//其余代碼。
}
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
更多關于過濾器屬性的資訊可以在這里找到。https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-5.0
uj5u.com熱心網友回復:
你是否考慮過一個IP地址允許串列?或者一個API密鑰或其他形式的認證?
您似乎正試圖利用 CORS 進行訪問控制,而這并不是它的目的。Mozilla 檔案相當不錯,但簡而言之,CORS 是一種安全地繞過瀏覽器同源限制的方法,您不應該期望它以同樣的方式使用 Postman 或任何其他非瀏覽器客戶端。
同樣值得考慮的是,每一個頭都可以被攻擊者控制,因此不應該被信任,任何憑證都應該只通過 https 傳輸
。轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/322724.html
標籤:
