coolcake
coolcake

Reputation: 2967

How to get windows user name when enabling both windows authentication and anonymous authentication

I've built my api in .net core for the first time in core 2.0. The client is built using vs 2017 angular template.

My api is used even by other applications which may not be using windows authentication. For those functions I want to allow anonymous access. For this reason I've to enable both windows authentication and anonymous authentication.

But when enable both I know I cannot get windows user name. In that case how can get the windows user name?

The following code breaks when I enable anonymous authentication along with windows authentication.

[Route("current")]
public ADUser GetCurrentUser()
{

         string accountUser = this.User.Identity.Name;     
         return new ADUser { Name = accountUser };
}

Can someone please help me how did they dealt the following situation. If not can someone tell me how to do the following things in .net core 2.0

  1. Authenticate the users using windows authentication
  2. Protect the api from being accessed by malicious user.
  3. use some basic functions of the api even by anonymous user.

When using windows authentication I need to be able to get windows user name so I check my user, roles database to authorize them accordingly.

[Update] As I said I know I get windows user name when I enable Windows Authentication and disable all other authentication types in IIS. But I am unable to access functions which I want anonymous users to be able to access even after using [AllowAnonymous]. enter image description here

I can also read from the following snippet that AllowAnonymous doesn't have any affect if only windows authentication is enabled.

When Windows authentication is enabled and anonymous access is disabled, the [Authorize] and [AllowAnonymous] attributes have no effect. If the IIS site (or HTTP.sys or WebListener server) is configured to disallow anonymous access, the request never reaches your app. For this reason, the [AllowAnonymous] attribute isn't applicable. Thanks

Upvotes: 5

Views: 7293

Answers (2)

Mickaël Derriey
Mickaël Derriey

Reputation: 13704

Here's how I solved this:

IIS

Since you want to allow anonymous users to hit some endpoints of your API, you need to enable both anonymous authentication and Windows authentication.

As a side note, you're right saying that [AllowAnonymous] has no effect when only Windows authentication is enabled because IIS, which sits in front of your API, will reject anonymous requests.

ASP.NET Core authentication

Now that anonymous authentication is enabled, IIS will not try to authenticate requests by default, so without any further configuration, all requests will be anonymous as far as ASP.NET Core is concerned.

The answer to this is to indicate to ASP.NET Core that you want to try to run the Windows authentication process on every request. You can do this this way:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Other code omitted for brievity

        // This sets the IIS authentication scheme as the default scheme
        services.AddAuthentication(IISDefaults.AuthenticationScheme);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Other code omitted for brievity

        // This includes the authentication middleware in the request pipeline
        // It will try to authenticate every incoming request
        app.UseAuthentication();

        // MVC comes next, so the authentication will have taken place
        // by the time your controller action is executed against the scheme
        // used in AddAuthentication
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

MVC

There's now 2 possibilities in your controller:

  • The client is compatible with Windows authentication, so User.Identity.IsAuthenticated will return true
  • The client is not compatible with Windows authentication, so User.Identity.IsAuthenticated will fetch the value false

This means that you can either use the [Authorize] attribute on the specific actions that require authentication, or add the AuthorizeAttribute globally to the application and use [AllowAnonymous] on the actions that can be called anonymously.

Upvotes: 3

Hussein Salman
Hussein Salman

Reputation: 8236

  • Deploy your application to IIS and then Open the Authentication menu for the site.

enter image description here

  • Disable Anonymous and enable Windows Authentication

enter image description here

  • Add the following to the ConfigureServices method:

    //using Microsoft.AspNetCore.Server.IISIntegration;

    services.AddAuthentication(IISDefaults.AuthenticationScheme)

  • For the APIs or action controllers that you want to secure, decorate them with [Authorize] attribute, then you get the logged in user using HttpContext.User.Identity.Name. Use [AllowAnonymous] on actions that you want to allow access.

In case you want to secure and allow access on the same api, then you need to provide your own implementation of the Authorization filter.

For more details check this link

Upvotes: 1

Related Questions