.NET Core WebApi 加入CORS (.net 7.0 up)與allow預檢要求

.NET Core WebApi 加入CORS (.net 7.0 up)與allow預檢要求

有時候我們希望測試Client端呼叫Server的Api,但若domain不相同或是沒有合理的開放的話,Browser會直接進行安全性的封鎖

<html>
    <head>
    </head>
    <body>
        <script language="javascript">
            window.onload = function(e){
                // Make a request for a user with a given ID
                axios.get('https://localhost:5001/api/test/history')
                .then(function (response) {
                    // handle success
                    console.log(response.status);
                })
                .catch(function (error) {
                    console.log(error.response.status);
                    // handle error
                    console.log(error);
                })
                .then(function () {
                    // always executed
                });
            }
        </script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg+GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    </body>
</html>

若我們真的去打了一個404不存在的網頁,但實際上Server有接到請求,所以回的了404,但是js端卻會因為CORS的Policy導致報錯,這個錯誤的例外,會導致js拿到ERR_NETWORK而且也無其他訊息或完整的異常資訊

.Net Core Startup.cs中,找到以下段落
//public void ConfigureServices(IServiceCollection services)內
services.AddCors(options => { options. AddPolicy(name: "MyAllowSpecificOrigins", policy => { policy. AllowAnyOrigin() . AllowAnyHeader(); }); });
//public void Configure(IApplicationBuilder app, IWebHostEnvironment env)內

app.UseRouting();
            
app.UseCors("MyAllowSpecificOrigins");

app.UseSentryTracing(); // 要啟用 Sentry 上的 Performance Monitoring 需加這行

app.UseAuthentication();

備註:UseCors的呼叫必須放在UseRouting之後 ,但在UseAuthorization之前,若有具名的policy,就也要具名UseCors加進來,若有具名但沒有UseCors(“xxxxxx”)的話,仍視為無效

所以成功加進去後,axios套件也是可以抓到

2024/01/30更新

大部分的CORS設定若是在Azure的app service仍可以透過CORS的Portal設定去處理掉

不過若是在本機的環境,有遇到下面的錯誤訊息(host有改過所以不是localhost)

Access to XMLHttpRequest at 'https://dev.azurewebsites.net:5001/api/Auth/app-login' from origin 'https://dev.azurewebsites.net:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

代表被preflight預檢請求擋掉了

這個時候在Api的Program.cs

var app = builder.Build(); 
//之後加上
app.UseCors(options =>
    options
        .WithOrigins("https://dev.azurewebsites.net:3000", "*") 
         //note Allow Any Origin或直接"*"不會過 
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials());
//之前加上
app.UseHttpsRedirection();

MSDN Reference∶

https://learn.microsoft.com/zh-tw/aspnet/core/security/cors?view=aspnetcore-8.0

One Reply to “.NET Core WebApi 加入CORS (.net 7.0 up)與allow預檢要求”

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *