代码之家  ›  专栏  ›  技术社区  ›  Nishan

MissingFieldException:未找到字段:“Microsoft.Net.Http.Headers.HeaderNames.Authorization”

  •  0
  • Nishan  · 技术社区  · 7 年前

    我用 .NET Core 3.0预览4 CLI . 我已经到了可以发送用户名和密码并获取令牌(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] 属性,我得到以下异常。

    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 只有标题。 enter image description here

    我在中配置了身份验证中间件 ConfigureServices 方法如下。

    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 方法。

            app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowCredentials());
            app.UseHttpsRedirection();
    
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
    

    我拼命地试着用0运气安装以下包。

    dotnet add包Microsoft.Net.Http.Headers--版本2.2.0

    dotnet add包Microsoft.AspNetCore.StaticFiles--版本2.2.0

    我不知道出了什么事。此代码用于处理.NET Core 2.2

    我的相关部分 csproj 文件看起来像这样。。

    <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>
    
    0 回复  |  直到 7 年前
        1
  •  0
  •   Edward    7 年前

    若要解决此问题,请尝试更改 Microsoft.AspNetCore.Authentication.JwtBearer 版本 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
  •  0
  •   Michael Ceber    7 年前

    当我的.net core sdk/运行时安装在preview 4而不是preview 5时,我遇到了这个问题,尽管我的nuget包引用是最新的。

    升级nuget时很容易做到,但不要安装最新的运行时。

    迈克

    推荐文章