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

问题描述 投票:0回答:2

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

这是我的Startup课程

    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?

c# jwt blazor
2个回答
3
投票

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

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

0
投票

我认为你在ConfigureServices方法中错过了这个:

services.AddTransient<IJwtTokenService, JwtTokenService>();

见这里:https://github.com/StuwiiDev/DotnetCoreJwtAuthentication/blob/master/JwtAuthentication.Server/Startup.cs

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

希望这可以帮助...

© www.soinside.com 2019 - 2024. All rights reserved.