Fra*_*cca 6 c# jwt blazor .net-core-3.0
按照本教程,我在 Startup.cs 文件中遇到了一个问题:
(需要向下滚动一点,抱歉)
问题出在默认身份上,出现以下错误:
“IServiceCollection 不包含 AddDefaultIdentity 的定义,并且没有可访问的扩展方法 AddDefaultIdentity 接受类型的第一个参数”可以找到 IServiceCollection(您是否缺少 using 指令或程序集引用?)”
我查看了文档,但我错过了我正在犯的错误,我看到了一堆与我类似的案例,但他们的解决方案(包括在内)似乎不起作用。我可以为我们提供一些帮助,提前致谢。
如果你想看一看,“我的”代码在这里
如果使用 Jwt 身份验证,则不应添加身份...注意:AddDefaultIdentity 扩展方法用于为 Razor Pages 和 MVC 添加默认 UI 服务。它还需要您添加 StaticFiles。
另请注意附加代码及其在配置方法中的排列
在你的启动类中尝试一下:
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>();
}
}
Run Code Online (Sandbox Code Playgroud)
}
希望这可以帮助...
更新 1: * 使用上面的代码更新您的 Startup 类 * 像这样注释您的 SampleDataController 控制器:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("api/[controller]")]
public class SampleDataController : Controller
{
// ..
}
Run Code Online (Sandbox Code Playgroud)
api/SampleData/WeatherForecasts
响应应包含创建的 JwtToken
执行流程摘要:向您的 Web Api 发送 get 请求。对路由点 WeatherForecasts 的请求被重定向到令牌控制器,其目的是创建 Jwt 令牌并将其返回给调用者。请注意,此控制器不会验证代表其发送此请求的用户的身份...
去做:
注意:您可以将 Jwt 令牌从服务器传递到 Blazor,其中包含有关用户的更多详细信息作为 cookie。
注意:如果用户已经通过身份验证,则不会重定向到登录表单。相反,我们向服务器发出 http 请求,以便检索 Blazor 中所需的资源(如果是这种情况)。
注意:我们如何知道我们的用户是否通过了身份验证?我们查询 IsAutentiated 方法。如果用户已通过身份验证,则检索 Jwt 令牌并将其添加到通过我们的 HttpClient 调用传递的标头集合中。
更多内容即将推出...
你看到了吗?