Blazor:IServiceCollection 不包含 AddDefaultIdentity 的定义

Blazor: IServiceCollection does not contain a definition for AddDefaultIdentity

在此之后 tutorial我在 Startup.cs 文件中遇到了一个问题:

(需要向下滚动一点,抱歉)

问题出在默认身份上,出现以下错误:

"IServiceCollection does not contain a definition for AddDefaultIdentity and no accessible extension method AddDefaultIdentity accepting a first argument of type" 可以找到 IServiceCollection(您是否缺少 using 指令或程序集引用?)"

我查看了 documentation,但我遗漏了我正在犯的错误, 我见过一堆与我相似的案例,但他们的解决方案(包括在内)似乎不起作用。我可以为我们提供一些帮助,在此先感谢。

"my"代码是HERE如果你想看看

如果使用 Jwt 验证,则不应添加身份...注意:AddDefaultIdentity 扩展方法用于为 Razor Pages 和 MVC 添加默认 UI 服务。它还要求您添加 StaticFiles。

Note also the additional code and its arrangement in the Configure method

在你的启动中试试这个 class:

 public class Startup
{
    //add
    public IConfiguration Configuration { get; }
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }


    // 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 void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddNewtonsoftJson();

        services.AddTransient<IJwtTokenService, JwtTokenService>();


        //Setting up Jwt Authentication
        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.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(routes =>
     {
         routes.MapDefaultControllerRoute();
     });

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

}

希望这对您有所帮助...

更新 1: * 使用上面的代码更新您的 Startup class * 像这样注释您的 SampleDataController 控制器:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] 
[Route("api/[controller]")]
    public class SampleDataController : Controller
    {
    // ..
    }
  • 运行 您的应用程序,然后 post 在 Postman 或 Fiddler 中为 url 获取 http 请求:

api/SampleData/WeatherForecasts

响应应包含创建的 JwtToken

执行流程摘要:向您的 Web 发布获取请求 Api。对路由点 WeatherForecasts 的请求被重定向到 Token 控制器,其目的是创建一个 Jwt 令牌并 return 它给调用者。请注意,此控制器不会验证代表其发送此请求的用户的身份...

待办事项:

  • 创建一个服务来存储 Jwt 令牌: 此服务可以使用 LocalStorage 和 SessionStorage 的 Blazor 扩展来存储和检索 Jwt 令牌。此服务可能包含 IsAutenticated、GetToken 等方法

注意:您可以将 Jwt 令牌从服务器传递到 Blazor,并将有关用户的更多详细信息作为 cookie。

  • 如果用户尚未登录并尝试访问安全资源,则创建登录组件以登录用户

注意:如果用户已经通过身份验证,他不会被重定向到登录表单。相反,我们向服务器发出一个 http 请求,以便检索 Blazor 中所需的资源(如果是这种情况)。

注意:我们如何知道我们的用户是否已通过身份验证?我们查询我们的 IsAutenticated 方法。如果用户通过身份验证,则检索 Jwt 令牌并将其添加到通过我们的 HttpClient 调用传递的 headers collection。

更多...

你看到了吗?