Make requests to unpublished ASP.NET Core Web API for debugging - asp.net-core-webapi

I'm developing an ASP.NET Core-based web app, but I'm currently in the debugging phase. This is also my very first time working with .NET Core.
I want to do application-level debugging and testing by making requests to the developed ASP.NET Core Web API from the frontend.
Can I publish the API somewhere for free for now to debug and test the entire web app?

Can I publish the API somewhere for free for now to debug and test the
entire web app?
You don't need to publish your API to test from your frontend app. You can can do that running your Web Api project locally therefore, setting debugger pointer to any break point.
Example Debugging Using Swagger In Localhost:
You could have a look on following example, I am testing the Web API project running on local environment using Swagger. I am sending request to my desired API and debugging at the same time whether the response expected. See below screenshot:
What if you encounter "Origin 'localhost:<port>' has been blocked by CORS policy" Error :
You could simply handel above error by following ways:
If you want to allow all request Endpoint:
builder.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
Note: Above code resolve your CORS error and allow all coming request from your frontend app
If you want to allow Certain request Endpoint:
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("http://localhost:5094");
});
});
Then use as below:
app.UseCors(MyAllowSpecificOrigins);
Note: Above code allow the request only from the endpoint containing http://localhost:5094. URL
If you sitll need further information you could refer to our official document here

Related

Using Microsoft Authentication Library with External Providers (ASP.NET 6)

I have an Azure App Service developed in .NET 6. I wish to authenticate users against several providers (Azure AD, Google, etc). Upon following the (I think) accurate tutorial I was able to authenticate against Microsoft accounts using MSAL with the following code:
var builder = WebApplication.CreateBuilder(args);
// Managed identity credential
var credential = new DefaultAzureCredential();
// Add key vault for initial access
builder.Configuration.AddAzureKeyVault(new Uri(builder.Configuration.GetValue<string>("Azure:VaultUri")), credential);
// Integrate key vault into Azure app config
builder.Configuration.AddAzureAppConfiguration(options =>
{
// Load config string from vault
var configConnection = builder.Configuration.GetValue<string>("config");
// Connect to config
options.Connect(configConnection);
options.ConfigureKeyVault(kv => kv.SetCredential(credential));
});
// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// CUSTOM DI
builder.Services.AddSingleton<IDatabaseRepo, CosmosDatabaseRepo>();
// Build
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();
The protected controller method is simply decorated with [Authorize].
That works great for Microsoft accounts. However, every attempt to integrate Google into this flow fails. I've done the following:
Follow various example utilizing the Microsoft.AspNetCore.Authentication.Google package. I added AddGoogle method with the client id and secret set. This results in an invalid token error.
The OAuth process works (using Postman) and provides both an access token and id token. But:
The access token fails with invalid_token
The open id token fails saying invalid_token and invalid signature.
If I remove AddMicrosoftIdentityWebApi and only use the AddGoogle method then I always receive a 500 Internal Server Error indicating an auth scheme was not defined. Doesn't matter where I define it- whether in AddAuthorization or decorated on the controller's Authorize attribute.
Attempted using manual JWT validation. This seems problematic because:
It also results in the 500 error whatever I try.
It's not supposed to be required if I understand the packages correctly.
ALSO:
The Google client id has been added to my App Service as an identity provider with the associated App (client) ID.
There's 38974 tutorials out there and none seem to point in the right direction/don't address this issue. Any and all guidance is appreciated.

ASP.NET Core with SPA, how to handle invalid routes on root?

Our ASP.NET Core with Single Page App as client, is hosted on Azure Web Service. We noticed that all environments and deployment slots get an occasional POST action request on /index.html. In the ASP.NET Core application, http requests to the root is routed to the SPA application files through configuring the SPA static files provider middleware:
services.AddSpaStaticFiles(configuration => {
configuration.RootPath = "ClientApp/dist/ClientApp";
});
When these POST actions are requested on /index.html, the application will throw an exception:
The SPA default page middleware could not return the default page '/index.html' because it was not found, and no other middleware handled the request.
In turn, the exception causes issues in our performance monitoring as the exceptions are not caught/handled anywhere. Especially if this happens multiple times in a short time.
Question: What can we configure to either immediately return 403 or similar response, or setup such that we at least catch the exception?
The SPA default page middleware could not return the default page '/index.html' because it was not found, and no other middleware handled the request.
This problem arises when the wwwroot folder is not copied in build or publishing the project.
In either cases, both commands don't copy the wwwroot folder.
As a workaround, you can add this target to your project file:
<Target Name="AddGeneratedContentItems" BeforeTargets="AssignTargetPaths" DependsOnTargets="PrepareForPublish">
<ItemGroup>
<Content Include="wwwroot/**" CopyToPublishDirectory="PreserveNewest" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder);#(Content)" />
</ItemGroup>
</Target>
What can we configure to either immediately return 403 or similar response, or setup such that we at least catch the exception?
Another reason can be , if your controller route attribute don't exactly match the request URL, then this type of error occurs.
Please refer the similar issue found in GitHub.
I have found a solution in an issue case on GitHub. This solution will call on the middleware only when the request meets the correct condition: when it's a GET request.
In the Configure method of the Startup class:
app.UseWhen(context => HttpMethods.IsGet(context.Request.Method), builder =>
{
builder.UseSpa(spa =>
{
// ... add any option you intend to use for the Spa middleware
});
});

Microsoft Identity Web invalid token in Blazor WASM

