Aurelia Windows Authentication - Post 401 Unauthorized - c#

I'm totally stuck on implementing Windows authentication for one of my .NET Core apps that uses Aurelia for client side.
The Aurelia application is hosted on port:9000 and the .NET WebAPI is hosted on port:9001.
The idea is to serve static pages from my .NET app once the app is published but now in development I use port:9000 because of the BrowserSync provided by Aurelia.
When I use port:9000 it's all fine and dandy and I have no issues posting or getting.
If I switch to port:9001 I can still get but not post. Posting results in 401 Unauthorized.
If we look at the headers for port:9000 requests..
Get(success):
Post(failed):
You can see that there are multiple headers missing in the post for some reasons, most importantly the authentication cookie..
Base-Repo.js
import {inject} from 'aurelia-framework';
import {HttpClient, json} from 'aurelia-fetch-client';
import {AppSettings} from '../infrastructure/app-settings';
#inject(HttpClient, AppSettings)
export class BaseRepo {
constructor(http, appSettings) {
http.configure(config => {
config
.withDefaults({
credentials: 'include',
headers: {
'Accept': 'application/json'
}
})
.withInterceptor({
request(request) {
console.log(`Requesting ${request.method} ${request.url}`);
return request;
},
response(response) {
console.log(`Received ${response.status} ${response.url}`);
return response;
}
})
});
this.http = http;
this.baseUrl = appSettings.api;
}
get(url) {
console.log('BaseRepo(get): ' + url);
return this.http.fetch(this.baseUrl + url)
.then(response => { return response.json(); })
.then(data => { return data; });
}
post(url, data) {
console.log('BaseRepo(post): ' + url, data);
return this.http.fetch(this.baseUrl + url, {
method: 'post',
body: json(data)
})
.then(response => response.json())
.then(data => { return data; });
}
}
Why is GET working but not POST when using BrowserSync port?
Edit 1
Post(success) for port:9001:
Edit 2
Console message post error:
OPTIONS http://localhost:9001/api/MYURLS 401 (Unauthorized)
Fetch API cannot load
http://localhost:9001/api/MYURLS.
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:9000' is therefore not allowed
access. The response had HTTP status code 401. If an opaque response
serves your needs, set the request's mode to 'no-cors' to fetch the
resource with CORS disabled.
Edit 3
Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
env.ConfigureNLog("nlog.config");
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddMemoryCache();
services.AddMvc();
services.InjectWebServices();
services.AddOptions();
//call this in case you need aspnet-user-authtype/aspnet-user-identity
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IConfiguration>(Configuration);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("CorsPolicy");
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
app.UseDefaultFiles();
app.UseStaticFiles();
//add NLog to ASP.NET Core
loggerFactory.AddNLog();
//add NLog.Web
app.AddNLogWeb();
}
}

I enabled "Enable Anonymous Authentication" in project properties and voila...
Before I only had "Enable Windows Authenticaiton" enabled, now both ports work!
When application is deployed this wont be enabled anyway because by then I will use the real IIS.
Update 1
After upgrading to .net core 2.0 I was no longer able to enable both Windows Authentication and Anonymous Authentication.
After some research I found out you have to add:
services.AddAuthentication(IISDefaults.AuthenticationScheme);
in your startup.cs in order for it to work.
More info can be found in comment section and docs.
Update 2
You need Microsoft.AspNetCore.Authentication package for authentication builder.

You will need to enable CORS in your ASP.NET Core project. There's information on how to do this here: https://learn.microsoft.com/en-us/aspnet/core/security/cors.
You need to call AddCors in ConfigureServices:
services.AddCors();
And then UseCors in Configure:
// Shows UseCors with CorsPolicyBuilder.
app.UseCors(builder => builder.WithOrigins("http://example.com"));
When you're using port 9000, you're on a different origin to the API, but with 9001, you're on the same origin and therefore CORS will not apply.
The OPTIONS requests are known as "preflighting". There's more information on those here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests.

Related

Blazor WebAssembly HttpResponseMessage empty Headers [duplicate]

