我遵循了本教程:https://medium.com/@st.mas29/microsoft-blazor-web-api-with-jwt-authentication-part-1-f33a44abab9d(适用于.NET核心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?
在app.UseAuthentication()
之后放置app.UseAuthorization()
和app.UseRouting()
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(routes =>
{
routes.MapDefaultControllerRoute();
});
我认为你在ConfigureServices方法中错过了这个:
services.AddTransient<IJwtTokenService, JwtTokenService>();
应该在您的服务器应用程序中定义JwtTokenService。我猜它的责任是创建令牌等。
希望这可以帮助...