I am trying to migrate the DelegateHandler apikey authentication to RequestDelegate apikey authentication.I was able to create below code ,but need clarification wheather the code configuration is correct and how to return error code if any condition fails in "async Task Invoke" method of DelegatingHandler class.
Using RequestDelegate:
- public class DelegatingHandler {
- private readonly RequestDelegate _next;
- private readonly ILogger _logger;
- private ISecurityService _securityService;
- public DelegatingHandler(RequestDelegate next, ILogger logger, ISecurityService securityService) {
- _next = next;
- _logger = logger;
- _securityService = securityService;
- }
-
- public async Task Invoke(HttpContext context, HttpRequestMessage request) {
- try {
-
- string apiKey = request.ApiKey();
-
-
- if (apiKey == null || apiKey.Trim().Equals(string.Empty)) {
-
- new HttpResponseMessage(HttpStatusCode.Unauthorized) {
- Content = new StringContent("Header information for ApiKey is missin")
- };
- }
- string message = "";
-
- string[] identity = apiKey.Split(':');
- if (!IsAuthorized(identity, request.RequestUri.AbsolutePath.ToString(), request.Method.ToString(),
- ref message)) {
-
-
- new HttpResponseMessage(HttpStatusCode.Unauthorized) {
- Content = new StringContent("Header information for ApiKey is missin")
- };
- } else {
-
- IPrincipal principal = new GenericPrincipal(
- new GenericIdentity(identity[0]), null);
- Thread.CurrentPrincipal = principal;
-
- _logger.Info(message,
- new {
- EndPoint = request.RequestUri.AbsolutePath.ToString(),
- UserName = Thread.CurrentPrincipal.Identity.Name
- });
- }
- await _next.Invoke(context);
- } catch (Exception ex) {
-
- new HttpResponseMessage(HttpStatusCode.InternalServerError) {
- Content = new StringContent(ex.ToString())
- };
- }
- }
-
- private bool IsAuthorized(string[] identity, string requestAbsolutePath, string httpMethod, ref string message) {
- try {
-
-
- message = "Unauthorized to access the requested resource";
- } catch (Exception ex) {
- message = ex.Message;
- _logger.Error("VSphereDelegationHandler Failed", new {
- Method = "IsAuthorized"
- }, ex);
- }
-
- return false;
- }
- }
APIKey Extension:
- public static class ApiKeyExtensions {
- public static IApplicationBuilder UseApiKey(this IApplicationBuilder builder) {
- return builder.UseMiddleware < VSphereDelegatingHandler > ();
- }
- }
In the startup.cs class do we need to register all the service Interface and Class files ,but I am getting error in program.cs
Program.cs
- 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 > ();
- });
- }
StartUp.cs
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
- public IConfiguration Configuration { get; }
-
-
- public void ConfigureServices(IServiceCollection services, string dbConnectionString)
- {
- services.AddControllers();
-
- services.AddScoped<ISecurityService, SecurityService>();
- services.AddScoped<ISecurityDataService, SecurityDataService>();
- services.AddScoped<ISecurityCheckService, SecurityCheckService>();
-
- services.AddScoped<IDBOps, DBOps>(db => new DBOps(dbConnectionString));
- }
-
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
-
- app.UseRouting();
-
- app.UseAuthorization();
-
- app.UseApiKey();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }