首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >c# asp.net核心承载error="invalid_token“

c# asp.net核心承载error="invalid_token“
EN

Stack Overflow用户
提问于 2019-01-28 13:11:20
回答 5查看 24.9K关注 0票数 14

有人能帮我解决这个问题吗?我正在使用Postman测试API

我正在学习一个关于asp.net核心的教程。

我现在负责它的身份验证部分。

我真的不明白这个错误的原因是什么。

在本教程中,它有一个登录并返回token。

这是登录的代码。这是有效的。我知道这是有效的,因为它返回一个令牌。我还尝试使用无效的登录。它返回401 Unauthorized,但是当我使用在数据库中找到的正确登录凭据时。它返回token

代码语言:javascript
运行
复制
[HttpPost("login")]
public async Task<IActionResult> Login(UserForLoginDto userForLoginDto)
    {
        var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

        if (userFromRepo == null)
            return Unauthorized();

        var claims = new[]
        {
            new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
            new Claim(ClaimTypes.Name, userFromRepo.Username)
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims),
            Expires = DateTime.Now.AddDays(1),
            SigningCredentials = creds
        };

        var tokenHandler = new JwtSecurityTokenHandler();

        var token = tokenHandler.CreateToken(tokenDescriptor);

        return Ok(new {
            token = tokenHandler.WriteToken(token)
        });
}

然后,本教程的下一部分是限制访问。用户应先登录才能查看内容。

下面是代码

代码语言:javascript
运行
复制
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>{
                options.TokenValidationParameters = new TokenValidationParameters{
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer = false
                };
            });

然后启用

代码语言:javascript
运行
复制
app.UseAuthentication();

我还在Values控制器中启用了[Authorize]

代码语言:javascript
运行
复制
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase

这是邮递员的截图

我遵循了教程。我粘贴从登录收到的令牌。但是它给了我一个错误

代码语言:javascript
运行
复制
WWW-Authenticate →Bearer error="invalid_token", error_description="The audience is invalid"

如果令牌来自登录,为什么错误会显示invalid token?我该如何解决这个问题?我已经找了一段时间了,但我自己解决不了这个问题。谢谢。

EN

回答 5

Stack Overflow用户

发布于 2019-01-28 13:31:37

我最近使用JWT token做了类似的事情,它与Postman一起工作得很好。我创建JWT令牌的方法略有不同,在您的例子中,问题可能是由于没有指定 issueraudience

你能试着像下面这样。

代码语言:javascript
运行
复制
   var claims = new List<Claim>
    {
        new Claim(ClaimTypes.WindowsAccountName, this.User.Identity.Name)
    };
    Claim userIdClaim = new Claim("UserId", "12345");
    claims.Add(userIdClaim);
    //Avoid Replay attack
    claims.Add(new Claim(ClaimTypes.GivenName, "User GivenName"));
    claims.Add(new Claim(ClaimTypes.Surname, "UserSurname"));
    claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));

    string[] roles = "Role1,Role2,Role23".Split(",");

    foreach (string role in roles)
    {
        claims.Add(new Claim(role, ""));
    }

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("veryVerySecretKey"));
    var key1 = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ASEFRFDDWSDRGYHF")); 
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    var encryptingCreds = new EncryptingCredentials(key1, SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256);
    var handler = new JwtSecurityTokenHandler();
    var t = handler.CreateJwtSecurityToken();
    var token = handler.CreateJwtSecurityToken("http://localhost:61768/", "http://localhost:61768/"
        , new ClaimsIdentity(claims)
        , expires: DateTime.Now.AddMinutes(1)
        , signingCredentials: creds
        , encryptingCredentials :encryptingCreds
        , notBefore:DateTime.Now
        ,  issuedAt:DateTime.Now);
    return new JwtSecurityTokenHandler().WriteToken(token);

我的ConfigureServices看起来像

代码语言:javascript
运行
复制
services.AddAuthentication()
            .AddJwtBearer(options =>
             {
                 options.RequireHttpsMetadata = false;
                 options.SaveToken = true;
                 options.TokenValidationParameters = new TokenValidationParameters
                 {
                     ValidateIssuer = true,
                     ValidateAudience = true,
                     ValidateLifetime = true,
                     ValidateIssuerSigningKey = true,
                     ValidIssuer = "http://localhost:61768/",
                     ValidAudience = "http://localhost:61768/",
                     TokenDecryptionKey= new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ASEFRFDDWSDRGYHF")),
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("veryVerySecretKey")),
                     ClockSkew = TimeSpan.Zero
                 };
             });

注意:适当更改颁发者和密钥。

票数 7
EN

Stack Overflow用户

发布于 2020-08-08 17:30:37

我遇到了一个类似的问题,.net Core3API无法验证自己的令牌。

我的解决方案是在Startup/Configure()中,将app.UseAuthentication()放在app.UseAuthorization()之前。

代码语言:javascript
运行
复制
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
    app.UseAuthentication();

    app.UseAuthorization();
 }
票数 6
EN

Stack Overflow用户

发布于 2019-01-28 14:25:07

您收到的错误与受众有关,您应该在选项中包括ValidAudience或将ValidateAudience设置为false。

代码语言:javascript
运行
复制
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options => {
            options.TokenValidationParameters = new TokenValidationParameters{
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
            ValidateIssuer = false,
            ValidateAudience = false
          };
        });
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54395859

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档