question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Issue validating token on .net core 2.0

See original GitHub issue

Hi, i followed the following sample: RefreshFlow.

I set it up to use JWT-Tokens. My Problem is that every request (with an Authorize-Attribute) fails with 404. After some investigation I found out that AddIdentity seems to cause the problem here. I tried to remove AddIdentity and register all required services manually (UserStore, RoleStore, UserManager, …) and it worked partially (using Roles on Authorize-Attribute still caused 403).

Am I missing something here?

Here’s the code with UseIdentity:

            services.AddDbContext<ApplicationDbContext>(options =>
            {
                var connectionString = Configuration.GetConnectionString("UserServiceSql");
                options.UseSqlServer(connectionString, b => b.MigrationsAssembly("UserService.Api"));
                options.UseOpenIddict<int>();
            }, ServiceLifetime.Transient);


            services.AddIdentity<User, Role>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
        
            // Configure Identity to use the same JWT claims as OpenIddict instead
            // of the legacy WS-Federation claims it uses by default (ClaimTypes),
            // which saves you from doing the mapping in your authorization controller.
            services.Configure<IdentityOptions>(options =>
            {
                options.User.RequireUniqueEmail = true;
                options.SignIn.RequireConfirmedEmail = true;
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
            });

            services.AddOpenIddict<int>(options =>
            {
                options.AddEntityFrameworkCoreStores<ApplicationDbContext>();
                options.AddMvcBinders();
                options.SetAccessTokenLifetime(TimeSpan.FromHours(2));
                options.SetRefreshTokenLifetime(TimeSpan.FromDays(14));
                options.EnableTokenEndpoint("/api/token");
                options.AllowPasswordFlow();
                options.AllowRefreshTokenFlow();
                options.DisableHttpsRequirement();
                options.UseJsonWebTokens();
                options.AddSigningKey(base.TokenValidationParameters.IssuerSigningKey);
            });


            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

            services
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {

                    options.TokenValidationParameters = this.TokenValidationParameters;
                    options.IncludeErrorDetails = true;
                });

The requests log output (if it helps 😃):

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed for user: (null).
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes ().
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: Identity.Application was challenged.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action UserService.Api.Controllers.UserController.Get (UserService.Api) in 33.1316ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 446.215ms 302 

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

11reactions
TomTFcommented, Aug 28, 2017

Figured it out, yay 😃

I changed

            services
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {

                    options.TokenValidationParameters = this.TokenValidationParameters;
                    options.IncludeErrorDetails = true;
                });

to

            services
                .AddAuthentication(o =>
                {
                    o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;                    
                })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = this.TokenValidationParameters;
                    options.IncludeErrorDetails = true;
                });

Thx

3reactions
kevinchaletcommented, Aug 28, 2017

Arf yeah, Identity overrides DefaultAuthenticateScheme/DefaultSignInScheme/DefaultChallengeScheme so setting a DefaultScheme has absolutely no effect… even if you do it after calling services.AddIdentity() 😢

@HaoK we absolutely need to do something to change that, it’s really a common trap.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Token Authentication in ASP.NET Core 2.0
Validate Tokens Manually in ASP.NET Core​​ In some cases, you might need to validate tokens without using the JwtBearer middleware. Using the ...
Read more >
ASP.NET Core 2.0 JWT Validation fails with `Authorization ...
I'm using ASP.NET Core 2.0 application (Web API) as a JWT issuer to generate a token consumable by a mobile app. Unfortunately, this...
Read more >
Creating And Validating JWT Tokens In C# .NET
NET Core inbuilt class for handling JWT Tokens, we pass it our token as well as our “expected” issuer, audience and our security...
Read more >
Make secure .NET Microservices and Web Applications
Authentication is the process of reliably verifying a user's identity. ... NET Core Identity to let you issue security tokens from an ASP....
Read more >
Securing ASP.NET Core 2.0 Applications with JWTs
Our code is saying that to consider a token valid we must: validate the server that created that token ( ValidateIssuer = true...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found