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.

Using Json Web Tokens with OpenIddict

See original GitHub issue

Hi,

I am trying to implement JWT in my API, after following through the example in the READ ME and successfully implementing as described, when I add the .UseJsonTokens() method all my resource endpoints result in 401 when trying to make a request with Authorization: Bearer "access_token".

Is there an additional configuration step I am missing?

I have a Angular2 SPA and a few other clients applications that need to request a token from my API and access the resources.

My Startup.cs is as follows:

        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddDbContext<AuthDbContext>(options =>
                options.UseSqlServer(Configuration["ConnectionStrings:Auth"]));

            // Register the Identity services.
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<AuthDbContext>()
                .AddDefaultTokenProviders();

            // Register the OpenIddict services, including the default Entity Framework stores.
            services.AddOpenIddict<ApplicationUser, AuthDbContext>()
                // Enable the token endpoint (required to use the password flow).
                .EnableTokenEndpoint("/connect/token")

                // Allow client applications to use the grant_type=password flow.
                .AllowPasswordFlow()

                .AllowRefreshTokenFlow()

                // During development, you can disable the HTTPS requirement.
                .DisableHttpsRequirement()

                // Adding this results in 401 on all resources, is there some configuration I am missing?
                //.UseJsonWebTokens()

                // Register a new ephemeral key, that is discarded when the application
                // shuts down. Tokens signed using this key are automatically invalidated.
                // This method should only be used during development.
                .AddEphemeralSigningKey();

            services.AddSwaggerGen(options => SwaggerConfig.ConfigureOptions(options));

            // Application services
        }
 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseStaticFiles();

            //CORS middleware must precede any defined endpoints in app
            app.UseCors(builder =>
            {
                builder.AllowAnyHeader();
                builder.AllowAnyMethod();
                builder.AllowAnyOrigin();
            });

            app.UseOAuthValidation(); // does this need to be replaced with JWT?

            app.UseOpenIddict();

            app.UseMvc();

            app.UseSwagger();
            app.UseSwaggerUi();

            using (var context = new AuthDbContext(
                app.ApplicationServices.GetRequiredService<DbContextOptions<AuthDbContext>>()))
            {
                context.Database.EnsureCreated();
            }
        }

Thanks

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:9 (5 by maintainers)

github_iconTop GitHub Comments

4reactions
dalestonecommented, Aug 1, 2016

Yep I read that and finally understood what you mean’t, thanks.

For anyone else that runs into this issue:

Add the following to configure

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                Authority = "http://localhost:5000",
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                Audience = "http://localhost:5000",
                RequireHttpsMetadata = false             
            });

When making a request to your token endpoint e.g http://localhost:5000/connect/token make sure the resource parameter is set to the audience you specified in the JwtBearerOptions e.g http://localhost:5000

get_token

Now when making requests to http://localhost:5000/api/**resource** you can just pass the Authorization header with the Bearer token

resource_request

What if the client wants to decode the JWT to read some custom properties on it?

0reactions
dalestonecommented, Aug 2, 2016

Ah OK understood thanks.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Token formats - OpenIddict documentation
OpenIddict 3.0 implements the JSON Web Token, JSON Web Signature and JSON Web Encryption standards and relies on the Azure Active Directory IdentityModel ......
Read more >
How to properly validate OpenIddict JWT access_token in ...
I'm trying to implement an identity server based on OpenIddict. The use case we have is one large javascript application that needs to ......
Read more >
Introducing OpenIddict 3.0 beta1 | Kévin Chalet's blog
OpenIddict now uses JSON Web Token (JWT) as the default token format. In OpenIddict 1.0/2.0, the ASP.NET Core Data Protection stack is always ......
Read more >
Set up token authentication with OpenIddict in .NET 5
Learn how to set up an OpenID Connect server using OpenIddict in .NET 5.
Read more >
Implementing simple token authentication in ASP.NET Core ...
In this post, discover how to add token authentication with OpenIddict by implementing the OAuth2 password flow.
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