I have a project with Identity Server 4 in netcore2.2
Now I want to migrate to netcore3.0
I have install sdk hosting bundle and so on...
Change version sdk in appsetting change target framework
If I compile tell me ok but...
my old startup.cs have in ConfigureService this call:
services.AddMvc(options => options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())))
.AddJsonOptions(options =>
{
options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
and netcore 3.0 tell me that options.SerializerSettings.DefaultValueHandling
and options.SerializerSettings.NullValueHandling
they are not recognized as valid
so I take out... another problem is that when with debug see the different step the breakpoint inside this call doesn't enter
'
services.AddDbContext<DBPLATFORMContext>(options =>
{
options.UseSqlServer(connectionString,
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(maxRetryCount: 5,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null);
});
});
and when I go to start my indexpage
in Configure
by
'
app.Use(async (context, next) => {
await next();
if (context.Response.StatusCode == 404 &&
!Path.HasExtension(context.Request.Path.Value) &&
!context.Request.Path.Value.StartsWith("/api/"))
{
context.Request.Path = "/index.html";
await next();
});
variable context give me response 404 and contenttype is null
Could you help me? Thanks
Related
There are API project and Worker project in the solution. The API project is written in net5.0 Microsoft.NET.Sdk.Web.
In Startup.cs
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); // for enum as strings
});
This code block is available in Startup.cs.
I also want to add these JsonOptions to net5.0 Worker project but Controller and Startup.cs are not available in worker project. How can i add?
I tried this
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
and this
services.AddMvc().AddJsonOptions(o =>
{
o.JsonSerializerOptions.PropertyNamingPolicy = null;
o.JsonSerializerOptions.DictionaryKeyPolicy = null;
});
but not works for me
AddJsonOptions are only used to bind/send json via endpoints, worker project does not expose any endpoints (at least by default), so there is no point adding them unless you resolve IOptions<JsonOptions> somewhere in the code directly. In this case you can always call Configure:
services.Configure<JsonOptions>(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); // for enum as strings
});
I used the accepted answer to How to check user-agent in ASP.NET Core health check calls (MapHealthChecks)? , with one difference in requirement:
My application is not using App services authentication and authorization. Therefore, I needed to allow anonymous access for healthcheck as per documentation.
Here are changes to Startup.cs
//other services
services.AddHttpContextAccessor();
services.AddScoped<IAuthorizationHandler, UserAgentAuthorizationHandler>();
services.AddHealthChecks()
.AddCheck<HealthCheckFoo>("health_check_foo")
.AddCheck<HealthCheckBar>("health_check_bar");
//other services.AddAuthorization
services.AddAuthorization(options =>
{
options.AddPolicy("HealthCheckPolicy", builder =>
{
builder.AddRequirements(new UserAgentRequirement("HealthCheck/1.0"));
});
});
//...
app.UseEndpoints(endpoints =>
{
//other endpoints...
endpoints.MapHealthChecks("/health", new HealthCheckOptions { AllowCachingResponses = false })
.RequireAuthorization("HealthCheckPolicy");
.WithMetadata(new AllowAnonymousAttribute());
My expectation is that when testing locally, https://localhost:5001/health return an error. It does not.
It looks as your startup class has a mistake on the endpoints.MapHealthChecks adds a RequireAuthorization but as the same time you also add the AllowAnonymousAttribute.
Try with:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("/health", new HealthCheckOptions()
{
AllowCachingResponses = false,
})
.RequireAuthorization("HealthCheckPolicy");
});
I'm getting this
No web page was found for the web address: https://limbu.azurewebsites.net/
Everything worked fine in development but after publishing I get this error.
I can navigate to Views by typing in url but not the index page. I'm also not able to perform Register and login functions from controller in published website.
My Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production")
{
services.Configure<IServiceProvider>(options => {
options.GetService<AppDbContext>().Database.Migrate();
}).AddDbContextPool<AppDbContext>(options => {
options.UseSqlServer(_config.GetConnectionString("AzureSqlConnection"));
//options.EnableSensitiveDataLogging(true);
});
}
else
{
services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(_config.GetConnectionString("Connection")));
}
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.SignIn.RequireConfirmedEmail = true;
}).AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
services.AddTransient<IMailService, SendGridMailService>();
services.AddHostedService<TimedHostedServices>();
services.AddScoped<IGetGlobalCovidData, GetGlobalCovidData>();
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
}).AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
//ServicePointManager.ServerCertificateValidationCallback += //This code is security risk as it validates all certificates
// (sender, certificate, chain, errors) => //Not to be used for production and used this instance as I trust the
// { //The site I'm pulling data from
// return errors == SslPolicyErrors.None;
// };
//services.AddLogging(loggingBuilder => { //This code is security risk as it displays all sensitive data
// loggingBuilder.AddConsole() //Not recommended for production
// .AddFilter(DbLoggerCategory.Database.Command.Name, LogLevel.Information);
// loggingBuilder.AddDebug();
//});
}
// 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();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapDefaultControllerRoute();
});
}
Please advise me on what I should provide for debugging.
my .cshtml build action is -content and donotcopy
.cs build action is -c# compiler and donotcopy
For the users who are getting the same issue, There could be different root causes for 404 error messages. Sub-status codes will help you understand the issue better.
You may check whether the site files are deployed correctly or not through Kudu Console. Also, suggest you Enable diagnostics logging for web apps in Azure App Service incase if you haven’t enabled earlier to check the complete error details and root cause.
I am creating a login server using Identityserver4. I am using ASP.net core 3.1 for functionality, and angular 9 project for serving static files for login/registeration screens. The angular project is being served from within the .netcore project's wwwroot folder.
For making sure that my angular routes work properly along with the controller routes, I have added the following in my Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(Constants.Constants.Policy);
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseIdentityServer();
app.UseWhen(x => !x.Request.Path.Value.StartsWith("/Account"), builder =>
{
builder.Use(async (context, next) => {
await next();
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/index.html";
await next();
}
})
.UseDefaultFiles(new DefaultFilesOptions { DefaultFileNames = new List<string>{"index.html"}})
.UseStaticFiles();
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Account}/{action=Login}/{id?}");
});
}
This ensures that when url contains http://localhost:port/Account/Login It will be served via controller route. Rest every other URL path will be served via angular.
The problem arises when the client applications try to access the http://localhost:port/.well-known/openid-configuration url to get discovery documents. Since, the URL does not start with "Account", it is being served via angular i.e, it gets redirected to the index.html page.
How do I add the .well-known/openid-configuration route to my Startup.cs so that it returns the discovery document?
The error I get when accessing IdentityServer from my client app is
The error I get on IdentityServer webpage is
I had to add an exception to route /.well-known along with /Account
app.UseWhen(x => !x.Request.Path.Value.StartsWith("/Account") && !x.Request.Path.Value.StartsWith("/.well-known/openid-configuration") , builder =>
{
builder.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/index.html";
await next();
}
})
.UseDefaultFiles(new DefaultFilesOptions { DefaultFileNames = new List<string> { "index.html" } })
.UseStaticFiles();
});
I have an auth policy configured in startup.cs
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", policy => policy
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
and I am using this in an attribute on an api controller:
[Authorize("Bearer")]
When I run the debugger in VS code, I get an exception :
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HL14EICAK26S": An unhandled exception was thrown by the application.
System.InvalidOperationException: The AuthorizationPolicy named: 'Bearer' was not found.
at Microsoft.AspNetCore.Authorization.AuthorizationPolicy.<CombineAsync>d__9.MoveNext()
When I run the program via dotnet run, I don't get this exception and it's able to pick up on the authorization attribute.
Why is this happening?
Cleaned, restored and rebuilt the project ... and it magically worked again....
I needed to add the following to get everything to work in my project. Here is Startup.cs
//Authentication
services.AddAuthentication()
.AddScheme<AuthOptions1, AuthenticationHandler1>("Scheme1", opt => { })
.AddScheme<AuthOptions2, AuthenticationHandler2>("Scheme2", opt => { });
//Authorization
services.AddAuthorization(opt =>
{
opt.AddPolicy("Policy1", policy =>
{
policy.AddAuthenticationSchemes("Scheme1");
policy.RequireAuthenticatedUser();
});
opt.AddPolicy("Policy2", policy =>
{
policy.AddAuthenticationSchemes("Scheme2");
policy.RequireAuthenticatedUser();
});
});
And then in my controllers I added this:
[Authorize("Policy1")]