c# - Blazor:IServiceCollection 不包含 AddDefaultIdentity 的定义

标签 c# jwt blazor .net-core-3.0

关注此 tutorial我在 Startup.cs 文件中遇到问题:

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

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

“IServiceCollection 不包含 AddDefaultIdentity 的定义并且没有可访问的扩展方法 AddDefaultIdentity 接受类型的第一个参数”可以找到 IServiceCollection(您是否缺少 using 指令或程序集引用?)“

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

“我的”代码是 HERE如果你想看看

最佳答案

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

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

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

 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 类 * 像这样注释您的 SampleDataController Controller :

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

api/SampleData/WeatherForecasts

响应应该包含创建的 JwtToken

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

待办事项:

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

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

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

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

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

更多内容……

你看到了吗?

关于c# - Blazor:IServiceCollection 不包含 AddDefaultIdentity 的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56429882/

相关文章:

c# - 使用属性路由时查询字符串不起作用

c# - ASP.NET Core JWT Bearer Token 自定义验证

c# - 如何转换为 C# 中的泛型参数?

c# - WPF:设计器未能添加第三方控件。这导致设计器重新启动

java - 如何从过滤器中的数据库中获取用户并在 jwt 响应中添加 Id?

c# - .Net Core 自定义身份验证使用 Identity Server 4 的 API key

c# - 如何在 Blazor WebAssembly-PWA 中运行离线数据库使用?

c# - 使用 <InputText> 给出空指针

blazor - 如何在 Blazor 中设置页面标题?

数据库中的 C# 枚举