30
votes

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?

3
share your csproject file - JeePakaJP

3 Answers

62
votes

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

15
votes

You must include Microsoft.AspNetCore.Authentication.JwtBearer package to your project. with version 3.0.0 for Core 3.0 and above.

1
votes

Something like this:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => Configuration.Bind("JwtSettings", options)) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => Configuration.Bind("CookieSettings", options));

From here: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/?view=aspnetcore-3.1