c# - 使用 Blazor 0.9.0 和 ASP.NET Core 3 预览版 4 进行 JWT 身份验证
问题描述
我遵循了本教程:https ://medium.com/@st.mas29/microsoft-blazor-web-api-with-jwt-authentication-part-1-f33a44abab9d (适用于.NET core 2.2)。
这是我的启动课
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?
解决方案
放置两者 app.UseAuthentication()
和app.UseAuthorization()
之后 app.UseRouting()
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(routes =>
{
routes.MapDefaultControllerRoute();
});
推荐阅读
- android - android - 为什么 mapObjectClickEvent 在单击 mapObject 时不会触发?
- java - 有没有一种简单的方法可以在 Spring MVC 或 Spring Boot 中列出文件夹内容?
- excel - 清除选定单元格以外的范围内容
- javascript - jquery animate run on click again not running
- macos - 通过host(Mac OS)终端获取Virtual Box的IP
- java - JDBI3动态创建WHERE子句
- css - 具有更平滑过渡的 CSS 对角渐变
- android - SQlite:无法打开数据库 - 目录存在
- swift - 使用按位运算快速清除第 i 位
- android-studio - 生成签名的 apk 给我 AAPT2 错误