Windows Authentication throwing off CORS? - asp.net

I have an issue where I'm using windows authentication that requires a preflight request to log in. However, despite having CORS enable in my startup file the application will fail the preflight "Allow-Access-Control-Origin" requirement.
Failed to load http://localhost:1190/api/test: Response to preflight
request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed
access.
I'm running a SPA on localhost:8080
I have an axios POST withCredentials
function identityLogin () {
const url = BASE_URL + 'api/token'
axios.get(url, {withCredentials: true}).then(response => {
if (response.statusText === 'OK') {
.....
} else {
....
}
})
.catch(error => {
console.log(error)
....
})
}
In my startup.cs I have
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
app.UseMvc();
Then when I first get the windows credentials, a previous developer wrote this:
[HttpGet("api/token")]
[Authorize]
public async Task<IActionResult> Get()
{
this.Response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:8080");
this.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type,Authorization");
this.Response.Headers.Add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
this.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
.........
}
Is persistent and possibly messing with the UseCORS? Is there a cookie being stored?
All I want the windows credentials for is to check a DB and then respond with a token.
**EDIT **
I specified origins with the same result.
app.UseMvc();
app.UseCors(builder => builder
.WithOrigins("http://localhost:8080")
.AllowAnyMethod()
.AllowAnyHeader(
.AllowCredentials());

ORDER MATTERS in startup.cs
app.UseCors must come before app.UseMvc:
app.UseCors(builder => builder
.WithOrigins("http://localhost:8080")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseMvc();

Related

Blocked by CORS policy despite having policy added to allow any and middleware set

I have been stuck on this issue for days. I'm attempting to add a CORS policy so my application does not require a CORS plugin (extension) to run. I've went through multiple tutorials of how to correctly implement the add policy and how to order the middleware. My application backend should send map data to the front end but without the plugin I receive the infamous
Access to XMLHttpRequest at 'http://localhost:5001/maps/NaturalEarthII/tilemapresource.xml' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. error. From my understanding everything is setup as it should be but the results are not agreeing, Please help! There is no controllers
ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
// Enable Gzip Response Compression for SRTM terrain data
services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/vnd.quantized-mesh" });
options.Providers.Add<GzipCompressionProvider>();
});
// Add CORS Service so Tile Server works
services.AddCors(options =>
{
//Here ive attepted implementing default and specific policy
//I've also tried only allowing specific origins and allowing any method + header
//no luck. I will change this to be more specific once i get maps to show
options.AddDefaultPolicy(
builder => builder.AllowAnyOrigin()
);
options.AddPolicy("allowAny",
builder => builder.WithOrigins("http://localhost:5001")
.SetIsOriginAllowed((host) => true)
.AllowAnyMethod().AllowAnyHeader()
);
});
services.AddControllers();
//services.AddSpaStaticFiles(config => config.RootPath = "wwwroot");
services.AddSingleton(typeof(MessageBus), new MessageBus());
}
Configure method:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Microsoft.Extensions.Hosting.IHostApplicationLifetime applicationLifetime)
{
applicationLifetime.ApplicationStopping.Register(OnShutdown);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Use Gzip Response Compression for SRTM terrain data
app.UseResponseCompression();
// We must set the Content-Type and Content-Encoding for SRTM terrain files,
// so the Client's Web Browser can display them.
app.Map("/terrain/srtm", fileApp =>
{
fileApp.Run(context =>
{
if (context.Request.Path.Value.EndsWith(".terrain")) {
context.Response.Headers["Content-Type"] = "application/vnd.quantized- mesh";
context.Response.Headers["Content-Encoding"] = "gzip";
}
return context.Response.SendFileAsync(
Path.Combine(Directory.GetCurrentDirectory(), ("data/terrain/srtm/" + context.Request.Path.Value)));
});
});
Console.WriteLine(Path.Combine(Directory.GetCurrentDirectory() + "data"));
// Make the data/maps directory available to clients
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "data")),
});
app.UseRouting();
//Add the default policy thats create in the conf services method
app.UseCors();
app.UseAuthorization();
app.UseWebSockets();
app.UseEndpoints(endpoints => endpoints.MapControllers().RequireCors("allowAny"));
bus = (MessageBus)app.ApplicationServices.GetService(typeof(MessageBus));
...
In the Add cors Ive attempted implementing default and specific policy
I've also tried only allowing specific origins and allowing any method + header. No luck. I will change this to be more specific once i get maps to show
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder => builder.AllowAnyOrigin()
);
options.AddPolicy("allowAny",
builder => builder.WithOrigins("http://localhost:5001")
.SetIsOriginAllowed((host) => true)
.AllowAnyMethod().AllowAnyHeader()
);
});
After trying endless attempts at making the back end work I gave up and implemented a reverse proxy on the front end. I can now use my web application without a CORS plugin.
proxy.conf.json:
{
"/maps":{
"target": "http://localhost:5001",
"secure": false
}
}
angular.json:
...
"serve": {
"builder": "#angular-devkit/build- angular:dev-server",
"options": {
"browserTarget": "cesium-angular:build",
"proxyConfig": "src/proxy.conf.json"
},
...
You are setting your allowed origin to be the service itself rather than address of your UI.
In your case your origin should be http://localhost:4200 not 5001
Add this to your program.cs
var app = builder.Build();
...
app.UseCors(policy => policy.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins("https://localhost:4200"));
Do note that the UseCors() needs to be called before UseAuthentication() and UseAuthorization()
I also can't see where you are calling your ConfigureServices method

Openiddict with dotnet core 5 giving the errors as "this server only accepts HTTPS requests."

I am trying to use the oidc-client with oppeniddict in the angular application but there is the error with .well-known/openid-configuration.
Error says:
GET http://localhost:2987/.well-known/openid-configuration 400 (Bad Request)
I have the openiddict implementation in the dot-net core 5 application.
Then I grab the URL http://localhost:2987/.well-known/openid-configuration and browse it in the browser, I am getting the error:
{
"error": "invalid_request",
"error_description": "This server only accepts HTTPS requests.",
"error_uri": "https://documentation.openiddict.com/errors/ID2083"
}
I have also disabled the SSL from web server settings as shown in the figure:
My startup ConfigureServices looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration["ConnectionString"], sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
});
options.UseOpenIddict();
});
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
options.ClaimsIdentity.UserNameClaimType = Claims.Name;
options.ClaimsIdentity.UserIdClaimType = Claims.Subject;
options.ClaimsIdentity.RoleClaimType = Claims.Role;
});
services.AddOpenIddict()
.AddCore(options =>
{
options.UseEntityFrameworkCore()
.UseDbContext<ApplicationDbContext>();
}).AddServer(options =>
{
options.SetAuthorizationEndpointUris("/connect/authorize")
.SetLogoutEndpointUris("/connect/logout")
.SetIntrospectionEndpointUris("/connect/introspect")
.SetUserinfoEndpointUris("/connect/userinfo");
options.RegisterScopes(Scopes.Email, Scopes.Profile, Scopes.Roles);
options.AllowImplicitFlow();
options.AddEncryptionKey(new SymmetricSecurityKey(
Convert.FromBase64String("DRjd/GnduI3Efzen9V9BvbNUfc/VKgXltV7Kbk9sMkY=")));
options.AddDevelopmentSigningCertificate();
options.UseAspNetCore()
.EnableAuthorizationEndpointPassthrough()
.EnableLogoutEndpointPassthrough()
.EnableUserinfoEndpointPassthrough()
.EnableStatusCodePagesIntegration();
}).AddValidation(options =>
{
// Import the configuration from the local OpenIddict server instance.
options.UseLocalServer();
// Register the ASP.NET Core host.
options.UseAspNetCore();
});
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader();
}));
services.AddControllersWithViews();
}
Configure:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStatusCodePagesWithReExecute("/error");
app.UseRouting();
app.UseCors("ApiCorsPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(options =>
{
options.MapControllers();
options.MapDefaultControllerRoute();
});
}
I feel like I have been missing something that is super easy to do. But couldn't find the actual reason for this. There are not any issues in the StackOverflow with this.
Is it the error from Openiddict or from the dot net core 5 itself? Any guide or workaround will be appreciated to dig out this issue.
I faced this problem recently also.
by default the Openiddict SSL is enable.
if you want to disable ssl checking.
you can disable it via following code
options.UseAspNetCore().DisableTransportSecurityRequirement();
Use Below code in method
public override void PreConfigureServices(ServiceConfigurationContext context)
{
PreConfigure<OpenIddictBuilder>(builder =>
{
builder.AddValidation(options =>
{
options.AddAudiences("PaymentService");
options.UseLocalServer();
options.UseAspNetCore();
});
//below code needs to be added
builder.AddServer(options => { options.UseAspNetCore().DisableTransportSecurityRequirement(); });
});
}

