我目前正在尝试学习如何使用持票令牌构建安全api,我不断收到此错误(InvalidOperationException:未找到名为’Bearer’的AuthorizationPolicy.)我不知道为什么.我正在使用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?}");
});
}
}
解决方法:
我没有使用策略,当我忘记在authorize属性中指出角色时,这个错误发生在我身上.
我有这个:
[Authorize("Administrator")] // if you don't specify the property name Roles it will consider it as the policy name
通过将其更改为:
[Authorize(Roles = "Administrator")]