【问题标题】:JWT authentication with Blazor 0.9.0 and ASP.NET Core 3 preview 4使用 Blazor 0.9.0 和 ASP.NET Core 3 预览版 4 进行 JWT 身份验证
【发布时间】:2023-03-12 10:52:01
【问题描述】:

我遵循了本教程:https://medium.com/@st.mas29/microsoft-blazor-web-api-with-jwt-authentication-part-1-f33a44abab9d(适用于 .NET core 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(未授权)错误,而是收到有关缺少授权中间件的投诉

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

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

【问题讨论】:

    标签: c# jwt blazor


    【解决方案1】:

    同时放置app.UseAuthentication()app.UseAuthorization() app.UseRouting()

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

    【讨论】:

      【解决方案2】:

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

      解决方法是在Startup.cs 文件中添加以下行,在app.UseRouting()app.UseEndpoints(...) 之间:

                  app.UseRouting();
      
                  //AUTHORIZING
                  app.UseAuthentication();
                  app.UseAuthorization();
      
                  app.UseEndpoints(endpoints =>
                  {
                      endpoints.MapRazorPages();
                      endpoints.MapControllers();
                      endpoints.MapFallbackToFile("index.html");
                  });
      

      【讨论】:

        猜你喜欢
        • 2021-04-20
        • 2020-05-20
        • 2022-01-23
        • 2020-07-26
        • 2019-10-30
        • 2019-09-06
        • 1970-01-01
        • 1970-01-01
        • 2020-01-30
        相关资源
        最近更新 更多