Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring IdentityServer 4 with Identity, combining services.AddAuthentication() and services.AddIdentity()

Using Identity Server 4, .NetCore2.0 and MS Identity with Implicit Flow/Grant Type;

I am not clear on the responsibilities of the the following as each specifically relates to validating/authorizing a bearer token.

I have the following Startup:

    public void ConfigureServices(IServiceCollection services) {
        ...
        services.AddAuthentication("Bearer")
           .AddIdentityServerAuthentication(options =>
           {
               options.Authority = GetAuthentication().ApiURL;
               options.RequireHttpsMetadata = false;

               options.ApiName = "afapps";
           });

        // Below needed to inject UserManager<ApplicationUser> userManager
        // elsewhere in app as this happens to be the authORization server
        // as opposed to authENtication server.
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<AuthDbContext>()                
            .AddDefaultTokenProviders();
    }

    public void Configure(IApplicationBuilder app) {
        app.UseAuthentication();
        app.UseMvc();
    }

If I omit the services.AddIdentity<ApplicationUser, IdentityRole>()... in startup. In controllers I can successfully use [Authorize] and my other custom ActionFilters shows HttpContext.User.Identity.IsAuthenticated as == true.

However, after adding services.AddIdentity<ApplicationUser, IdentityRole>()... to enable usage of Identity's UserManager<ApplicationUser>; I now have to additionally add [Authorize(AuthenticationSchemes = "Bearer")] to each controller..

Is there a way to combine or arrange services.AddAuthentication() and services.AddIdentity() such that I do not have to specify [Authorize(AuthenticationSchemes = "Bearer")]?

like image 666
ttugates Avatar asked Feb 02 '18 20:02

ttugates


1 Answers

Use the AddAuthentication(Action<AuthenticationOptions> configureOptions) override after AddIdentity() to set the options manually like this:

services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Bearer";
        options.DefaultAuthenticateScheme = "Bearer";
        options.DefaultChallengeScheme = "Bearer";
        options.DefaultSignInScheme = "Bearer";
    });

You have to do this because the string override only sets the DefaultScheme, while AddIdentity() sets the more specific options. DefaultScheme is only used as the fallback for all the others, as per the documentation.

like image 163
Mim Avatar answered Oct 24 '22 08:10

Mim