没有配置身份验证处理程序以对该方案进行身份验证:“ bearer” .net core 2.0

我是.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);
        }
    }
}
eywe0686 回答:没有配置身份验证处理程序以对该方案进行身份验证:“ bearer” .net core 2.0

您可以使用AddJwtBearer方法,有关扩展名的使用方法,请参阅以下文章:

https://developer.okta.com/blog/2018/03/23/token-authentication-aspnetcore-complete-guide

下面带有选项和事件的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);
        }
    };
});

并在控制器/动作上使用:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

不要忘记在Configure方法中启用身份验证:

app.UseAuthentication();
本文链接:https://www.f2er.com/2982591.html

大家都在问