使用Blazor 0.9.0和ASP.NET Core 3的JWT身份验证预览4

时间:2019-04-23 04:10:27

标签: c# jwt blazor

我遵循了本教程:https://medium.com/@st.mas29/microsoft-blazor-web-api-with-jwt-authentication-part-1-f33a44abab9d(适用于.NET Core 2.2)。

这是我的启动课程

    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>();
        }
    }

我还在Api控制器SampleDataController上添加了[Authorize]。

我希望(根据帖子)访问数据时会出现401(未经授权)错误,相反,我抱怨缺少授权中间件

enter image description here

如果我添加app.UseAuthorization()(取消注释该行),则该应用程序可以正常工作,而不会出现任何错误,就像客户端已被授权一样检索数据。

访问数据时需要做什么才能获得401?

3 个答案:

答案 0 :(得分:3)

app.UseAuthentication()app.UseAuthorization()放在之后 app.UseRouting()

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

答案 1 :(得分:0)

我认为您在ConfigureServices方法中错过了这一点:

services.AddTransient<IJwtTokenService, JwtTokenService>();

参见此处:https://github.com/StuwiiDev/DotnetCoreJwtAuthentication/blob/master/JwtAuthentication.Server/Startup.cs

JwtTokenService应该在您的服务器应用程序中定义。我猜它的责任是创建令牌等。

希望这对您有帮助...

答案 2 :(得分:0)

如果您发送带有授权令牌的请求,并且未在Startup.cs文件中设置服务器授权,则API将返回错误消息<Called method> contains authorization metadata, but a middleware was not found that supports authorization...

解决方法是将以下行添加到Startup.csapp.UseRouting()之间的app.UseEndpoints(...)文件中:

            app.UseRouting();

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

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