ASP.NET初心者です。
自作でASP.NETのWEB APIを作成し、WEB API側でクライアントにデータを返さないようにCORSの設定をしたのですが、
WEB APIを呼び出している側=>正常に、呼び出し処理が失敗してくれる
WEB API側=>処理が実行され、データベースの取得処理が実行されてしまう。(実行されるだけで、API呼び出し側は失敗する)
という状態になってしまいます。
CORSの設定で、WEB API側の処理も実行させないようにしたいのですが、可能でしょうか?
何か設定もれなど、ありますでしょうか?
以下、詳細になります。
[環境]
Windows 10 Pro(64bit)
Microsoft Visual Studio Community 2022 (64 ビット) - Version 17.12.4
作成したプロジェクトで使用しているFrameworkのターゲット:net9.0
[質問内容]
CORSの設定でpolicy.WithOriginsメソッドに設定したURL以外は、WEB API側の処理を実行させないようにする事は可能でしょうか?
[実現したい事]
CORSの設定で、WEB API側の処理を実行させないようにする。
※呼ばれたAPIの中でデータ作成処理などが入っていると、その処理が実行されてしまう為
[発生している問題]
CORSの設定をしても、ASP.NET Core Web APIプロジェクトで作成したAPIの処理が呼ばれてしまう。
[作成したソリューションの構成]
ソリューション名:BlazorApp1
プロジェクト1:BlazorApp1←Blazor WebAssemblyスタンドアロンプロジェクト。画面側を作成し、WEB APIを呼び出す。
プロジェクト2:WebApplication1←ASP.NET Core Web APIプロジェクト。WEB APIの処理を作成する。
[前準備]
1.BlazorApp1プロジェクト側で、"追加"→"サービス参照"から、"OpenAPI"を選択し
WebApplication1で作成したAPIを使用できるクラスを自動生成。
2.ソリューションBlazorApp1の"プロパティ"から、"共通プロパティ"→"スタートアッププロジェクトの構成"で
"マルチスタートアッププロジェクト"に設定し、BlazorApp1とWebApplication1を同時起動するように設定。
3.WebApplication1の、Program.csのAddCorsの設定の中で、policy.WithOriginsメソッドに適当なURLを設定し、
CORSの設定で、処理が実行されないように設定。(https://localhost:9999という存在しないものを設定)
WebApplication1側のProgram.csは、以下になります。
using Microsoft.EntityFrameworkCore;
using WebApplication1;
using WebApplication1.MyEFCore;
using Microsoft.Extensions.Hosting;
using NLog.Web;
using NLog;
using Microsoft.AspNetCore.HttpLogging;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Options;
using NSwag.Generation.Processors.Security;
using NSwag;
using System.Net;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi.Models;
using OpenApiDocument = Microsoft.OpenApi.Models.OpenApiDocument;
var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
try
{
var builder = WebApplication.CreateBuilder(args);
// NLogの設定
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
builder.Host.UseNLog();
// Httpログの設定
builder.Services.AddHttpLogging(options =>
{
//options.LoggingFields = HttpLoggingFields.All;
});
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services.AddOpenApiDocument();
// Windowsサービス登録用の設定
builder.Services.AddWindowsService();
builder.Services.AddHostedService<CustomeService>();
builder.Services.AddDbContextFactory<AndersonDbContext>(opt =>
{
if (builder.Environment.IsDevelopment())
{
opt = opt.EnableSensitiveDataLogging().EnableDetailedErrors();
}
string? connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
opt.UseSqlServer(connectionString,
opt =>
{
opt.EnableRetryOnFailure();
});
});
var myOrigins = "_myOrigins";
builder.Services.AddCors(options =>
{
string allowOriginsUrls = builder.Configuration.GetValue<string>("allowOriginsUrl", "");
var allowOriginsAry = allowOriginsUrls.Split(",");
options.AddPolicy(name: myOrigins,
policy =>
{
policy.WithOrigins(allowOriginsAry)
.AllowAnyHeader().AllowAnyMethod();
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.UseSwaggerUi(options =>
{
options.DocumentPath = "openapi/v1.json";
});
}
// Httpログを使用する
app.UseHttpLogging();
// Cors設定を使用する
app.UseCors(myOrigins);
app.UseHttpsRedirection();
// 認証認可のミドルウェアを追加
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
catch(Exception ex)
{
logger.Error(ex);
}
finally
{
LogManager.Shutdown();
}
WebApplicationo1のappsettings.Development.jsonは、以下になります。
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.AspNetCore.HttpLogging": "Information"
}
},
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5000"
}
}
},
"ConnectionStrings": {
"DefaultConnection": "secret string"
},
"allowOriginsUrl": "https://localhost:9999"
}
[手順]
1.Visual Studioから、"F5"ボタンで実行し、BlazorApp1とWebApplication1が実行される。
(この時、BlazorApp1は、https://localhost:7043というアドレスになっている。
WEB API側のCORSの設定は、https://localhost:9999のみアクセス可能となっている。)
2.BlazorApp1側から、WebApplication1のWEB APIを呼び出す。(OpenAPIで自動作成したクラスから呼び出す)
3.BlazorApp1側のデータ取得処理が、失敗する。(設定した通り失敗する)
4.WebApplication1側の処理が実行されてしまう。(データベースの取得処理が、実行されてしまう)
※CORSの設定で、https://localhost:7043を設定した場合は、正常にBlazorApp1側でデータが取得できます。
以上、よろしくお願いいたします。