Franco Tiveron
Franco Tiveron

Reputation: 2896

JWT authentication with Blazor 0.9.0 and ASP.NET Core 3 preview 4

I followed this tutorial: https://medium.com/@st.mas29/microsoft-blazor-web-api-with-jwt-authentication-part-1-f33a44abab9d (which is for .NET core 2.2).

Here my Startup class

    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public IConfiguration Configuration { get; }
        public Startup (IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().AddNewtonsoftJson();
            //services.AddMvcCore().AddAuthorization().AddNewtonsoftJson();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });

            services.AddResponseCompression(opts =>
            {
                opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "application/octet-stream" });
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseResponseCompression();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBlazorDebugging();
            }

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

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });

            app.UseBlazor<Client.Startup>();
        }
    }

I also added [Authorize] on the Api controller SampleDataController.

I expected (as per the post) to get a 401 (Unauthorized) error when accessing the data, instead I get a complaint about missing authorization middleware

enter image description here

If I add app.UseAuthorization() (un-comment the line) the application works normally, without any error, retrieving the data as though the client is authorized.

What needs to be done to get a 401 when accessing the data?

Upvotes: 1

Views: 2358

Answers (2)

Sen Alexandru
Sen Alexandru

Reputation: 2263

If you send a request with a an authorization token, and the server authorization is not setup in the Startup.cs file, the API will return an error saying <Called method> contains authorization metadata, but a middleware was not found that supports authorization...

The fix is to add the below lines in the Startup.cs file, BETWEEN app.UseRouting() and app.UseEndpoints(...):

            app.UseRouting();

            //AUTHORIZING
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });

Upvotes: 0

Artem Zharinov
Artem Zharinov

Reputation: 96

Place both app.UseAuthentication() and app.UseAuthorization() after app.UseRouting()

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(routes =>
     {
         routes.MapDefaultControllerRoute();
     });

Upvotes: 4

Related Questions