【发布时间】:2018-05-19 23:02:28
【问题描述】:
我正在使用 .net core 2.0 和 jwt 不记名身份验证 (https://github.com/aspnet/Security) 制作一个小型新项目
这是我的 Startup.cs
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services)
{
// Add entity framework to services collection.
var sqlConnection = Configuration.GetConnectionString("SqlServerConnectionString");
services.AddDbContext<RelationalDatabaseContext>(
options => options.UseSqlServer(sqlConnection, b => b.MigrationsAssembly(nameof(Main))));
// Injections configuration.
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<DbContext, RelationalDatabaseContext>();
services.AddScoped<IEncryptionService, EncryptionService>();
services.AddScoped<IIdentityService, IdentityService>();
services.AddScoped<ITimeService, TimeService>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Requirement handler.
services.AddScoped<IAuthorizationHandler, SolidAccountRequirementHandler>();
services.AddScoped<IAuthorizationHandler, RoleRequirementHandler>();
// Load jwt configuration from setting files.
services.Configure<JwtConfiguration>(Configuration.GetSection(nameof(JwtConfiguration)));
services.Configure<ApplicationSetting>(Configuration.GetSection(nameof(ApplicationSetting)));
// Build a service provider.
var serviceProvider = services.BuildServiceProvider();
var jwtBearerSettings = serviceProvider.GetService<IOptions<JwtConfiguration>>().Value;
// Cors configuration.
var corsBuilder = new CorsPolicyBuilder();
corsBuilder.AllowAnyHeader();
corsBuilder.AllowAnyMethod();
corsBuilder.AllowAnyOrigin();
corsBuilder.AllowCredentials();
// Add cors configuration to service configuration.
services.AddCors(options => { options.AddPolicy("AllowAll", corsBuilder.Build()); });
services.AddOptions();
// This can be removed after https://github.com/aspnet/IISIntegration/issues/371
var authenticationBuilder = services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
});
authenticationBuilder.AddJwtBearer(o =>
{
// You also need to update /wwwroot/app/scripts/app.js
o.Authority = jwtBearerSettings.Authority;
o.Audience = jwtBearerSettings.Audience;
o.RequireHttpsMetadata = false;
o.SecurityTokenValidators.Clear();
o.SecurityTokenValidators.Add(new JwtBearerValidator());
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.NoResult();
c.Response.StatusCode = 500;
c.Response.ContentType = "text/plain";
if ("dev".Equals(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")))
{
// Debug only, in production do not share exceptions with the remote host.
return c.Response.WriteAsync(c.Exception.ToString());
}
return c.Response.WriteAsync("An error occurred processing your authentication.");
}
};
});
#region Mvc builder
// Construct mvc options.
var mvcBuilder =
services.AddMvc(mvcOptions =>
{
//only allow authenticated users
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.AddRequirements(new SolidAccountRequirement())
.Build();
mvcOptions.Filters.Add(new AuthorizeFilter(policy));
});
// Add json configuration/
mvcBuilder.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
#endregion
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
/// <param name="loggerFactory"></param>
/// <param name="serviceProvider"></param>
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
{
// Enable logging.
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// Use JWT Bearer authentication in the system.
app.UseAuthentication();
// Enable cors.
app.UseCors("AllowAll");
// Enable MVC features.
app.UseMvc();
}
通过这些配置,jwt 已在我的 Web 应用程序中启用。但是,我目前面临一件事:
- 使用 API 不需要身份验证(放置在 [AllowAnonymous] 属性下),如果我在请求中传递 Authorization 标头,OnAuthenticationFailed将引发事件(由于未检测到令牌)。
我的问题是:如何让我的 jwt 身份验证自动忽略标记为 AllowAnonymous 的方法或控制器?
谢谢,
【问题讨论】:
标签: asp.net-core asp.net-core-mvc jwt asp.net-core-2.0 asp.net-core-webapi