authenticationjwtbearer-token.net-core-1.1.net-core-2.0

Missing extension method AddJwtBearerAuthentication() for IServiceCollection in .NET Core 2.0


I have updated my project from Core 1.1 to Core 2.0 using instructions from https://blogs.msdn.microsoft.com/webdev/2017/08/14/announcing-asp-net-core-2-0/ (updated target framework to .NET Core 2.0 and used metapackage Microsoft.AspNetCore.All). I have updated all possible nuget packages to latest versions as well.

In .NET Core 1.1 i was adding JWT Bearer Authentication this way:

app.UseJwtBearerAuthentication(); // from Startup.Configure()

As per http://www.talkingdotnet.com/whats-new-in-asp-net-core-2-0/ for Core 2.0 the new way is to call:

services.AddJwtBearerAuthentication(); // from Startup.ConfigureServices()

But the method AddJwtBearerAuthentication() is absent. The package Microsoft.AspNetCore.Authentication.JwtBearer 2.0.0 is installed.

New empty Core 2.0 projects (with JwtBearer package) are also does not have extension method AddJwtBearerAuthentication() for IServiceCollection.

The old method app.UseJwtBearerAuthentication() does not compile at all:

Error   CS0619  'JwtBearerAppBuilderExtensions.UseJwtBearerAuthentication(IApplicationBuilder, JwtBearerOptions)' is obsolete: 'See https://go.microsoft.com/fwlink/?linkid=845470'

Please help.


Solution

  • In ConfigureServices use the following code to configure JWTBearer Authentication:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                o.Authority = "https://localhost:54302";
                o.Audience = "your-api-id";
                o.RequireHttpsMetadata = false;
            });
    
            services.AddMvc();
        }
    

    And in Configure just before UseMvc() add UseAuthentication():

    app.UseAuthentication();
    
    app.UseStaticFiles();
    
    app.UseMvc();
    

    For a detailed example see: https://github.com/aspnet/Security/blob/dev/samples/JwtBearerSample/Startup.cs#L51