So the problem is that i have Blazor WebAssembly for a front-end, Making API calls through the Ocelot API Gateway but for some reason the CORS are failing
but in Ocelot Gateway in Program.cs i have
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.SetBasePath(builder.Environment.ContentRootPath)
.AddJsonFile("ocelot.json", optional: false, reloadOnChange:true)
.AddEnvironmentVariables();
builder.Services.AddOcelot(builder.Configuration);
var app = builder.Build();
await app.UseOcelot();
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.Run();
Having like this also does not work:
builder.Services.AddCors(options =>
{
options.AddPolicy("asd",
policy =>
{
policy.AllowAnyOrigin().AllowAnyMethod();
});
});
var app = builder.Build();
await app.UseOcelot();
app.UseCors("asd");
app.Run();
What should I do to access any origin or just get rid of this cors? I have tried nearly everything but nothings seems to solve my problem.
Solution:
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.SetBasePath(builder.Environment.ContentRootPath)
.AddJsonFile("ocelot.json", optional: false, reloadOnChange:true)
.AddEnvironmentVariables();
builder.Services.AddOcelot(builder.Configuration);
builder.Services.AddCors(); // Add cors
var app = builder.Build();
app.UseCors(builder => builder // Allow any
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
await app.UseOcelot();
app.Run();
Related
How can I setup listening multiple ports? On first port I want to have default app with https, on another I want to use HTTPS and require SSL based authentication with client certificates. How to do it? This is my current Startup.cs code:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(kestrelOptions =>
{
kestrelOptions.ConfigureHttpsDefaults(httpOptions =>
{
httpOptions.ClientCertificateMode = ClientCertificateMode.AllowCertificate;
});
});
var services = builder.Services;
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, cfg =>
{
cfg.ReturnUrlParameter = "returnUrl";
cfg.LoginPath = "/account/login";
cfg.LogoutPath = "/account/logout";
})
.AddCertificate(CertificateAuthenticationDefaults.AuthenticationScheme, cfg =>
{
cfg.AllowedCertificateTypes = CertificateTypes.All;
cfg.RevocationMode = X509RevocationMode.Online;
});
services.AddControllersWithViews();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
My goal is to use Certificate authentication on some endpoints (and don't display certificate request e.g. for web explorer users) and not use delayed certificates.
I did it with kestrelOptions.ListenLocalhost:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(kestrelOptions =>
{
kestrelOptions.ListenLocalhost(8080, cfg =>
{
cfg.UseHttps(httpOptions =>
{
httpOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
});
});
kestrelOptions.ListenLocalhost(8081, cfg =>
{
cfg.UseHttps(httpOptions =>
{
httpOptions.ClientCertificateMode = ClientCertificateMode.NoCertificate;
});
});
});
Now one port is for mTLS (8080) and another don't require certificate! Works really nice.
I am trying to publish my web api that i created using asp.net core 6 to azure it publishes successfully however i get a HTTP Error 500.30 - ASP.NET Core app failed to start error when the webapp tries to start when i try to debug it in the console i get the following error
which points to my programe.cs folder
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MyPortfolioWebAPI.Data;
using Microsoft.AspNetCore.Cors;
using Newtonsoft.Json.Serialization;
using Microsoft.Extensions.FileProviders;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<MyPortfolioContext>(options => options.UseSqlServer(builder.Configuration["ConnectionStrings:DefaultConnection"]));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//Enable cores
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowOrigion", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
//Json Serializer
builder.Services.AddControllersWithViews().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
.AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
// Add services to the container.
builder.Services.AddControllers();
var app = builder.Build();
//Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(options=>options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseAuthorization();
app.MapControllers();
builder.Services.AddDirectoryBrowser();
app.UseStaticFiles();
//
var fileProvider = new PhysicalFileProvider(Path.Combine(path1:builder.Environment.WebRootPath, "Images"));
var requestPath = "/Images";
//
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = fileProvider,
RequestPath = requestPath
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = fileProvider,
RequestPath = requestPath
});
app.Run();
I create a sample project and using your code. I can reproduce the issue.
You need change your code
var fileProvider = new PhysicalFileProvider(Path.Combine(path1:builder.Environment.WebRootPath, "Images"));
to
var fileProvider = new PhysicalFileProvider(Path.Combine(path1:builder.Environment.ContentRootPath, "Images"));
These two methods can be compiled successfully. When I use WebRootPath on my side, the prompt is null, so I use ContentRootPath according to the official document.
We also can check the error logs in kudu site.
We can find the error in here, you also can use other methods.
And you have Images folder in project, so you also need tp include the folder when you build or publish. I temporarily added the Images folder to wwwroot and the program works fine.
Test Result
Here is my program.cs class:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddTransient<IUserService, UserService>();
builder.Services.AddTransient<IUserRepository, UserRepository>();
#region IAUECManager Database Connection
builder.Services.AddDbContext<IAUECManagerDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("IAUECManagerConnectionString"));
});
#endregion
#region JWT Authentication
//TODO Change JWT Secret Key
var jwtSecretKey = "something that should be change in the future";
builder.Services.AddHttpClient();
builder.Services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(option =>
{
option.RequireHttpsMetadata = false;
option.SaveToken = true;
option.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSecretKey)),
ValidateIssuer = false,
ValidateAudience = false
};
});
#endregion
//services.AddCors();
builder.Services.AddCors(o => o.AddPolicy("MyPolicy", builder => {
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin();
}));
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors("MyPolicy");
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Why when I want to send a request from ajax which is in my UI project that is including in the same solution with my api project it says:
Access to XMLHttpRequest at 'https://localhost:7039/api/V1/Users/Register' from origin 'https://localhost:44323' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am in the process of upgrading from IdentityServer4 1.x to IdentityServer4 2.0 which also means that i have upgraded the to .Net core 2.0 I am aware that there are a lot of breaking changes with this upgrade I have done it once before but for some reason I am stuck on this error.
warn: IdentityServer4.Startup[0]
No default authentication scheme has been set. Setting a default scheme is required.
warn: IdentityServer4.Startup[0]
No default authentication scheme has been set. Setting a default scheme is required.
The error appears in Configure after i call app.UseIdentityServer();
Configure method:
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
if (Debugger.IsAttached)
loggerFactory.AddConsole(Configuration);
else
loggerFactory.AddConsoleJson(Configuration);
InitializeDatabase(app);
// Stops microsoft from overwriting claim types to their proprietary ones
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
app.UseAuthentication();
app.UseCors(builder =>
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()
);
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedProto
});
app.UseDeveloperExceptionPage();
app.UseIdentityServer();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
ConfigureServices method
public void ConfigureServices(IServiceCollection services)
{
var settingsSetup = Configuration.GetSection("Settings").Get<Settings>();
settingsSetup.XenaConnectionUrl = Configuration["XenaPath"];
services.AddSingleton(settingsSetup);
var idsConnectionString = Configuration.GetConnectionString("XenaIdentityConnection");
var xenaConnectionString = Configuration.GetConnectionString("XenaConnection");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<UserDbContext>(builder =>
builder.UseSqlServer(xenaConnectionString));
services.AddCors();
services.AddMvc();
services.TryAddScoped<UserManager, UserManager>();
services.TryAddScoped<SignInManager, SignInManager>();
services.TryAddSingleton(new XenaClient(Configuration));
services.AddTransient<Services.IClaimsService, XenaClaimsService>();
services.AddTransient<IProfileService, ProfileService>();
// Sms service setup
services.Configure<SmsOptions>(Configuration.GetSection("SmsOptions"));
services.AddTransient<ISMSService, SMSService>();
services.AddTransient<IResourceOwnerPasswordValidator, PasswordValidator>();
services.AddIdentityServer()
.AddSigningCredential(LoadCertificate())
// this adds the config data from DB (clients, resources)
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(idsConnectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
// this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(idsConnectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
.AddProfileService<ProfileService>();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
});
services.AddAuthorization(options =>
{
options.AddPolicy("Supporter", policy => policy.RequireClaim("supporter"));
});
}
I am setting DefaultAuthenticateScheme so i cant really figure out what the problem is. I have resorted to digging around in the source code and it seams to have something to do with the validation I am obviously not adding something but i cant figure out what it is source
I found the problem. All the following does is initialise it. It doesnt actually add an authentication type.
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
});
The project I was using as reference had the following
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
})
.AddGoogle("Google", options =>
{
options.AccessType = "offline";
options.SignInScheme = IdentityConstants.ExternalScheme;
options.ClientId = Configuration.GetSection("Settings:GoogleClientId").Value;
options.ClientSecret = Configuration.GetSection("Settings:GoogleClientSecret").Value;
});
But my current project does not need google login at this time so i just removed that part. Which caused it to fail becouse no authecation type had been added.
I just removed the AddAuthentication part and everything is working now.
I am trying to use cookie based authentication in ASP.Net Core 2.0 Web API and trying to activate that using the following code. The signin page is hosted inan separate domain than the one the app is hosted. And I have added [Authorize] attribute to the controller.
At startup I can see the service code invoked in debugger.
My expectation is that when my web client use the web api service, the middleware will detect that header does not have the cookie and will redirect the client to the login page. Yet I am able to invoke the controller freely.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("AllowAll",
builder => builder.SetIsOriginAllowed(s => true)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()));
services.TryAddTransient<CorsAuthorizationFilter, CorsAuthorizationFilter>();
services.AddSwaggerGen(c =>
{
c.OperationFilter<FileOperationFilter>();
c.SwaggerDoc("v1", new Info
{
Title = "Collateral Management API",
Version = "v1"
});
});
services.AddMvcCore(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.AddApiExplorer()
.AddJsonFormatters(s => s.NullValueHandling = NullValueHandling.Ignore);
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(auth =>
{
auth.Cookie.Domain = "xxx.com";
auth.Cookie.Name = "xxx";
auth.LoginPath = "/signin";
auth.AccessDeniedPath = "/signin";
});
services.AddAuthorization(auth =>
{
auth.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
});
//...
}
and later ...
app.UseAuthentication()
Try adding:
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
});
After services.AddMvc()
EDIT
Given the way you are adding MVC can you try:
// requires: using Microsoft.AspNetCore.Authorization;
// using Microsoft.AspNetCore.Mvc.Authorization;
services.AddMvcCore(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
AddMvcCore doesn't add the authorization services by default. You will also need to do AddMvcCore(...).AddAuthorization()