我是.net Core的新手,正在从事一个新项目,该项目具有一组需要承载令牌认证的API。
我已经成功配置了startup.cs文件以使用Bearer令牌,但是仅在使用[Authorize]明确修饰时才保护端点。
我希望所有端点默认使用JwtBearerToken身份验证,除非端点具有[AllowAnonymous]。
到目前为止,我读到的内容表明我只需要在启动时将JwtBearer指定为默认身份验证方案,如下所示(我尝试了几个稍有不同的示例,这是最新的)。
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(cfg =>
{
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuer = "your app",
ValidateAudience = true,
ValidAudience = "the client of your app",
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("a secret that " +
"needs to be at least 16 characters long"))
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
var connection = @"Server=(localdb)\<dev stuff>;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<PrimaryRepository>(options => options.UseSqlServer(connection));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
}
}
每个示例我都遵循相同的结果-没有[Authorize]的情况下端点不受保护。默认情况下,如何使它们获得授权?