I am using minimal APIs and I am using OpenAPI support (Swagger) for my .net 6 app.
The middle part of the launchSettings.json file that is auto generated looks like:
"profiles": {
"WebApplication1": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7087;http://localhost:5285",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
My question is how do set the Swagger settings in C# code to match how Swagger is being set in that json document?
This is the auto generated Program class:
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthorization();
// 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.UseHttpsRedirection();
app.UseAuthorization();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", (HttpContext httpContext) =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = summaries[Random.Shared.Next(summaries.Length)]
})
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast");
app.Run();
}
}
How can this be done?
See this post to get you started, long story short is to look up the existing calls to specify what is needed.
A clean way to add Swagger to ASP.NET Core application
Related
So i built a asp.net core web api app on .NET 5.0 , it works completely fine on my machine . Today i deployed it on elastic beanstalk AWS using the aws tools .
It doesn't show any error while deploying and stuff. it just returns me code 404 not found.
Here is my code.
using Startup.cs
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using ShopApiNet5.Authentication;
using ShopApiNet5.Models;
namespace ShopApiNet5
{
public class Startup
{
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();
services.AddDbContext<ModelContext>(opt => opt.UseInMemoryDatabase("ModelDB"));
services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ModelContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = Configuration["JWT:ValidAudience"],
ValidIssuer = Configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
};
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "ShopApi", Version = "V1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "TodoApi v1"));
}
//app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Here is my launchsettings.json
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"launchUrl": "swagger",
"iisExpress": {
"applicationUrl": "http://shopapinetsm.us-east-1.elasticbeanstalk.com/",
"sslPort": 44352
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"ShopApiNet5": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchUrl": "swagger",
//"applicationUrl": "https://localhost:5001;http://localhost:5000",
"applicationUrl": "http://shopapinetsm.us-east-1.elasticbeanstalk.com/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
}
}
}
and here is the link to view the latest log
https://elasticbeanstalk-us-east-1-676277819872.s3.amazonaws.com/resources/environments/logs/tail/e-afp9eu4yxa/i-00e8df513fd738529/TailLogs-1636655753712.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20211111T183555Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86399&X-Amz-Credential=AKIAIOUOORMVUTXOJUHQ%2F20211111%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=af742a78702d5d2e8131fe07d96e15b83449ffcbdacb0912a15acec32f371e3e
Please help me 🥲
So i just made a new app without https enabling, and it just worked as i remember.
I created 3 separate projects, web api project, an web mvc project, and a asp.net core app. I am using IdentityServer4 with asp.net core identity. I have a project solution id that has the information of the TestUsers. On the line RedirectUris = {"https://localhost:5444/signin-oidc"}, I am redirecting it to the project WeatherMVC. The launchsettings.json on all three files are correct and so is the RedirectUris is correct. Is there something that I am not doing correctly that is causing me to receive this message?
weatherapi project:
----startup.cs:
namespace weatherapi
{
public class Startup
{
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.AddAuthentication("Bearer")
.AddIdentityServerAuthentication("Bearer", options =>
{
options.ApiName = "weatherapi";
options.Authority = "https://localhost:5443";
});
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "weatherapi", Version = "v1" });
});
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "weatherapi v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
----launchsettings.json:
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:52575",
"sslPort": 44354
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"weatherapi": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"hotReloadProfile": "aspnetcore",
"launchUrl": "swagger",
"applicationUrl": "https://localhost:5445;http://localhost:5002",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
WeatherMVC Project:
----launchsettings.json:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:65206",
"sslPort": 44398
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"WeatherMVC": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": "true",
"applicationUrl": "https://localhost:5444;http://localhost:5001"
}
}
}
These two projects are under one solution which I perform a multiple startup projects.
On the other project, named id...
id project:
----launchsettings.json
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:19916",
"sslPort": 44341
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"id": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"hotReloadProfile": "aspnetcore",
"dotnetRunMessages": "true",
"applicationUrl": "https://localhost:5443;http://localhost:5000"
}
}
}
inside of this class below Config.cs, I have the code where it will perform the Redirect_uri:
public static IEnumerable<Client> Clients =>
new[]
{
// m2m client credentials flow client
new Client
{
ClientId = "m2m.client",
ClientName = "Client Credentials Client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = {new Secret("SuperSecretPassword".Sha256())},
AllowedScopes = {"weatherapi.read", "weatherapi.write"}
},
// interactive client using code flow + pkce
new Client
{
ClientId = "interactive",
ClientSecrets = {new Secret("SuperSecretPassword".Sha256())},
AllowedGrantTypes = GrantTypes.Code,
RedirectUris = {"https://localhost:5444/signin-oidc"},
FrontChannelLogoutUri = "https://localhost:5444/signout-oidc",
PostLogoutRedirectUris = {"https://localhost:5444/signout-callback-oidc"},
AllowOfflineAccess = true,
AllowedScopes = {"openid", "profile", "weatherapi.read"},
RequirePkce = true,
RequireConsent = true,
AllowPlainTextPkce = false
},
};
}
}
----startup.cs:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddInMemoryClients(Config.Clients)
.AddInMemoryIdentityResources(Config.IdentityResources)
.AddInMemoryApiResources(Config.ApiResources)
.AddInMemoryApiScopes(Config.ApiScopes)
.AddTestUsers(Config.Users)
.AddDeveloperSigningCredential();
services.AddControllersWithViews();
}
// 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.UseStaticFiles();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
}
}
UPDATE
After adding the debugger in program.cs as suggested:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(builder =>
{
builder.SetMinimumLevel(LogLevel.Debug);
builder.AddFilter("IdentityServer4", LogLevel.Debug);
});
I finally noticed that it is calling the redirect uri that belongs to the project named WeatherMVC using it's sslPort: 44398. Please see the launchsettings.json for that weathermvc projcect. Can't seem to understand why it is redirecting that URI if I do not have it set to that.
WeatherApi is a client to IdentityServer and when it authenticates it tells IdentityServer its redirect uri. IdentityServer checks against its allowed redirect uris and redirects if it finds a match.
This code specifies a list of VALID redirect uris not THE redirect uri.
RedirectUris = {"https://localhost:5444/signin-oidc"},
You have IISExpress and also Kestrel setup in your launchsettings.json and I think your WeatherApi project is just using the first setting that it finds as the redirect uri.
Some possible solutions are:
Add the other uri for WeatherApi to the allowed uris e.g.
RedirectUris = {
"https://localhost:5444/signin-oidc", "https://localhost:44398/signin-oidc"},
You can also change Kestrel in launchsettings.json for WeatherApi to use the same ports
"applicationUrl": "https://localhost:44398;http://localhost:65206"
I think your project is based on this tutorial. This could be helpful for people to follow the steps involved. It also has a link to the code.
if anyone have similar problem with database. Check you uri in table.ClientRedirectUris
I have faced the same error because I have missed added URLs with "http" whereas it requires "https". Confirm that you have added URLs with "https" and not the "http".
public static class RedirectUrls
{
public const string WebSigninURI = "https://localhost:44332/signin-oidc";
public const string WebSignOutURI = "https://localhost:44332/signout-callback-oidc";
}
This error does not happen when I test the application in development mode on my PC, but on the remote server it does. The app verify if user exist and the password requirements, but if I use a password like "1234" the app give me this error, but it does happen if I use a password like "#juan147-lop4s785"
This is the launchSettings.json file
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:63322",
"sslPort": 44361
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
//"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"UniJobs": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
//"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
and this us mi Startup.cs file
namespace UniJobs
{
public class Startup
{
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.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<Usuarios>(options => options.SignIn.RequireConfirmedAccount = true)
//Incluye los roles de los usuarios a la app
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
It's likely that when creating a user, you're not checking whether it was successful or not and therefore when your "weak password" doesn't meet the default Identity options, it fails to create the user and then the database complains about the missing foreign key, resulting in your error.
Have a look here for the default Identity password options and how to customise them.
If you're using UserManager to create the user, you just need to check if it there were any errors and respond accordingly, something like the below:
var result = await UserManager.CreateAsync(user, password);
if(!result.Succeeded)
return result.Errors.Select(x => x.Description);
var roleResult = await UserManager.AddToRoleAsync(user, "User");
if (!roleResult.Succeeded)
return roleResult.Errors.Select(x => x.Description);
I have a problem with my ASP.NET Core Web Service.
I needed JWT for Authentication in my Angular project. That's why I made a service where the user needs to be checked, if he is authorized. I made it with .NET Core, because I have IIS Server.
When I run it locally with "dotnet run" I can make get or put requests locally. I tested it also in YARC plugin of Google Chrome by making a POST request with Payload (JSON with 2 key value pairs).
I uploaded the service in IIS Server, started it, gave the url (this time with the domain of server where IIS located) on YARC plugin in my local maschine again for POST request with the same payload. It gives me 404-Not Found Error.
Functional local url is: http://localhost:5000/api/auth/login
URL for IIS: http://myIISMachine:7471/api/auth/login (Port number is in the launchSettings.json file as well)
ConfigureServices function in my Startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "http://localhost:5000",
ValidAudience = "http://localhost:5000",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MySecretKey"))
};
});
services.AddCors(options =>
{
options.AddPolicy("EnableCORS", builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build();
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
And Configure function:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("EnableCORS");
app.UseAuthentication();
//app.UseHttpsRedirection();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "api/{controller=Home}/{action=Index}/{id?}");
});
}
launchSettings.json file:
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:7471",
"sslPort": 44365
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"webapplication": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
What am I doing here wrong? Or maybe is this something to do with the settings in IIS server? Could you help me please?
I have a website in ASP .NET Core Mvc 2.0 published in Azure. It worked fine until today when I updated the website. The update consist in changing the keys and passwords because the website have social logins providers. After updates and executing the website it gives me Http 500 error in browser.
Startup file
public class Startup
{
private IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
var users = new Dictionary<string, string> { { "Admin", "Admin#1234" } };
services.AddSingleton<IUserService>(new UserService(users));
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
})
.AddTwitter(options =>
{
options.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];
options.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];
})
.AddMicrosoftAccount(options =>
{
options.ClientId = Configuration["Authentication:Microsoft:ApplicationId"];
options.ClientSecret = Configuration["Authentication:Microsoft:Password"];
})
.AddGoogle(options =>
{
options.ClientId = Configuration["Authentication:Google:ClientId"];
options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
})
.AddCookie(options =>
{
options.LoginPath = "/auth/signin";
});
}
// 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();
}
app.UseRewriter(new Microsoft.AspNetCore.Rewrite.RewriteOptions().AddRedirectToHttps(301, 44301));
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc();
}
}
launchSettings.json file
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "https://localhost:44301/",
"sslPort": 44301
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
},
"IdentityApp": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:44301/"
}
}
}
I'm not sure what is going on but I suspect that is a https problem. There is no error in the code and after debugging the code there is no error.
I'm stuck someone can help please.
Thanks in advance.