.Net 6 Use default cookie auth and secure specific controller with managed identity

Viewed 206

In my current project I am using cookie authentication to secure my controllers. However, for one particular controller (which will simply be used as API controller) I want the endpoints to be secured using Azure AD.

My use case is that the application serves as a website where users log in and the authentication is stored as a cookie. This already works. Now I want to extend a new controller that will be called via a Logic App.

But I only want the Logic App to be able to call this endpoint. So I created a system managed identity for the Logic App and now I want to secure this new API controller/endpoint.

I have read many articles explaining how to implement multiple schemes. But I don't understand how to implement cookie auth + this particular authentication method.

Perhaps a different method is required, thus I am asking it here. Preferably I don't want to edit the existing working code but rather have a [Authorize(Policy = "ManagedApp")] policy at the top of the new controller.

Any help is appreciated, I am pretty of stuck.

Current ConfigureServices method (irrelevant code removed)

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
        {
            options.LoginPath = "/signin";
            options.LogoutPath = "/signout";
            // Stuff to store the auth cookie
        })
    services.AddMvc();
}
1 Answers

From the information you provided, it seems to me that, in order to use policies such as [Authorize(Policy = "ManagedApp")], besides the AddAuthentication(... definition, you will still need to either include:

  • AddAuthorization
  • or AddPolicySchemes, depending on your preferences.

I would recommend following this tutorial, which explains both implementations: https://code-maze.com/dotnet-multiple-authentication-schemes/

Please mind that, in order to use exactly [Authorize(Policy = "ManagedApp")], you will need to register a policy named as "ManagedApp".

Concerning the development of front-end and API controllers alongside each other, I wrote this answer some time ago, which may be of interest for your scenario.

In order to authorize all your endpoints by default, you can, for example:

  • Have different (base) controllers for the front-end and API, and employ a specified Authorize attribute in each of them, then inheriting from those (Microsoft ref);
  • Or use RequireAuthorization on the endpoints definition, as Andrew Lock suggests here.

Hope this helps!

Related