現在、ベアラートークンを使用して安全なAPIを構築する方法を学習しようとしています。このエラー(InvalidOperationException:The AuthorizationPolicy named: 'Bearer' was not found。)が発生し続け、その理由がわかりません。私はasp.net-core 2.0を使用していて、jwt authミドルウェアを使用しようとしています。これが私のスタートアップクラスです、どんな助けでも大歓迎です!
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
const string TokenAudience = "ExampleAudience";
const string TokenIssuer = "ExampleIssuer";
private RsaSecurityKey key;
private TokenAuthOptions tokenOptions;
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)
{
var keyParams = RSAKeyUtils.GetRandomKey();
key = new RsaSecurityKey(keyParams);
tokenOptions = new TokenAuthOptions()
{
Audience = TokenAudience,
Issuer = TokenIssuer,
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
};
services.AddDbContext<VulnerabilityContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<LoggingActionFilter>();
services.AddScoped<VulnsService>();
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.Authority = "https://localhost:54302";
o.Audience = tokenOptions.Audience;
o.RequireHttpsMetadata = false;
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//app.UseSession();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
AuthenticationSchemes
をコントローラークラスに追加すると、うまくいきます。
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]