I must be doing something wrong here but I can't figure it out; it seems to be a CORS issue from what I can tell. I need to expose Access-Control-Expose-Headers: * to any origin but dotnet core 2.1 isn't doing what I expect.
Relevant Startup.cs code:
public void ConfigureServices(IServiceCollection services)
{
//Mapping settings to POCO and registering with container
var settings = new AppSettings.ReportStorageAccountSettings();
Configuration.Bind(nameof(AppSettings.ReportStorageAccountSettings), settings);
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials();
});
});
services.AddSingleton(settings);
services.AddApiVersioning();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("AllowAll");
app.UseHttpsRedirection();
app.UseMvc();
}
This application is hosted in Azure and I have added a * entry to the CORS settings in Azure just for good measure. Now, whenever the client application (which is also hosted in Azure) makes a post request, the headers are not accessible via JS and Access-Control-Expose-Headers: * is not present in the response. However, I can see the headers when I inspect the network response and when using Fiddler. I have tried Axios and Jquery for accessing the headers to rule out any issues with the JS. What am I doing wrong here?
In the controller I respond with:
Response.Headers.Add("Location", $"api/someLocation");
return StatusCode(StatusCodes.Status202Accepted);
The CorsPolicyBuilder's AllowAnyHeader method configures the Access-Control-Allow-Headers response header, which is used only for preflighted requests. The Access-Control-Expose-Headers response header is what's needed, which is configured using WithExposedHeaders.
Here's a complete example:
services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()
.WithExposedHeaders("Location"); // params string[]
});
});
As Kirk mentioned .WithExposedHeaders() method is what is needed.
Another variation to Kirk's answer is:
// in Startup.cs
// at the end of ConfigureServices() add:
services.AddCors();
// at the top of Configure() add:
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().WithExposedHeaders("*"));

Blazor cannot connect to ASP.NET Core WebApi (CORS)