ASP.NET CORS Exception on POST with a react app

I have a react app calling my service with CORS enabled from my local app. This works fine for GET methods but for some reason it throws a CORS exception when calling a POST method. Is there anything I need to add to configure for POST? thanks
in my startup.cs:
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins(
"http://localhost:3000"
);
});
});
In my react app the call is pretty basic:
axios({
method: "POST",
url: `https://localhost:44340/patientsearch`,
data: { searchModel },
});
The exception:
Access to XMLHttpRequest at 'https://localhost:44340/patientsearch' from origin 'http://localhost:3000' 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.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(x =>
{
x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().WithOrigins("https://localhost:5002");
});
}

CORS issue in IdentityServer 4

I'm using IdentityServer 4 as oauth for my application ( Reactjs ) I'm running Identityserver on port http://localhost:5000 and reactjs app on http://localhost:3000. I have tried using CORS for my idenityserver4 with the following code.
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer(options =>
{
options.Events.RaiseSuccessEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseErrorEvents = true;
})
.AddClientStore<ClientStore>()
//.AddInMemoryApiResources(Config.GetApiResources())
.AddResourceStore<ResourceStore>()
//.AddInMemoryClients(Config.GetClients())
.AddCustomUserStore()
.AddCertificateFromFile();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins( "http://localhost:3000/")
.AllowAnyMethod()
.AllowAnyHeader());
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment environment)
{
app.UseForwardedHeaders();
if (environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
//app.UseCors("default");
app.UseIdentityServer();
app.UseStaticFiles();
// uncomment, if you want to add an MVC-based UI
app.UseMvcWithDefaultRoute();
}
}
Even though I have added localhost:3000 in WithOrigins(), when I try to make a request from react app with axios I'm getting the following blocked error.
Can someone help me to know where I'm doing wrong. I need my application to only allow some list of origins (apps)
Thanks
It's likely this could be because of the trailing slash, this is mentioned in the documentation.
Note: The specified URL must not contain a trailing slash (/). If the URL terminates with /, the comparison returns false and no header is returned.
Try http://localhost:3000 instead of http://localhost:3000/.
I'd also question the usage of both .AllowAnyOrigin() and .WithOrigins(). What you're looking to achieve should be possible using only .WithOrigins().
If you are sending a request to another domain, try sending a http request from your identity server not react.js app. I encountered a similar issue but i just used my API as a proxy and it worked fine.

