首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
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

Stack Overflow用户

发布于 2019-10-28 04:27:57

我也有同样的问题。请注意,配置函数中的顺序。

app.usemvc ();应该在底部。如下所示:

代码语言:javascript
运行
复制
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseAuthentication();
    app.UseMvc();
}
票数 0
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54395859

复制
相关文章

相似问题

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