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

4

6

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.

Yahweh answered 16/8, 2017 at 11:15 Comment(0)
M
10

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

Moreen answered 16/8, 2017 at 15:48 Comment(0)
Z
1

Method that configure Jwt authentication:

// Configure authentication with JWT (Json Web Token).
public void ConfigureJwtAuthService(IServiceCollection services)
{
  // Enable the use of an [Authorize(AuthenticationSchemes = 
  // JwtBearerDefaults.AuthenticationScheme)]
  // attribute on methods and classes to protect.
  services.AddAuthentication().AddJwtBearer(cfg =>
  {
    cfg.RequireHttpsMetadata = false;
    cfg.SaveToken = true;
    cfg.TokenValidationParameters = new TokenValidationParameters()
    {
      IssuerSigningKey = JwtController.SecurityKey,
      ValidAudience = JwtController.Audience,
      ValidIssuer = JwtController.Issuer,
      // When receiving a token, check that we've signed it.
      ValidateIssuerSigningKey = true,
      // When receiving a token, check that it is still valid.
      ValidateLifetime = true,
      // This defines the maximum allowable clock skew when validating 
      // the lifetime. As we're creating the tokens locally and validating
      // them on the same machines which should have synchronised time,
      // this can be set to zero.
      ClockSkew = TimeSpan.FromMinutes(0)
    };
  });
}

Now inside the ConfigureServices() method of the Startup.cs, you can call ConfigureJwtAuthService() method to configure the Jwt authentication.

Zacatecas answered 18/1, 2018 at 13:40 Comment(0)
R
0
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options => {
            options.Audience = "http://localhost:5001/";
            options.Authority = "http://localhost:5000/";
        });

see https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x

Recompense answered 16/8, 2017 at 16:27 Comment(0)
E
0

.Net 7

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security.DataHandler.Encoder;
using PAP.Web.Helpers;
using PAP.Web.Services;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

//builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));

// configure strongly typed settings object
AppSettings AppSettings = new AppSettings();

builder.Configuration.GetSection("AppSettings").Bind(AppSettings);

// Now start using it
string OauthIssuer = AppSettings.OAuthIssuer;
string OauthClientId = AppSettings.OAuthClientId;
var OauthSecret = TextEncodings.Base64Url.Decode(AppSettings.OAuthSecret);
 

builder.Services.AddAuthentication(auth =>
{
    auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
        .AddCookie(cookie =>
        {
            cookie.AccessDeniedPath = "logout";
            cookie.SlidingExpiration = true;
        })
        .AddJwtBearer(jwt =>
        {
            jwt.Audience = OauthClientId;
            jwt.Authority = OauthIssuer;
            jwt.RequireHttpsMetadata = false;
            jwt.SaveToken = true;
            jwt.TokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = OauthIssuer,
                ValidAudience = OauthClientId,
                IssuerSigningKey = new SymmetricSecurityKey(OauthSecret),
                ValidateIssuer = true,
                RequireAudience = true,
                RequireExpirationTime = true,
                RequireSignedTokens = true,
                ValidateIssuerSigningKey = true,
                ValidateLifetime = false,
                ValidateTokenReplay = false,
                ValidateActor = false,
                ValidateAudience = true,
                ClockSkew = TimeSpan.Zero
            };
            jwt.Configuration = new OpenIdConnectConfiguration();

        }); 

builder.Services.AddCon`enter code here`trollers();

// configure strongly typed settings object
//builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));

// configure DI for application services
//builder.Services.AddScoped<IUserService, UserService>();


var app = builder.Build();
IdentityModelEventSource.ShowPII = true;
// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

if (!app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseHsts();
}

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

AppSettings.cs namespace PAP.Web.Helpers;

public class AppSettings
{
    public string OAuthIssuer { get; set; }
    public string OAuthClientId { get; set; }
    public string OAuthSecret { get; set; } 

}
Everest answered 2/5, 2023 at 23:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.