MissingFieldException: Field not found: 'Microsoft.Net.Http.Headers.HeaderNames.Authorization'

China☆狼群 提交于 2019-12-10 22:49:51

问题


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).

This is my login method.

[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 });
}

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)

I'm sending the request with Authorization header only.

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
        };
    });
}

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();
        });

Desperately I have tried installing following packages with 0 luck.

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

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

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

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>

回答1:


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>



回答2:


I was getting this problem when my .net core sdk/runtime installed was on preview 4 and not on preview 5, even though my nuget package references were on the latest.

Easily done, when you upgrade nuget, but do not install the latest runtime.

This explains why I did not have the issues on linux/docker which was using the nightly runtime build.

Mike



来源:https://stackoverflow.com/questions/56067167/missingfieldexception-field-not-found-microsoft-net-http-headers-headernames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!