0

I have an ASP.NET Core Web API which can be accessed by many client applications. I want to authenticate all client applications. All client application have different client ID under same tenant. How to do this?

This is my appsettings.json file

enter image description here

And here is my Startup.cs file

public void ConfigureServices(IServiceCollection services)
{
    Essilor.Common.AwsMfaHelper.ProfileHelper.UseProfile("ride-dev", true);
    InitializeEnvironment();

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(Configuration);
    services.AddAuthorization();
    services.AddAuthZClient();

    services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
    services.AddAWSService<Amazon.S3.IAmazonS3>();

    RegisterServices(services);

    services.AddMvcCore();
    services.AddRazorPages();
    services.AddControllersWithViews(options =>
            {
                options.Filters.Add(typeof(AuditTrailAttribute));
            });
}

1 Answer 1

0

In your current scenario, this is similar to the concept of ApiKey, I modified the following sample code based on the code tested in my previous answer, I hope it will be useful to you.

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;

namespace SecuringWebApiUsingClient_ID.Middleware
{
public class Client_IDMiddleware
{
    private readonly RequestDelegate _next;
    private const string APIKEYNAME = "ApiKey";
    public Client_IDMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue(Client_ID, out var extractedClient_ID))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Client ID was not provided. (Using Client_IDMiddleware) ");
            return;
        }

        var appSettings = context.RequestServices.GetRequiredService<IConfiguration>();

        var apiKey = appSettings.GetValue<string>(Client_IDs);

        if (!Client_IDs.Equals(extractedClient_ID))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Unauthorized client. (Using Client_IDMiddleware)");
            return;
        }

        await _next(context);
    }
}
}

For more details, pls check below thread.

ASP.NET core - simple API key authentication

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.