aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

UseJwtBearerAuthentication is obsolete?

Open vrooijen opened this issue 9 years ago • 21 comments

As I was redirected from https://github.com/dotnet/cli/issues/6373 I ask my question here:

Steps to reproduce

dotnet publish -r ubuntu.16.04-arm

Expected behavior

Published application

Actual behavior

Microsoft (R) Build Engine version 15.2.93.5465 Copyright (C) Microsoft Corporation. All rights reserved.

Startup.cs(99,11): error CS0117: 'JwtBearerOptions' does not contain a definition for 'AutomaticAuthenticate' [C:\Tools\dotnet 2\webapp\WebApplication.csproj] Startup.cs(100,11): error CS0117: 'JwtBearerOptions' does not contain a definition for 'AutomaticChallenge' [C:\Tools\dotnet 2\webapp\WebApplication.csproj] Startup.cs(97,7): error CS0619: 'JwtBearerAppBuilderExtensions.UseJwtBearerAuthentication(IApplicationBuilder, JwtBearerOptions)' is obsolete: 'See https://go.microsoft.com/fwlink/?linkid=845470' [C:\Tools\dotnet 2\webapp\WebApplication.csproj]

Environment data

CLI version: 2.0.0-preview1-005791 TargetFramework: netcoreapp2.0 RuntimeFrameworkVersion: 2.0.0-preview1-002028-00 RuntimeIdentifiers: ubuntu.16.04-arm Microsoft.AspNetCore.Authentication.JwtBearer: 2.0.0-preview1-002028-00

I can't find information what to use now, is this really obsolete?

vrooijen avatar Apr 21 '17 10:04 vrooijen

I found the code in the dev branch: https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerAppBuilderExtensions.cs

Moving the section from 'Configure' to the 'Startup' method and using services.AddJwtBearerAuthentication(options => { /* configure options.TokenValidationParameters */ }); does the job.

The thing I am missing is AutomaticAuthenticate/AutomaticChallenge which is removed in JwtBearerOptions. This made me use the AuthorizeAttribute without any additional configuration. Now I get an 403

The server logs "authenticationscheme bearer was forbidden"

Update: had to add services.AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser() .Build(); });

Issue solved!

vrooijen avatar Apr 21 '17 12:04 vrooijen

@HaoK ?

Tratcher avatar Apr 21 '17 13:04 Tratcher

The replacement for: Automatic is setting DefaultAuthenticate/ChallengeScheme via

services.AddAuthentication(o => 
{
   o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
   o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
});

I'll open a breaking change announcement later today with more details

HaoK avatar Apr 21 '17 17:04 HaoK

Hi,

Before I had this code:

in Configure
[...]
            var options = new JwtBearerOptions
            {
                Audience = Configuration["auth0:clientId"],
                Authority = $"https://{Configuration["auth0:domain"]}/"
            };
            app.UseJwtBearerAuthentication(options);
[...]

Now I have this:

in ConfigureServices
1/
            //JWT
            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .Build();
            }
            );
            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            });

Or

2/
            //JWT
            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .Build();
            }
