问题描述
我正在使用.net core 2.0和jwt承载身份验证进行一个小的新项目( https://github .com/aspnet/Security )
I'm making a small new project using .net core 2.0 and jwt bearer authentication (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();
}
使用这些配置,在我的Web应用程序中启用了jwt.但是,我目前正面临着一件事:
With these configurations, jwt has been enabled in my web application. But, there is one thing I'm currently facing with:
- 使用API不需要身份验证(位于 [AllowAnonymous] 属性下),如果我在请求中传递了 Authorization 标头,则 OnAuthenticationFailed 事件将被引发(由于未检测到令牌).
- With API doesn't require authentication (placed under [AllowAnonymous] attribute), if I pass Authorization header in my request, OnAuthenticationFailed event will be raised (due to no token is detected).
我的问题是:如何使我的jwt身份验证自动忽略标记为 AllowAnonymous 的方法或控制器?
My question is: How can I make my jwt authentication automatically ignore methods or controller which is marked as AllowAnonymous ?
谢谢
推荐答案
而不是使用 OnAuthenticationFailed ,请尝试将其放入 OnChallenge :
Instead of using OnAuthenticationFailed, try putting it in OnChallenge:
o.Events = new JwtBearerEvents()
{
OnChallenge = c =>
{
c.HandleResponse();
c.Response.StatusCode = 500;
c.Response.ContentType = "text/plain";
return c.Response.WriteAsync("An error occurred processing your authentication.");
}
};
这篇关于Asp.net Core 2.0 Jwt不会忽略AllowAnonymous的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!