I have a ASP.NET Core Server running on local IP https://192.168.188.31:44302 with Web API Enpoints.
I can connect to said server with VS Code REST Client.
Now I want to conenct to the Web API with Blazor WebAssembly running on https://192.168.188.31:5555.
My Blozor Code:
#page "/login"
#inject HttpClient Http
[ ... some "HTML"-Code ... ]
#code {
private async Task Authenticate()
{
var loginModel = new LoginModel
{
Mail = "some#mail.com",
Password = "s3cr3T"
};
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = ClientB.Classes.Uris.AuthenticateUser(),
Content =
JsonContent.Create(loginModel)
};
var response = await Http.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("responseBody: " + responseBody);
}
public async void LoginSubmit(EditContext editContext)
{
await Authenticate();
Console.WriteLine("Debug: Valid Submit");
}
}
When I now trigger LoginSubmit I get the following error-message in the developer console of Chrome and Firefox: login:1 Access to fetch at 'https://192.168.188.31:44302/user/authenticate' from origin 'https://192.168.188.31:5555' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I'm new to web development and found that you have to enable CORS on the server-side ASP.NET Core project, so I extended startup.cs with
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UserDataContext, UserSqliteDataContext>();
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://192.168.188.31:44302",
"https://192.168.188.31:5555",
"https://localhost:44302",
"https://localhost:5555")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddControllers();
services.AddApiVersioning(x =>
{
...
});
services.AddAuthentication(x =>
...
});
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddScoped<IViewerService, ViewerService>();
}
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
Program.IsDevelopment = env.IsDevelopment();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(MyAllowSpecificOrigins);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Log.Initialize();
}
But I still get above error message.
Am I doing something wrong with configuring CORS?
Why is it working as expected with the VS Code REST Client and how am I making the call wrong in the Blazor WASM application?
The issue causing the error message login:1 Access to fetch at 'https://192.168.188.31:44302/user/authenticate' from origin 'https://192.168.188.31:5555' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. was caused by HttpsRedirection.
To resolve the issue, either deactivate HttpsRedirection by removing the line app.UseHttpsRedirection(); in function Configure or add the proper ports for redirection in function ConfigureServices (recommended way).
In my case, I start my WebAPI at port 44302, so my solution looks like this (you have to adapt it to your port number):
if (Program.IsDevelopment)
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 44302;
});
}
else
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443;
});
}
Also note that it is sufficient to add the IP address of the requesting API to CORS like this:
services.AddCors(options =>
{
options.AddPolicy(name: specificOrigins,
builder =>
{
builder.WithOrigins("https://192.168.188.31:5555",
"http://192.168.188.31:5444")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Step 1: Please add following code in your WebAPI's Startup.cs to allow CORS with specific origins:
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
builder.WithOrigins("https://localhost:44351")
.AllowAnyHeader()
.AllowAnyMethod());
});
Step 2: Now change "https://localhost:44351" in above code with your blazor web assembly application's URL. Refer below screen shot:
Step 3: Now add app.UseCors() in your WebAPI's Configure method after app.UseRouting() and before app.UseRouting(). Please refer below screen shot:
I was also facing same issue and it solved my problem. Hope it will also work for you.
Note: No changes required in Blazor web assembly code to fix the above issue.

SignalR JavaScript client error in connect to remote .Net Core Hub

I'm using Asp.Net Core (3) SignalR (Latest Version) as described in Microsoft's tutorial at here https://learn.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-3.1 but having error in connect to hub.
NuGet packages installed on server:
Microsoft.AspNetCore.SignalR(1.1.0)
Microsoft.AspNetCore.SignalR.Core(1.1.0)
My server runs at http://localhost:52852 and the client is running at http://localhost:10843.
I have added the client URL as acceptable Origin in server CORS policy.
Server Startup :
// ConfigureServices
services.AddCors(options =>
options.AddPolicy("CorsPolicy",
builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:10843/")
.AllowCredentials();
}));
services.AddSignalR(hubOptions => {
hubOptions.EnableDetailedErrors = true;
});
// App Configure
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapHub<AsteriskHub>("/signalr");
});
// Hub
public class MyHub : Hub
{
// Some Codes ...
}
Client Javascript :
const connection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:52852/signalr")
.configureLogging(signalR.LogLevel.Information)
.withAutomaticReconnect()
.build();
connection.start();
I have read many documents similar to my issue over Microsoft and Asp.Net and Stackoverflow posts but confused why I have this error:
Access to XMLHttpRequest at
'http://localhost:52852/signalr/negotiate?negotiateVersion=1' from
origin 'http://localhost:10843' 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.
Thanks for any help.
.WithOrigins("http://localhost:10843/")
Please remove trailing slash / from the end of your URL, like below.
.WithOrigins("http://localhost:10843")
Besides, please apply your CORS policy with app.UseCors("CorsPolicy"), like below.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//... other middleware ...
app.UseCors("CorsPolicy");
app.UseRouting();
//...
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapHub<AsteriskHub>("/signalr");
});
//...
}

.Net Core 2.1 CORS and Authorization with Firebase JWT

