Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# JWT承载身份验证和授权不工作,因为TokenValidationParameters_C#_Asp.net Core_.net Core_Jwt_Asp.net Core Mvc - Fatal编程技术网

C# JWT承载身份验证和授权不工作,因为TokenValidationParameters

C# JWT承载身份验证和授权不工作,因为TokenValidationParameters,c#,asp.net-core,.net-core,jwt,asp.net-core-mvc,C#,Asp.net Core,.net Core,Jwt,Asp.net Core Mvc,我正在尝试使用.NETCore3.1制作WebAPI,并制作客户端应用程序,该应用程序将该API用于所有服务器内容。对于客户端应用程序,我使用ASP.Net Core 3.1 MVC。 在我的API上,我试图进行JWT承载身份验证和授权 JwtAuthenticationService.cs是我用来生成令牌的类 public async Task<String> GenerateJsonWebToken(ApplicationUser appUser) { var claim

我正在尝试使用.NETCore3.1制作WebAPI,并制作客户端应用程序,该应用程序将该API用于所有服务器内容。对于客户端应用程序,我使用ASP.Net Core 3.1 MVC。
在我的API上,我试图进行JWT承载身份验证和授权

JwtAuthenticationService.cs
是我用来生成令牌的类

public async Task<String> GenerateJsonWebToken(ApplicationUser appUser)
{
    var claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, appUser.UserName),
        new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
        new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(5)).ToUnixTimeSeconds().ToString())
    };

    var roleNames = await _userManager.GetRolesAsync(appUser);

    foreach (var roleName in roleNames)
    {
        claims.Add(new Claim(ClaimTypes.Role, roleName));
    }
  

    var token = new JwtSecurityToken(
        new JwtHeader(
            new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:SecretKey"])),
            SecurityAlgorithms.HmacSha256)),
        new JwtPayload(claims));
            
    return new JwtSecurityTokenHandler().WriteToken(token);
}
当我将这些参数
validateSuer
ValidateAudience
更改为true时,API不允许我访问控制器并重定向我

这是我的appsettings.json

"Jwt": {
    "SecretKey": "SomeSecretKey",
    "Issuer": "https://localhost:44393/",
    "Audience": "https://localhost:44301/"
  },

调用该端点时必须包含令牌,因为它现在受到保护。您可以在浏览器的本地存储中获取令牌,也可以根据存储方式获取cookie

然后在此处放置您的令牌:

在您的登录控制器上添加
[Authorize(Authorize(AuthenticationSchemes=“Bearer”)]
,以检查带有承载令牌的标题

当我将这些参数的validateIsuer或ValidateAudience更改为true时,API不允许我访问控制器并重定向我

因为生成的令牌中没有
颁发者
受众

如果要更改为
ValidateIssuer
validateudience
的true,请按如下所示进行更改:

var token = new JwtSecurityToken(_config["Jwt:Issuer"],
    _config["Jwt:Audience"],
    claims: claims,
    expires: DateTime.Now.AddDays(5),
    signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:SecretKey"])),
        SecurityAlgorithms.HmacSha256));

它仍然不起作用,问题是否是因为我使用了identity作为登录/reg功能?这是我在API中向登录控制器发出Post请求时得到的结果。您的API中是否有authentication scheme=“Bearer”?请试一试。
"Jwt": {
    "SecretKey": "SomeSecretKey",
    "Issuer": "https://localhost:44393/",
    "Audience": "https://localhost:44301/"
  },
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
    _config["Jwt:Audience"],
    claims: claims,
    expires: DateTime.Now.AddDays(5),
    signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:SecretKey"])),
        SecurityAlgorithms.HmacSha256));