.net core 未将任何身份验证处理程序配置为对方案进行身份验证:";持票人。net核心2.0
我是.net Core的新手,我正在尝试将一个项目从.net Core 1.0升级到2.0, 当我试图访问API时,我遇到了这个错误。 “未配置任何身份验证处理程序来对方案进行身份验证:“Bear”.net core 2.0”。 由于UseJWTBeareAuthentication在.net core 2.0中不起作用,我将其替换为AddAuthentication Startup.cs.net core 未将任何身份验证处理程序配置为对方案进行身份验证:";持票人。net核心2.0,.net-core,asp.net-core-mvc,asp.net-core-webapi,asp.net-core-2.1,.net Core,Asp.net Core Mvc,Asp.net Core Webapi,Asp.net Core 2.1,我是.net Core的新手,我正在尝试将一个项目从.net Core 1.0升级到2.0, 当我试图访问API时,我遇到了这个错误。 “未配置任何身份验证处理程序来对方案进行身份验证:“Bear”.net core 2.0”。 由于UseJWTBeareAuthentication在.net core 2.0中不起作用,我将其替换为AddAuthentication Startup.cs public void Configure(IApplicationBuilder app, IHosti
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; });
}
在“配置方法”下,我有:
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)
{
}
身份验证中间件:
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);
}
}
}
您可以使用方法,请参阅下面的文章了解如何使用扩展:
以下带有选项和事件的AddJwtBearer代码示例供您参考:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer("Bearer",options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "Issuer",
ValidAudience = "Audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Yourkey"))
};
options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
var loggerFactory = context.HttpContext.RequestServices
.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger("Startup");
logger.LogInformation("Token-Expired");
context.Response.Headers.Add("Token-Expired", "true");
}
return System.Threading.Tasks.Task.CompletedTask;
},
OnMessageReceived = (context) =>
{
return Task.FromResult(0);
}
};
});
不要忘记在Configure
方法中启用身份验证:
app.UseAuthentication();
谢谢Nan的建议,但我仍然看到相同的错误,我没有使用app.UseAuthentication()而使用AuthenticationMiddleware,我更新了问题来描述序列,我不确定我做错了什么。你的AuthenticationMiddleware做了什么?获取令牌并填写索赔原则?为什么不直接使用默认身份验证处理程序?是的,你是对的,我的身份验证中间件填写声明原则,我删除了它并使用了app.UseAuthentication(),但仍然存在相同的错误。是的,我已经编辑了问题并按照你的建议包括了步骤,但是从代码中,您仍在使用中间件,并且缺少app.UseAuthentication()。请在一个干净的项目中尝试我的代码,看看它是否有效。
app.UseAuthentication();