MissingFieldException:找不到字段:'Microsoft.Net.Http.Headers.HeaderNames.Authorization' [英] MissingFieldException: Field not found: 'Microsoft.Net.Http.Headers.HeaderNames.Authorization'

查看:309
本文介绍了MissingFieldException:找不到字段:'Microsoft.Net.Http.Headers.HeaderNames.Authorization'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 .NET Core 3.0预览版4 CLI 制作了API.我想到了可以发送用户名和密码并获得令牌(JWT)的地步.

I making an API with .NET Core 3.0 Preview 4 CLI. I've came up to the point where you can send username and password and get the token (JWT).

这是我的登录方法.

[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] UserForLoginDto userForRegisterDto)
{
    var userFromRepo = await _repo.Login(userForRegisterDto.Username.ToLower(), userForRegisterDto.Password);
    if (userFromRepo == null) //User login failed
        return Unauthorized();

    //generate token
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:Token").Value);
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new Claim[]{
            new Claim(ClaimTypes.NameIdentifier,userFromRepo.Id.ToString()),
            new Claim(ClaimTypes.Name, userFromRepo.Username)
        }),
        Expires = DateTime.Now.AddDays(1),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);

    return Ok(new { tokenString });
}

此方法可以正常工作并为我提供令牌,但是我想使用[Authorize]属性限制对方法或控制器的访问,因此出现以下异常.

This methods works fine and provide me the token, but I want to restrict access to a method or a controller using [Authorize] attribute, I get the following exception.

MissingFieldException: Field not found: 'Microsoft.Net.Http.Headers.HeaderNames.Authorization'.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<TStateMachine>(ref TStateMachine stateMachine)
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
Microsoft.AspNetCore.Authentication.AuthenticationHandler<TOptions>.AuthenticateAsync()
Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, string scheme)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

我仅使用Authorization标头发送请求.

I'm sending the request with Authorization header only.

我已经在ConfigureServices方法中配置了身份验证中间件,如下所示.

I have configured authentication middleware in ConfigureServices method as follows.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddControllers()
        .AddNewtonsoftJson();
    services.AddScoped<IAuthRepository, AuthRepository>();

    var key = Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value);

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => {
        options.TokenValidationParameters = new TokenValidationParameters{
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });
}

,并且已将app.UseAuthentication();添加到Configure方法.

and have added app.UseAuthentication(); to Configure method.

        app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowCredentials());
        app.UseHttpsRedirection();

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

我拼命尝试安装以下具有0运气的软件包.

Desperately I have tried installing following packages with 0 luck.

dotnet添加软件包Microsoft.Net.Http.Headers --version 2.2.0

dotnet add package Microsoft.Net.Http.Headers --version 2.2.0

dotnet添加软件包Microsoft.AspNetCore.StaticFiles --version 2.2.0

dotnet add package Microsoft.AspNetCore.StaticFiles --version 2.2.0

我不知道出了什么问题.该代码曾经用于.NET Core 2.2

I have no idea what is going wrong. This code used to work with .NET Core 2.2

我的csproj文件中的相关段看起来像这样.

Relevant segment in my csproj file looks like this..

<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0-preview5-19227-01" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0-preview4-19216-03" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0-preview4.19216.3">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0-preview4.19216.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.3" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.4.0" />
  </ItemGroup>

推荐答案

要解决此问题,请尝试将Microsoft.AspNetCore.Authentication.JwtBearer版本更改为3.0.0-preview5-19216-09.

For resolving this issue, try to change Microsoft.AspNetCore.Authentication.JwtBearer version to 3.0.0-preview5-19216-09.

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0-preview5-19216-09" />
  <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0-preview4-19216-03" />
  <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0-preview4.19216.3">
    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    <PrivateAssets>all</PrivateAssets>
  </PackageReference>
  <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0-preview4.19216.3" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.3" />
  <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.4.0" />  
</ItemGroup>

这篇关于MissingFieldException:找不到字段:'Microsoft.Net.Http.Headers.HeaderNames.Authorization'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