The name 'CertificateAuthenticationDefaults' does not exist in the current context - asp.net

I'm trying to configure mTLS authentication with ASP.NET core 3.1 by using the example from Microsoft Docs but getting the error below
Error CS0103 The name 'CertificateAuthenticationDefaults' does not exist in the current context
The code I'm using for Startup.cs is below:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Data;
namespace WebApplication1
{
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<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddControllersWithViews();
// Configure the application to use the protocol and client ip address forwared by the frontend load balancer
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
// Configure the application to client certificate forwarded the frontend load balancer
services.AddCertificateForwarding(options => { options.CertificateHeader = "X-ARR-ClientCert"; });
// Add certificate authentication so when authorization is performed the user will be created from the certificate
services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme).AddCertificate();
}
// 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.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseForwardedHeaders();
app.UseCertificateForwarding();
app.UseHttpsRedirection();
app.UseRouting();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
Any suggestinos on fix will be appreciated

In order to overcome the error I have to add the following statement in the code :
using Microsoft.AspNetCore.Authentication.Certificate;
and install Microsoft.AspNetCore.Authentication.Certificate 3.1.20 package.

Related

How to read the Azure App Configuration in Service Fabric ASP.NET Core Stateless Web API?

I need help to read the App Configuration in Service Fabric ASP.NET Core Stateless Web API. In the Normal ASP.NET Core Web API, we can use the Host CreateDefaultBuilder to read the config and use it in the Startup and other classes. If I try to inject in the Service Fabric Web API, it does not work. The Program.cs contains only the following.
private static void Main(string[] args)
{
try
{
// The ServiceManifest.XML file defines one or more service type names.
// Registering a service maps a service type name to a .NET type.
// When Service Fabric creates an instance of this service type,
// an instance of the class is created in this host process.
ServiceRuntime.RegisterServiceAsync("EmailAPIType",
context => new EmailAPI(context)).GetAwaiter().GetResult();
ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(EmailAPI).Name);
// Prevents this host process from terminating so services keeps running.
Thread.Sleep(Timeout.Infinite);
}
catch (Exception e)
{
ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
throw;
}
}
And the startup.cs contains
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EmailAPI
{
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();
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
I tried to inject Host CreateDefaultBuilder in program.cs
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(options =>
{
options.Connect(ConnectionString)
.Select(ConfigValues).TrimKeyPrefix(qualtricsAppConfigPrefix + ":")
.UseFeatureFlags();
});
})
.UseStartup<Startup>());
I am running out of Ideas how to do. In Azure Function App we can do it in Startup, not sure how we can handle in Service Fabric ASP.NET Core Web API. Any examples please.
I have uploaded the sample project created in One Drive. Here is the link to it.
https://1drv.ms/u/s!Au2rKbF-hqWY61pykRlWRTI4DB8t?e=vz0c8z
Finally figured it out. For anyone who is interested here is it. If you have any better way to do it please let me know
public class Startup
{
private static string prefix = "";
public Startup(IConfiguration configuration)
{
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json", false, false)
.AddEnvironmentVariables();
var builder = configurationBuilder.Build();
configurationBuilder.AddAzureAppConfiguration(o => AddApplicationKeysAppConfiguration(o, builder));
builder = configurationBuilder.Build();
configuration = builder;
Configuration = configuration;
}
private static void AddApplicationKeysAppConfiguration(AzureAppConfigurationOptions options, IConfigurationRoot configuration)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
environment = string.IsNullOrWhiteSpace(environment) ? Environment.GetEnvironmentVariable("Environment") : environment;
string connectionString = "";
options.Connect(connectionString)
.Select($"{prefix}*", environment).TrimKeyPrefix(prefix + ":")
.UseFeatureFlags(flagOptions =>
{
flagOptions.Label = environment;
});
}
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.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

How can you add a Microsoft Graph client service as a MediatR service in .NET Core 3.1?

