我正在学习如何向WebApi添加JWT令牌身份验证。到目前为止,我在Startup.cs
内所做的操作:
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
..
..
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "http://localhost:Port",
ValidateAudience = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("testPass"))
}
});
app.UseMvc();
}
但是我遇到类似这样的错误:
JwtBearerAppBuilderExtensions.UseJwtBearerAuthentication(IApplicationBuilder, JwtBearerOptions)' is obsolete: 'See https://go.microsoft.com/fwlink/?linkid=845470
和
2. JwtBearerOptions' does not contain a definition for 'AutomaticAuthenticate'
答案 0 :(得分:1)
您可以在ConfigureServices
的{{1}}方法中进行此操作。
StartUp.cs
然后使用 public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = false,
ValidateIssuerSigningKey = true,
ValidIssuer = "http://localhost:Port",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourKey"))
};
});
// other configuration...
}
方法:
Configure
答案 1 :(得分:0)
尝试在ConfigureService中而不是在Configure中进行操作,尝试类似
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
它将起作用!