I'm following this blog post on authenticating with firebase with .net Core 2 https://blog.markvincze.com/secure-an-asp-net-core-api-with-firebase/
(I realise i'm using .net core 2.1 but thinking it must be similar)
I'm using a React Frontend with a .net core 2.1 WebApi Backend.
I am able to hit the controller no problem, however once I try to add the authentication to startup.cs I then get a:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at localhost:4000 (Reason: CORS request did not succeed)
Works totally fine up until that point
My request is coming from http://localhost:3000
UPDATES------------------------------------------------------------------
As a side note, this works when using POSTMAN. I can authenticate with Firebase AND hit the controller without a problem
Also works in chrome. Seems to be an issue with the firefox browser
My Implementation (After Successful Firebase Login Frontend)
Axios Request
axois
.get("https://localhost:4000/v1/picture", {
headers: {
accept: "application/json",
"Accept-Language": "en-US,en;q=0.8",
"Content-Type": `multipart/form-data;`,
Authorization: "Bearer " + localStorage.getItem("token")
//Is the above the correct way to pass a jwt to be authenticated backend? This is the full jwt returned by Firebase
}
})
Startup.cs
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader());
}
);
//https://blog.markvincze.com/secure-an-asp-net-core-api-with-firebase/
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://securetoken.google.com/mafirebaseapp";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "https://securetoken.google.com/mafirebaseapp",
ValidateAudience = true,
ValidAudience = "mafirebaseapp",
ValidateLifetime = true
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
...
...
app.UseCors("AllowSpecificOrigin");
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseMvc();
}
PictureController.cs
[Route("v1/picture")]
public class PictureController : Controller
{
[Authorize]
[HttpGet]
public IActionResult GetPicture()
{
return Ok("Hi");
}
}
I looked at another post which pointed out that the ordering of the methods made a difference so i don't think that's a problem.
Any help will be much appreciated!
Thanks!
You can try to use a specify a CORS policy for a specific action, just add [EnableCors("AllowSpecificOrigin")] to you action.
You can use this NuGet package to make it easy (Support AspNetCore >= 2.0)
Install-Package AspNetCore.Firebase.Authentication
In Startup.cs file
public void ConfigureServices(IServiceCollection services)
{
services.AddFirebaseAuthentication(Configuration["FirebaseAuthentication:Issuer"], Configuration["FirebaseAuthentication:Audience"]);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseAuthentication();
}
Just have to use [Authorize] attribute on your controllers to enforce authorization
Source: https://bitbucket.org/RAPHAEL_BICKEL/aspnetcore.firebase.authentication/src/master/

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'

My application is working fine in IE browser, But it's not working in Chrome browser due to CORS issue.
The issue is
Failed to load http://localhost:52487/api/Authentication/: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
I am using angular 2 in front-end and using Asp.net core 1.0 in back-end. I have tried
This is my startup code
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAll", p =>
{
p.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// Add framework services.
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<Data>(Configuration.GetSection("Data"));
services.Configure<COCSettings>(Configuration.GetSection("COCSettings"));
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
AppSettings.ConnectionString = Configuration["Data:DefaultConnectionString"];
// *If* you need access to generic IConfiguration this is **required**
services.AddSingleton<IConfiguration>(Configuration);
// Injecting repopsitories with interface
AddServices(services);
// Add Json options
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMiddleware(typeof(ErrorHandling));
app.UseMiddleware(typeof(GetNoCache));
app.UseCors("AllowAll");
app.UseMvc();
}
this is how I am calling the API from UI(angular) side
constructor(private http: Http) {
this.headers = new Headers();
this.headers.append('Accept', 'application/json');
}
GetMaintainCOC(FYONId) {
return this.http.get(this.apiUrl + 'GetCertificationofConformity?FYONId=' + FYONId, { withCredentials: true })
.map(responce => <any>responce.json())
.catch(error => {
return Observable.throw(error);
});
}
It is working, when I am calling AllowCredentials() inside of AddPolicy
services.AddCors(options =>
{
options.AddPolicy("AllowAll", p =>
{
p.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
I got this key of idea from
Access-Control-Allow-Origin: "*" not allowed when credentials flag is true, but there is no Access-Control-Allow-Credentials header
What I understood
I am using { withCredentials: true } in angular http service call. So I guess I should use AllowCredentials() policy in CORS service.
Well you appear to have it solved, but here's the simple answer.
If you set the withCredentials flag in the request definition, cookies etc. will be passed in the request. Otherwise they won't be passed.
If your server returns any Set-Cookie response headers, then you must also return the Access-Control-Allow-Credentials: true response header, otherwise the cookies will not be created on the client. And if you're doing that, you need to also specify the EXACT origin in the Access-Control-Allow-Origin response header, since Access-Control-Allow-Origin: * is not compatible with credentials.
So do this:
Pass withCredentials in request
Pass Access-Control-Allow-Origin: <value-of-Origin-request-header> response header
Pass Access-Control-Allow-Credentials: true response header

Categories

Resources