Authentication .NET核心Web API中的身份验证未激活
我正在尝试激活.net核心web api中的JWT令牌身份验证方案。它根本没有激活 我将Swagger配置为接收令牌,并让API的使用者访问其所有控制器。但它只是让每个人都可以访问,而不是检查是否存在有效的令牌 我已经尝试在所有控制器上添加[Authorize]关键字,但仍然不起作用 这里我提供了startup.cs文件Authentication .NET核心Web API中的身份验证未激活,authentication,asp.net-core,jwt,asp.net-core-webapi,Authentication,Asp.net Core,Jwt,Asp.net Core Webapi,我正在尝试激活.net核心web api中的JWT令牌身份验证方案。它根本没有激活 我将Swagger配置为接收令牌,并让API的使用者访问其所有控制器。但它只是让每个人都可以访问,而不是检查是否存在有效的令牌 我已经尝试在所有控制器上添加[Authorize]关键字,但仍然不起作用 这里我提供了startup.cs文件 namespace Web.Api { public class Startup { public Startup(IHostingEnviro
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}");
});
}
}
}
namespace Web.Api
{
公营创业
{
公共启动(IHostingEnvironment环境)
{
var builder=new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile(“appsettings.json”,可选:false,reloadOnChange:true)
.AddJsonFile($“appsettings.{env.EnvironmentName}.json”,可选:true)
.AddenEnvironmentVariables();
Configuration=builder.Build();
}
公共IConfiguration配置{get;}
公共启动(IConfiguration配置)
{
配置=配置;
}
public void配置服务(IServiceCollection服务)
{
services.AddOptions();
services.addswagger文档();
//CORS配置
services.AddCors(选项=>
{
options.AddPolicy(“AllowAllOrigins”,
生成器=>
{
建设者
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
//身份验证配置
services.Configure(Configuration.GetSection(“Jwt”));
var token=Configuration.GetSection(“Jwt”).Get();
var secret=Encoding.ASCII.GetBytes(token.Key);
services.AddAuthentication(选项=>
{
options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(选项=>
{
options.RequireHttpsMetadata=false;
options.SaveToken=true;
options.TokenValidationParameters=新的TokenValidationParameters
{
ClockSkew=时间跨度从分钟(5),
validateisuer=true,
ValidateAudience=true,
ValidateLifetime=true,
ValidateSuersigningKey=true,
ValidIssuer=token.Issuer,
ValidAudience=象征。观众,
IssuerSigningKey=新对称安全密钥(机密)
};
});
services.AddRouting(options=>options.LowercaseUrls=true);
services.AddSingleton();
services.addScope();
services.AddScoped(implementationFactory=>
{
var actionContext=implementationFactory.GetService().actionContext;
返回新的UrlHelper(actionContext);
});
services.AddVersionedApiExplorer(o=>o.GroupNameFormat=“'v'VVV”);
services.AddMvcCore()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddFormatterMappings()
.AddJsonFormatters();
}
public void Configure(IAApplicationBuilder应用程序、IHostingEnvironment环境、IApiVersionDescriptionProvider提供程序)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(x=>x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseAuthentication();
app.useswagger文档(提供商);
app.UseMvc(路由=>
{
MapRoute(“API默认”、“API/{controller}/{action}/{id?}”);
MapRoute(“打印机默认”、“api/{controller}/{action}/{vendorDriver}/{vendormodel}”);
});
}
}
}
我将向您展示我在项目中的工作方式(我使用的是ASP.NET Core 2.2)
//内部配置服务
services.AddAuthentication().AddCookie().AddJwtBearer(cfg=>{
cfg.TokenValidationParameters=新的TokenValidationParameters()
{
validateisuer=true,
ValidateAudience=true,
ValidateLifetime=true,
ValidateSuersigningKey=true,
ValidisUser=配置[“令牌:颁发者”],
Validudience=配置[“令牌:受众”],
IssuerSigningKey=new-SymmetricSecurityKey(Encoding.UTF8.GetBytes(配置[“令牌:键]))
};
});
//内部配置
app.UseAuthentication();
//在需要身份验证的控制器中
[ApiController]
[授权(AuthenticationSchemes=JwtBearerDefaults.AuthenticationScheme)]
公共类SampleController:ControllerBase{
}
我将向您展示我在项目中的工作方式(我使用的是ASP.NET Core 2.2)
//内部配置服务
services.AddAuthentication().AddCookie().AddJwtBearer(cfg=>{
cfg.TokenValidationParameters=新的TokenValidationParameters()
{
validateisuer=true,
ValidateAudience=true,
ValidateLifetime=true,
ValidateSuersigningKey=true,
ValidisUser=配置[“令牌:颁发者”],
Validudience=配置[“令牌:受众”],
IssuerSigningKey=new-SymmetricSecurityKey(Encoding.UTF8.GetBytes(配置[“令牌:键]))
};
});
//内部配置
app.UseAuthentication();
//在需要身份验证的控制器中
return services
.AddMvcCore()
.AddApiExplorer()
.AddAuthorization()
.AddCors()
.AddDataAnnotations()
.AddFormatterMappings();