How to replace AddJwtBearer extension in .NET Core 3.0

shelbypereira picture shelbypereira · Oct 28, 2019 · Viewed 14.2k times · Source

I have the following code which compiles and works in .NET Core 2.2:

  byte[] key = Encoding.ASCII.GetBytes(Constants.JWT_SECRET); 
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

In .NET Core 3.0 I am getting the error:

Error CS1061 'AuthenticationBuilder' does not contain a definition for 'AddJwtBearer' and no accessible extension method 'AddJwtBearer' accepting a first argument of type 'AuthenticationBuilder' could be found (are you missing a using directive or an assembly reference?)

when I look at the MSFT documentation: https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.jwtbearerextensions.addjwtbearer?view=aspnetcore-2.2

and try to got to version 3.0, It seems that this is the last version where this is defined. How do I migrate AddJwtBearer to Core 3.0?

Answer

Overlord picture Overlord · Oct 28, 2019

Like Mert Sayin says, include package Microsoft.AspNetCore.Authentication.JwtBearer, but use Version 3.0.0.