I am just finished trying to implement this: https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore-v2/tree/master/1.%20Desktop%20app%20calls%20Web%20API
Instead of using a WPF application I am using a Blazor WASM client.
I added the token to the outgoing requests to my .net core API but I always get a 401.
Blazor authenticates well and gets the token back, seems to be working fine but:
the audience has the wrong GUID
"scp" (scope) is missing, hence the token being invalid for usage
If I run the sample from the link mentioned above and decode the token I can see a correct AUD & SCP in the token. So it's probably something with my configuration in Blazor?
Config in Blazor
// AD authentication
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add("api://xxx-xxxx-xxxx-xxxx/access_as_user");
});
builder.Services
.AddHttpClient<IApiClient, ApiClient>(client => client.BaseAddress = _baseUri)
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
Response
Bearer error="invalid_token", error_description="The audience '63ee4227-xxxx-xxxx-xxxx' is invalid"
The audience GUID is the clientID of my Blazor app registration
Code in Startup.cs
...
services.AddProtectedWebApi(Configuration)
.AddInMemoryTokenCaches();
...
...
app.UseAuthentication();
app.UseAuthorization();
...
Any idea what could have been wrong?
When I was learning to use Blazor WebAssembly I followed this tutorial which does something very similar and it may be easier for you to implement as you don't have to try and convert any codefrom WPF.
However, one thing to try is to change this:
options.ProviderOptions.DefaultAccessTokenScopes.Add("api://xxx-xxxx-xxxx-xxxx/access_as_user");
To this:
options.ProviderOptions.DefaultAccessTokenScopes.Add("xxx-xxxx-xxxx-xxxx/access_as_user");
In my application I am calling two API endpoints, one is hosted within the same domain as the Blazor application and the other is on a separate domain. When requesting a token for the external domain the api:// prefix must be used. However, for the same domain it must be excluded.

SignalR client server connected but not pushing data to client on production server

I have developed a web app using SignalR and its working perfectly on my development server. But for some unknown reasons its not working on production server.
I have done some tests:
$.connection.hub.start().done(function () {
console.log('started');
});
This always gives my 'started' in console as expected. So client and server are connected. But when I send any data like login credentials, i am not receiving anything back.
Here is the connection frames image. As you can see client is sending data to server but not receiving anything in response.
public override Task OnConnected()
{
Clients.All.Listen("Connected to HUB");
}
CLIENT SIDE Listen method:
hub.client.listen = function (response) {
console.log('Listen', response);
}
There is a Listen method which I use to debug. This doesn't print anything. So signalr client server are not connecting.
EDIT:
Reported issue here: https://github.com/SignalR/SignalR/issues/4279 if this helps.
EDIT2:
My webapp is a Vue js 2 app. I compiled using vue-cli and uploaded to server. My signalr.js file is copied from an ASP.NET MVC project.
I made a Test ASP.NET MVC 5 app with SignalR 2.4 and I was able to communicate on live server.
https://learn.microsoft.com/en-us/aspnet/signalr/overview/testing-and-debugging/troubleshooting
IIS issues
This section contains issues with Internet Information Services.
SignalR works on Visual Studio development server, but not in IIS
SignalR is supported on IIS 7.0 and 7.5, but support for extensionless URLs must be added. To add support for extensionless
URLs, see https://support.microsoft.com/kb/980368
SignalR requires ASP.NET to be installed on the server (ASP.NET is not installed on IIS by default). To install ASP.NET, see ASP.NET
Downloads.

Insecure CORS request sent to ASP.NET Core RC2 API App in Azure fails

I created a new asp.net core rc2 web api application as the official docs at https://docs.asp.net/en/latest/security/cors.html?highlight=cors.
I was only able to use the "Microsoft.AspNetCore.Cors 1.0.0-rc2-final" package and not the "Microsoft.AspNet.Cors" as per the article.
Then, I am able to configure Cors for any origin. I also created another asp.net core app as a simple client to test CORS. When I deployed both apps on my machine this worked as expected. Without CORS configured my client app is disallowed access but with it enabled it works. However when I publish to Azure I get the classic "Origin 'http://Gonzigonz.azurewebsites.net' is therefore not allowed access."
I also tried removing the Web API CORS configuration I had just added and instead using the Azure App Service CORS feature from the Azure portal but this didn't work either.
I have my code up on Github:
https://github.com/gonzigonz/SampleApp-Backend-ASP.NET-Core-RC2
You can view live versions on Azure:
Web API: http://gonzigonz-api.azurewebsites.net
CORS Test Client: http://gonzigonz.azurewebsites.net
It's currently configured using via the Web API nuget package and not the Azure feature.
UPDATE: I found that it does work from outside my corporate office. I tested this with my iPad... when connected to the office WiFi it doesn't work but when I switch off WiFi and just use my cellular data it works! I even created a new Azure VM just to double test and it works there!
UPDATE 2: It does work from within my corporate office using fiddler... Could the issue be with my client and its AJAX request below?
(jquery-1.11.2)
$.ajax({ url: url, cache: false }).always(showResponse);
As I see you are setting up CORS this way here:
public void ConfigureServices(IServiceCollection services)
{
// Add Cors services.
services.AddCors();
...
}
public void Configure(IApplicationBuilder app)
app.UseCors(builder =>
builder.AllowAnyOrigin()
);
What works for me is this (localhost):
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()));
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseCors("AllowAll");
}
}
GitHub
Post
It works if I send my request over HTTPS.
I noticed the issue when I tried my ajax request using Plunker and saw the following console error:
VM275 jquery.min.js:4
Mixed Content: The page at 'https://plnkr.co/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://gonzigonz-api.azurewebsites.net/api/todo?_=1463710805503'.
This request has been blocked; the content must be served over HTTPS.
Sending the request using HTTPS solved the problem, although I still don't know if this is a CORS configuration or Azure restriction that causes it to fail when using the insecure endpoint.

Resources