CORS problem with B2C and Azure App Service

I have enabled CORS in my ASP.NET/Angular application by using AddCors and EnableCors in controllers. My application is communicating with AD B2C pages. After build I have this error in the console :
Access to XMLHttpRequest at 'https://XXX.b2clogin.com/ (redirected
from 'https://XXX.azurewebsites.net/User/Info') from origin
'https://XXX.azurewebsites.net' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
Startup.cs :
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
Controller :
[EnableCors("CorsPolicy")]
[Authorize]
public class UserEditController : Controller
I have enabled CORS on Azure too by putting : Allowed Origins - * .
UPDATE:
[Route("User/Info")]
[HttpGet]
public async Task<IActionResult> LoggedInUserInfo()
{
if (User.Identity.IsAuthenticated)
{
var user = ((ClaimsIdentity)User.Identity).FindFirst(ClaimTypes.NameIdentifier).Value;
var viewmodel = await userService.GetUserByObjectId(user);
return Json(new { loggedIn = "true", user = viewmodel });
}
return Json(new { loggedIn = "false" });
}
It appears that you're attempting a cross-origin request from the https://xxx.azurewebsites.net/ domain to the https://xxx.b2clogin.com/ domain.
Currently the .b2clogin.com domain doesn't allow any cross-origin requests from any other domain.

Resources