So I have a .NET Core web API with it's own local data context, and I'd like to add the ability to call Microsoft Graph as a downstream API.
However, when I try to add the necessary properties to call the Graph API, I get a build error:
Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[Application.Users.Me+Query,Microsoft.Graph.User] Lifetime: Transient ImplementationType: Application.Users.Me+Handler': Unable to resolve service for type 'Microsoft.Graph.GraphServiceClient' while attempting to activate 'Application.Users.Me+Handler'.)
Here is my startup class:
using API.Middleware;
using Application.TestEntities;
using FluentValidation.AspNetCore;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Persistence;
using Microsoft.Identity.Web;
namespace API
{
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<DataContext>(opt =>
{
opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
});
services.AddCors(opt =>
{
opt.AddPolicy("CorsPolicy", policy =>
{
policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3000");
});
});
services.AddMicrosoftIdentityWebApiAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();
services.AddMediatR(typeof(List.Handler).Assembly);
services.AddControllers(opt =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
opt.Filters.Add(new AuthorizeFilter(policy));
})
.AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<Create>());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<ErrorHandlingMiddleware>();
if (env.IsDevelopment())
{
// app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
And my application handler for calling downstream:
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Graph;
using Microsoft.Identity.Web;
namespace Application.Users
{
public class Me
{
public class Query : IRequest<User> { }
public class Handler : IRequestHandler<Query, User>
{
private readonly ITokenAcquisition _tokenAcquisition;
private readonly GraphServiceClient _graphServiceClient;
public Handler(ITokenAcquisition tokenAcquisition, GraphServiceClient graphServiceClient)
{
_tokenAcquisition = tokenAcquisition;
_graphServiceClient = graphServiceClient;
}
public async Task<User> Handle(Query request, CancellationToken cancellationToken)
{
var user = await _graphServiceClient.Me.Request().GetAsync();
return user;
}
}
}
}
Hopefully I'm on the right track here, but please let me know if I'm not.
Right so this was a simple oversight on my part.
As per #franklores, you need to register Microsoft Graph in your startup class services:
services.AddMicrosoftIdentityWebApiAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
Adding the following to appsettings (scopes may differ):
"DownstreamAPI": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.read"
},
And be sure to install Microsoft.Identity.Web.MicrosoftGraph to enable the AddMicrosoftGraph() function.

Hyphens in route, works with link, doesn't work directly

I am trying to use hyphens in an URL route. In ASP.NET Core MVC. I setup a default MVC template.
The only thing I change is to add this first line:
[Route("hello-dude")]
public IActionResult Privacy()
{
return View();
}
Now, when I got to test the project, I click privacy and it shows the correct page and URL. (http://localhost:44386/hello-dude)
But when I go to the address bar and put that in manually, click enter, I get "site cannot be reached".
What is going on here?
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.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApplication8
{
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.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();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}

Ocelot Caching : AddCacheManager Try specifying the type arguments explicitly error

New to Ocelot and .net core. I am trying to implement caching in .net core 3.0 microservice in Ocelot gateway. As per Ocelot guideline (https://ocelot.readthedocs.io/en/latest/features/caching.html)
As per second step, my startup.cs looks like:
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
namespace MS_APIGateway
{
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.AddOcelot().AddCacheManager(x => **// Getting error here**
{
x.WithDictionaryHandle();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
//JWT
app.UseAuthentication();
//JWT
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
await app.UseOcelot();
}
}
}
The compiler is throwing error at AddCacheManager line and the error message is:
Error CS0411 The type arguments for method 'ServiceCollectionExtensions.AddCacheManager<T>(IServiceCollection, IConfiguration, string, Action<ConfigurationBuilder>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Please help. Thank you.
we have to add using Ocelot.Cache.CacheManager;

Missing startup.cs program.cs .Net Core Razor

I have a .Net Core 3 Web App using Razor pages. I was messing with solution explorer a few days ago and now I notice I'm missing startup.cs and program.cs. How can I restore them? I'm also getting this error: "Unable to run your project. The RunCommand property is not defined".
First I'd check to make sure your files are in the project directory before trying to rebuild them. If they are still in the directory you can add them to your solution using Visual Studio.
Right click the project > Add > Existing item...
If you don't have those files and can't find them, then recreate them. Here's the default code for them.
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.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace NOCng
{
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.AddRazorPages();
}
// 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");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace NOCng
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}

Resources