正在尝试在.net核心Web API中激活JWT令牌身份验证方案。它根本没有激活。
我将Swagger配置为接收令牌,并向API的使用者提供对其所有控制器的访问权限。但这只是让所有人都可以访问,而不是检查是否存在有效的令牌。
我尝试将[Authorize]关键字放在所有控制器上,但仍然无法正常工作。
这里我提供了startup.cs文件
namespace Web.Api
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddSwaggerDocumentation();
// CORS Configurations
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// Authentication Configurations
services.Configure<TokenManagement>(Configuration.GetSection("Jwt"));
var token = Configuration.GetSection("Jwt").Get<TokenManagement>();
var secret = Encoding.ASCII.GetBytes(token.Key);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ClockSkew = TimeSpan.FromMinutes(5),
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = token.Issuer,
ValidAudience = token.Audience,
IssuerSigningKey = new SymmetricSecurityKey(secret)
};
});
services.AddRouting(options => options.LowercaseUrls = true);
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<IUrlHelper>(implementationFactory =>
{
var actionContext = implementationFactory.GetService<IActionContextAccessor>().ActionContext;
return new UrlHelper(actionContext);
});
services.AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV");
services.AddMvcCore()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddFormatterMappings()
.AddJsonFormatters();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseAuthentication();
app.UseSwaggerDocumentation(provider);
app.UseMvc(routes =>
{
routes.MapRoute("API Default", "api/{controller}/{action}/{id?}");
routes.MapRoute("Printers Default", "api/{controller}/{action}/{vendorDriver}/{vendormodel}");
});
}
}
}
答案 0 :(得分:1)
services.AddMvc()
和services.AddMvcCore()
之间的区别是应用程序内部加载的服务。
AddMvcCore()
仅添加必需的服务来运行Asp.net应用程序,而AddMvc()
则加载常用的服务。
答案 1 :(得分:1)
services.AddMvc()
将加载授权服务(AddAuthorization()):
return services
.AddMvcCore()
.AddApiExplorer()
.AddAuthorization()
.AddCors()
.AddDataAnnotations()
.AddFormatterMappings();
因此您可以使用services.AddMvc()
或services.AddMvcCore().AddAuthorization()
答案 2 :(得分:0)
我将向您展示我如何在项目中使用它(我正在使用 ASP.NET Core 2.2 )
// Inside ConfigureServices
services.AddAuthentication().AddCookie().AddJwtBearer(cfg => {
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = configuration["Tokens:Issuer"],
ValidAudience = configuration["Tokens:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Tokens:Key"]))
};
});
// Inside Configure
app.UseAuthentication();
// In the controllers that need Authentication
[ApiController]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class SampleController : ControllerBase {
}
答案 3 :(得分:0)
好吧,我刚刚添加了行
services.AddMvc()。SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
我不知道为什么行
services.AddMvcCore()。SetCompatibilityVersion(CompatibilityVersion.Version_2_2)不会 激活它