`

It doesnt work. I can t call [Authorize] endpoint.
I dont understand how can I specify the OAuth settings? 
Can you help me to find a solution please?

ranouf avatar Jun 02 '17 19:06 ranouf

@ranouf https://github.com/aspnet/Security/blob/c5b566ed4abffac4cd7011e0465e012cf503c871/samples/JwtBearerSample/Startup.cs#L47-L53

Tratcher avatar Jun 02 '17 19:06 Tratcher

Thank you @Tratcher !

And for the next who have the same error, don t forget to add " app.UseAuthentication();" in Configure.

ranouf avatar Jun 02 '17 20:06 ranouf

What is the replacement of TokenValidationParameters from JwtBearerOptions ?

My existing code is: app.UseJwtBearerAuthentication(new JwtBearerOptions { AutomaticAuthenticate = true, AutomaticChallenge = true, TokenValidationParameters = tokenValidationParameters });

cannot find equivalent replacement.

Any suggestion?

Added later:

I tried this

services.AddJwtBearerAuthentication(o =>
            {
                o.TokenValidationParameters = tokenValidationParameters;
            });

But m not sure, if I use above, do I still need to call services.AddAuthentication? If yes, then does the sequence matter?

goforgold avatar Jun 26 '17 10:06 goforgold

Yes, you also should call AddAuthentication to specify your default schemes.

Tratcher avatar Jun 26 '17 14:06 Tratcher

After I have updated my runtime from Preview 2.0 to 2.0.0-rtm-26425, my code started to break. In my code, I was previously using TokenValidationParameters for Jwt authentication as specified in this example link http://www.c-sharpcorner.com/article/handle-refresh-token-using-asp-net-core-2-0-and-json-web-token/

Now when I compile, I could not find the extension method. I am getting the below exception when I compile my project.

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

Any help on how to solve this issue?

mubavoice avatar Jul 30 '17 16:07 mubavoice

For RTM those extensions have moved one level down to an auth builder: https://github.com/aspnet/Announcements/issues/262

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o => o.LoginPath = new PathString("/login"))
                .AddFacebook(o =>
                {
                    o.AppId = Configuration["facebook:appid"];
                    o.AppSecret = Configuration["facebook:appsecret"];
                });

Tratcher avatar Jul 31 '17 14:07 Tratcher

Thanks @Tratcher, I have fixed the issue with below line services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o => { o.TokenValidationParameters = tokenValidationParameters; });

mubavoice avatar Aug 01 '17 02:08 mubavoice

Thanks, this worked for me as well.

services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.Audience = Configuration["MySettings:Auth0Settings:Audience"]; options.Authority = Configuration["MySettings:Auth0Settings:Authority"]; });

jculverwell avatar Aug 15 '17 02:08 jculverwell

Hello, what's the replacement fot this code in netcoreapp2.0?

            services.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                //AutomaticAuthenticate = true,
                //AutomaticChallenge = true,
                TokenValidationParameters = new TokenValidationParameters
                {
                    // The signing key must match!
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("AppConfiguration:Key").Value)),

                    // Validate the JWT Issuer (iss) claim  
                    ValidateIssuer = true,
                    ValidIssuer = Configuration.GetSection("AppConfiguration:SiteUrl").Value,


                    // Validate the JWT Audience (aud) claim  
                    ValidateAudience = true,
                    ValidAudience = Configuration.GetSection("AppConfiguration:SiteUrl").Value,

                    // Validate the token expiry  
                    ValidateLifetime = true,

                    ClockSkew = TimeSpan.Zero
                }
            });  

digounet avatar Aug 15 '17 17:08 digounet

See https://github.com/aspnet/Security/blob/dev/samples/JwtBearerSample/Startup.cs#L51

HaoK avatar Aug 15 '17 17:08 HaoK

@digounet use below in ConfigureServices method

     var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("AppConfiguration:Key").Value)),

                // Validate the JWT Issuer (iss) claim  
                ValidateIssuer = true,
                ValidIssuer = Configuration.GetSection("AppConfiguration:SiteUrl").Value,


                // Validate the JWT Audience (aud) claim  
                ValidateAudience = true,
                ValidAudience = Configuration.GetSection("AppConfiguration:SiteUrl").Value,

                // Validate the token expiry  
                ValidateLifetime = true,

                ClockSkew = TimeSpan.Zero
            };

        services.AddJwtBearer(options =>
        {
            options.TokenValidationParameters = tokenValidationParameters;
        });

yayadavid avatar Oct 13 '17 09:10 yayadavid

I previously used a custom service (which provides device specific data) when configuring Jwt bearer.

public void Configure(IApplicationBuilder app, ..., IdentityInfo idInfo)
{
    app.UseJwtBearerAuthentication(new JwtBearerOptions
    {
        TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(idInfo.TokenSecurityKey),

            ValidateIssuer = true,
            ValidIssuer = idInfo.ApplicationId,

            ValidateAudience = true,
            ValidAudience = AuthenticationConstants.LoginAudience
        }
    });
}

How am I supposed to migrate this to AddJwtBearer?

nkreipke avatar Oct 18 '17 09:10 nkreipke

Where is IdentityInfo being configured? In ConfigureServices?

Tratcher avatar Oct 18 '17 16:10 Tratcher

Yes, IdentityInfo is a singleton service which is not only used in UseJwtBearerAuthentication but also in other areas like the token generator. To clarify, this information is not simply read from the configuration but gathered from other sources (IdentityInfo itself has further service dependencies).

Not being able to resolve services in ASP.NET Core 2 AddJwtBearer makes things really awkward and kind of misses the point of a service oriented architecture.

nkreipke avatar Oct 18 '17 20:10 nkreipke

Hi all,

I'm getting this error when trying to use Auth0 with .AddAuthentication/.AddJwtBearer and app.UseAuthentication.

IDX10503: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.X509SecurityKey , KeyId: Microsoft.IdentityModel.Tokens.RsaSecurityKey , KeyId: '. Exceptions caught: ''. token: '{"alg":"HS256","typ":"JWT"}.{"iss":"","sub":"","aud":"","iat":,"exp":}'.

Any help would be greatly appreciated :)

MattHartz avatar Nov 10 '17 03:11 MattHartz

My Auth0 account is configured to use RS256, but https://auth0.com/docs/quickstart/backend/aspnet-core-webapi/v2/01-authorization says this method should use RS256... but it appears to use HS256.

MattHartz avatar Nov 10 '17 03:11 MattHartz