ASP.NET Core Web API 授权期间生成 JWT 令牌时出错

问题描述 投票:0回答:1

我有一个Web API项目,通过它注册并登录。在授权期间,我应该获取令牌,出现错误:

An unhandled exception has occurred while executing the request.  System.TypeInitializationException: The type initializer for System.IdentityModel.Tokens.Jwt.JsonExtensions' threw an exception.    System.TypeLoadException: Could not load type 'Microsoft.IdentityModel.Json.JsonConvert' from assembly 'Microsoft.IdentityModel.Tokens, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

代币生成代码:

using ASFT.Auth.Interfaces;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;

namespace ASFT.Auth.Services
{
    public class TokenService : ITokenService
    {
        public string GenerateAccessToken(IEnumerable<Claim> claims)
        {
            var signinCredentials = new SigningCredentials(AuthOptions.Key, SecurityAlgorithms.HmacSha256);

            var tokenOptions = new JwtSecurityToken(
                issuer: AuthOptions.Issuer,
                audience: AuthOptions.Audience,
                claims: claims,
                expires: DateTime.Now.AddHours(48),
                signingCredentials: signinCredentials);

            return new JwtSecurityTokenHandler().WriteToken(tokenOptions);
        }
    }
}

The error 就在这条线上 -

return new JwtSecurityTokenHandler().WriteToken(tokenOptions);

连接包:

<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.11" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.11" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.11">
   <PrivateAssets>all</PrivateAssets>
   <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets></PackageReference>

响应正文中包含令牌和刷新令牌的预期状态 200。

c# jwt authorization asp.net-core-webapi
1个回答
0
投票

这可能是由于运行时尝试删除它认为运行时已经拥有并且正在项目中重复的程序集而导致的问题。

尝试将其添加到您的

.csproj
文件中

<PropertyGroup>
    <_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
</PropertyGroup>

您可以在这里找到问题的更详细描述和解释。

© www.soinside.com 2019 - 2024. All rights reserved.