Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWTAuthentication not working in asp.net core 2.0 after migrate from 1.1 to 2.0 with System.IdentityModel.Tokens.Jwt - 5.1.4 update

Tags:

Error

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

Here is the code for the JWT authentication

app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey = key,
                    ValidAudience = tokenOptions.Audience,
                    ValidIssuer = tokenOptions.Issuer,

                    // When receiving a token, check that it is still valid.
                    ValidateLifetime = true,

                    // This defines the maximum allowable clock skew - i.e. provides a tolerance on the token expiry time 
                    // 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. Where external tokens are
                    // used, some leeway here could be useful.
                    ClockSkew = TimeSpan.FromMinutes(0)
                }
            });

The same code was working fine in asp.net core 1.1 I, have just migrate from core 1.1 to core 2.0 and updated the System.IdentityModel.Tokens.Jwt(5.1.1) to (5.1.4)

ConfigureServices

RSAParameters keyParams = RsaKeyUtils.GetRandomKey();
            key = new RsaSecurityKey(keyParams);
            tokenOptions = new TokenAuthOptions()
            {
                Audience = TokenAudience,
                Issuer = TokenIssuer,
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
            };
            services.AddSingleton<TokenAuthOptions>(tokenOptions);
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                    .RequireAuthenticatedUser().Build());
            });

I tried the solution posted in this question Authentication in dot net core preview-2.0 . But the solution is not working getting an error as IServiceCollection doesn't contain the definition for AddJwtBearerAuthentication

Tried to implement https://github.com/aspnet/Security/blob/c5b566ed4abffac4cd7011e0465e012cf503c871/samples/JwtBearerSample/Startup.cs#L47-L53 https://github.com/IdentityServer/IdentityServer4/issues/1055 https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/

500 internal server error.

The same code was working perfectly on asp.net core 1.1. When upgrade to 2.0 the issue occur.

Please anyone let me know how can I resolve this issue.

like image 600
San Jaisy Avatar asked Sep 09 '17 09:09

San Jaisy


1 Answers

The method for adding Jwt Bearer Authentication has changed in ASP.NET Core 2.0. See the latest version of the sample you linked.

You need to register the Jwt Bearer Authentication process as a service, rather than a middleware component. See the relevant code in ConfigureServices:

services.AddAuthentication(...)
    .AddJwtBearer(...);

Try this in ConfigureServices:

services.AddAuthentication()
    .AddJwtBearer(jwt =>
    {
        jwt.TokenValidationParameters = new TokenValidationParameters
        {
            IssuerSigningKey = key,
            ValidAudience = tokenOptions.Audience,
            ValidIssuer = tokenOptions.Issuer,

            // When receiving a token, check that it is still valid.
            ValidateLifetime = true,

            // This defines the maximum allowable clock skew - i.e. provides a tolerance on the token expiry time
            // 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. Where external tokens are
            // used, some leeway here could be useful.
            ClockSkew = TimeSpan.FromMinutes(0)
        };
     });

services.AddAuthorization(auth =>
{
     auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
             .RequireAuthenticatedUser()
             .Build());
});

And make sure you have this in Configure:

app.UseAuthentication();

As I can't test this against your scenario, there's every chance it won't work first time. Be sure to be specific when you include any further information that comes from this.

like image 144
Kirk Larkin Avatar answered Sep 30 '22 14:09

Kirk Larkin