我是.net Core的新手,我正在尝试将项目从.net Core 1.0升级到2.0, 当我尝试访问API时,出现此错误。 “没有配置身份验证处理程序来对该方案进行身份验证:“ bearer” .net core 2.0”。 由于UseJwtBearerauthentication在.net core 2.0中不起作用,因此我将其替换为AddAuthentication。
Startup.cs
public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory,IApplicationLifetime appLifetime)
{
app.UseAuthentication();
app.UseCors("AllowAll");
app.UseMvc();
}
public void ConfigureServices(IServiceCollection services)
{
var tvp = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,IssuerSigningKey = _signingKey,// Validate the JWT Issuer (iss) claim
ValidateIssuer = true,ValidIssuer = "ABC",// Validate the JWT Audience (aud) claim
ValidateAudience = true,ValidAudience = "User",// Validate the token expiry
ValidateLifetime = true,// If you want to allow a certain amount of clock drift,set that here:
ClockSkew = TimeSpan.FromMinutes(5)
};
services.AddSingleton(s => tvp);
ConfigureAuth(services,tvp);
}
private void ConfigureAuth(IServiceCollection services,TokenValidationParameters tvp)
{
//TODO: Change events to log something helpful somewhere
var jwtEvents = new JwtBearerEvents();
jwtEvents.OnAuthenticationFailed = context =>
{
Debug.WriteLine("JWT Authentication failed.");
return Task.WhenAll();
};
jwtEvents.OnChallenge = context =>
{
Debug.WriteLine("JWT Authentication challenged.");
return Task.WhenAll();
};
jwtEvents.OnmessageReceived = context =>
{
Debug.WriteLine("JWT Message received.");
return Task.WhenAll();
};
jwtEvents.OnTokenValidated = context =>
{
Debug.WriteLine("JWT Message Token validated.");
return Task.WhenAll();
};
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
o.TokenValidationParameters = tvp;
o.Events = jwtEvents; });
}
在Configure方法下,我有:
app.UseDefaultFiles();
app.UseStaticfiles();
app.UseAuthentication();
app.UseCors("AllowAll");
app.UseRequestResponseLogging();
app.UseNoCacheCacheControl();
app.UseMvc();
AuthController.cs
[HttpPost]
[EnableCors("AllowAll")]
[AllowAnonymous]
[Authorize(AuthenticationSchemes =
JwtBearerDefaults.AuthenticationScheme)]
public IactionResult Authenticate([FromBody] UserContract model)
{
}
Authenticationmiddleware:
public class Authenticationmiddleware
{
private readonly RequestDelegate _next;
public Authenticationmiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context,IAuthUser authUser)
{
if (context.User?.Identity != null)
{
if (context.User?.Identity?.IsAuthenticated == true)
{
authUser.username = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
}
using (LogContext.PushProperty("username",authUser.username))
{
await _next.Invoke(context);
}
}
}