Home > Enterprise >  .Net WebApi - CORS are Missing Allow Origin
.Net WebApi - CORS are Missing Allow Origin

Time:04-26

I'm doing my first WebAPI project in .Net and for frontend I'm using React. I just implemented JWT authorization and I notice when I run react server the posts are not fetching anymore. I tried to inspect to see what is the issue and I notice that the status is Blocked, and Transferred -> CORS are Missing Allow Origin.

How can I fix this issue? Thank you in advance.

var builder = WebApplication.CreateBuilder(args);

// DB set
var connectionString = builder.Configuration.GetConnectionString("DBConnection");
builder.Services.AddDbContext<FireStoneDbContext>(options =>
    options.UseSqlServer(connectionString));

// CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", builder =>
    {
        builder.AllowAnyMethod()
               .AllowAnyOrigin()
               .AllowAnyHeader();
    });
});

// Add services to the container.
builder.Services.AddControllers();

// Register services
builder.Services.AddTransient<IPostService, PostService>();
builder.Services.AddTransient<IAuthService, AuthService>();
builder.Services.AddTransient<IUsersService, UsersService>();
// Register Repositories
builder.Services.AddTransient<IPostRepository, PostRepository>();
builder.Services.AddTransient<IUsersRepository, UsersRepository>();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "FireStone API",
        Description = "An ASP.NET Core Web API for managing FireStone",
        TermsOfService = new Uri("https://example.com/terms"),
    });

    options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Description = "Standard Authorization header using the Bearer scheme (\"bearer {token}\")",
        In = ParameterLocation.Header,
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey
    });

    options.OperationFilter<SecurityRequirementsOperationFilter>();

    // using System.Reflection;
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});

// Authentication for the apis
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)),
            ValidateIssuer = false,
            ValidateAudience = false,
        };
    });


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

app.Run();

Request header:

GET /api/Post HTTP/1.1
Host: localhost:7187
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Origin: http://localhost:3000
Connection: keep-alive
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
Pragma: no-cache
Cache-Control: no-cache

HTTP/2 200 OK
content-type: application/json; charset=utf-8
date: Mon, 25 Apr 2022 12:06:34 GMT
server: Kestrel
X-Firefox-Spdy: h2

enter image description here

CodePudding user response:

you need to add app.UseCors between UseRouting and UseAuthorization

app.UseRouting();

app.UseCors("AllowAll");

app.UseAuthorization();
  • Related