ASP.NET Core with windows auth always gives 403 - asp.net-core-3.1

Using Visual Studio 2019 I created a .NET Core API, and I told it to use windows authentication. I then edited the WeatherForecastController.cs file and added a simple post route:
[HttpPost]
public ActionResult Foo()
{
return NoContent();
}
If I then run the app locally, via VS, and try to POST to that, passing NTLM credentials, it still gives a forbidden (403) error. I've seen multiple possible solutions to this from googling but nothing seems to work.
In my Startup.cs I have this
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
and in the ConfigureServices I added
services.AddAuthentication(IISDefaults.AuthenticationScheme);

Well, this had nothing to do with authentication. Postman was returning a 403 no matter what. I finally dropped down to doing it manually via curl and found the server was throwing an exception in a completely unrelated area. Fixing that fixed the issue.

Related

Flutter web call to .net core api error 'Access-Control-Allow-Origin'

Flutter web call to .net core api error 'Access-Control-Allow-Origin'
Help me i want flutter-Web call api
i use .net core api
how to allow 'Access-Control-Allow-Origin' on .net core api
code in Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace test_api
{
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
// app.UseResponseCaching();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Flutter Web error
The error means that your api (this unrelated to flutter) has blocked the request due to CORS policy. CORS blocks request from other IP. So you pretty much have to enable it.
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
Follow the guidelines and the answers here. Try to search for your specific asp.net core version. Furhtermore the EnableCors attribute on top of the controllers is required for this to work. Your allow only specific origins simply does not specify any kind of hosts. It specifies only the name of the policy and also you havent used in the services

.Net Core Web API Bearer The issuer is invalid

I have written a Blazor WASM app based on the latest Microsoft template. In development mode it all works great but after publishing it to Azure App Service I randomly get a 401 unauthorised when calling the API, looking at the returned headers I get
WWW-Authenticate: Bearer error="invalid_token", error_description="The issuer 'https://*domain*.azurewebsites.net' is invalid"
This is when the client is using the https://domain.azurewebsites.net client. So it matches the web API.
I also have a custom domain attached to the app service, this means there is also https://www.domain.co.uk and https://domain.co.uk both are SSL'd.
I have checked the JWT token and it contains the correct URL for the version of the website I am calling.
Sometimes everything works but 60% of the time it allows the user to login and then fails on the API calls. I can't seem to track it to 1 domain name or pattern like expired logins. If you log out and then log back in, it doesn't clear the issue.
The configure looks like this
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
Any help or hints in the right direction is appreciated
Cheers
Dave
In my case it was caused by Linux environment of App Service. Now documentation has a clear note on that:
For Azure App Service deployments on Linux, specify the issuer explicitly in Startup.ConfigureServices.
This is how I set it:
services.Configure<JwtBearerOptions>(
IdentityServerJwtConstants.IdentityServerJwtBearerScheme,
options =>
{
options.Authority = "https://my-site.azurewebsites.net";
#if DEBUG
options.Authority = "https://localhost:5001";
#endif
});

Unity WebClient SSL Timeout

I'm working on a Unity project that is reliyng on fetching data from a web API I set up on a public webserver. The server is currently set to self-signed ssl and requires the client to send certification to be able to read the data, if the client fails to send the cert the website returns with "403 forbidden".
I've tested this in the browser and postman and everything works fine.
I've also tested the exact same function in a pure visual studio project and it worked like a charm.
However, when I try this function in Unity I am met with the WebException "The request timed out
".
The way I'm currently doing it is via a WebClient, with an overrided method of WebRequest:
private void Connect()
{
ServicePointManager.CheckCertificateRevocationList = false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback += ignoreCertCallback;
ServicePointManager.Expect100Continue = true;
using (var wc = new CertificateWebClient())
{
try
{
var responseBytes = wc.DownloadString(url);
Debug.Log(responseBytes);
Debug.Log(wc.ResponseHeaders);
}
catch (WebException e)
{
Debug.Log(e.ToString());
}
}
}
Override of WebRequest:
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
X509Certificate2 certificate = new X509Certificate2(#"C:\temp\ClientCert.pfx", "password");
request.ServerCertificateValidationCallback = delegate (System.Object obj, X509Certificate X509certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
{
return true;
};
Debug.Log(request.RequestUri);
(request as HttpWebRequest).ClientCertificates.Add(certificate);
request.Timeout = 2000;
return request;
}
Important to note is that I've tried the exact same functions inside of Unity with the "client.badssl.com" and their cert, and that also worked like a charm, returning the correct error codes when no cert is sent and everything and If I turn off client certification on my website, everything also works like charm...
From What I understand, It might be Mono that might be the problem as the certification is self-signed and not from a verified CA... But i've not been able to find a workaround... so any help would be great
What are your BG settings? I mean: is it on AWS? Express/NodeJS? WebGL? I am facing the same issue but when testing locally it works like a charm
I would suggest: to check if it is an infrastructure problem you might want to create a certificate for your domain (eg 'goodboy.mytest.io") that is certified from some free SSL providers (I can say LetsEncrypt just for testing) and launch a local server that's using that certificate, then go in your "hosts" file (depending on OS that you are currently running) and mock your localhost as "goodboy.mytest.io", so you can check if connecting to that domain everything goes fine without additional layers (usually placed between connection "bouncing" on web)
I'm following up this too

Custom Authentication - Spring boot 403 forbidden error

I was trying it implement custom authentication, Authentication works fine, but have problems with Authorization. I am using JWT tokens, Any API I try to access it throwing me a 403 forbidden error. I am not sure what is wrong. I have the full source code in github. https://github.com/vivdso/SpringAuthentication, Spring boot magic is not working on this. Any pointers are apperciated.
Using MongoDb as my repository to store user accounts and roles.
InMemory Authentication is working fine, but Custom Authentication always returs 403, Below is my I extended WebSecurityConfigurerAdapter
#Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
// authenticationManagerBuilder.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
// authenticationManagerBuilder.inMemoryAuthentication().withUser("user").password("user").roles("USER");
authenticationManagerBuilder.authenticationProvider(getCustomAuthenticationProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/customer").hasAuthority("ADMIN")
.antMatchers(HttpMethod.GET, "/order").hasAuthority("USER").and()
.csrf().disable();
}
#Bean
protected CustomAuthenticationProvider getCustomAuthenticationProvider(){
return new CustomAuthenticationProvider();
}
I don't have any custom implementation for authorization.
The issue is resolved, I have updated Github repository. The spring boot security was working fine, the issue was the roles assigned to the user collection was a Json string object (e.g. {"role":"ROLE_ADMIN"}) instead of sting object "ROLE_ADMIN".
Thanks

Connecting Aurelia with backend API

Context: I'm starting a new project for my company. It's been many years since I've done some web development and decided to build it using the latest platforms (so I'm a still new to all of this).
Current stack:
Aurelia frontend (running on localhost:9000)
Backend REST API using ExpressJS (running on localhost:8000)
PostGreSQL database running on AWS, providing data for the backend
Question: I can't seem to connect my frontend with my backend properly.
Here is my code:
import {inject} from "aurelia-framework";
import {HttpClient} from "aurelia-http-client";
#inject(HttpClient)
export class Login {
constructor(httpClient){
this.http = httpClient;
}
signIn() {
const url = 'http://localhost:8000/api/user/demo/test';
this.http
.get(url)
.then(data => {
console.log("data");
console.log(data);
})
.catch(error => {
console.log('Error getting ' + url);
console.log(error);
});
};
}
This always end up in the catch block, with a "response: ProgressEvent"
If I put the url in the browser I get a proper JSON:
{"status":"success","data":[],"message":"Retrieved ALL users"}
The code above only works for 'local' content, i.e. localhost:9000. As soon as I need content from somewhere else I get this error. What am I missing?
I think that CORS is not allowing you to access localhost:8000 from localhost:9000. To solve this, you should enable your ExpressJS server to accept CORS requests from localhost:9000 (or all hosts using a wildcard "*").
Look into these resources:
https://enable-cors.org/server_expressjs.html
https://github.com/expressjs/cors
Or search Google for 'expressJS cors'.