【发布时间】:2018-08-19 07:48:57
【问题描述】:
请告诉我为什么这段代码不起作用。
public class Startup
{
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(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = AuthOptions.ISSUER,
ValidateAudience = true,
ValidAudience = AuthOptions.AUDIENCE,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey()
};
});
services.AddDbContext<ApplicationContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<User, IdentityRole>().AddEntityFrameworkStores<ApplicationContext>();
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)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
}
}
我尝试删除 options.Default* 并将其替换为仅 JwtBearerDefaults.AuthenticationScheme。仅当我将 [Authorize] 更改为 [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] 时它才有效。但我不想为每个属性使用AuthenticationSchemes 属性。
【问题讨论】:
-
您的 Startup 中有其他身份验证或身份相关的东西吗?
-
@poke 我更新了我的代码。请检查
标签: c# asp.net-core jwt asp.net-core-identity