核心3.1承载401未获授权

时间:2020-07-05 19:30:57

标签: c# asp.net-core-mvc postman

我正在学习如何通过ASP使用JwtBearer和授权。净核心3.1

我正在尝试拥有一个必须由用户登录授权的控制器。这是我的代码:

我的Startup.cs文件具有:

    public void ConfigureServices(IServiceCollection services)
    {
     ...

        services.AddAuthentication()
            .AddCookie()
            .AddJwtBearer(cfg =>
            {
                cfg.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidIssuer = _config["Tokens:Issuer"],
                    ValidateAudience = true,
                    ValidAudience = _config["Tokens:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]))
                };
            }
            );
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsEnvironment("Development"))
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/error");
        }

        app.UseStaticFiles();
        app.UseNodeModules();


        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(cfg =>
        {
            cfg.MapControllerRoute("Fallback",
                "{controller}/{action}/{id?}"
                , new { controller = "App", action = "Index"}
                );
        });
    }

对于我的令牌生成代码:

    [HttpPost]
    public async Task<IActionResult> CreateToken([FromBody] LoginViewModel model)
    {
        if(ModelState.IsValid)
        {
            var user = await _userManager.FindByNameAsync(model.UserName);

            if(user != null)
            {
                var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);

                if (result.Succeeded)
                {
                    var claims = new[]
                    {
                        new Claim(JwtRegisteredClaimNames.Sub, user.Email)
                        , new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                        , new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
                    };

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));

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

                    var token = new JwtSecurityToken(
                        issuer: _config["Tokens:Issuer"]
                        , audience: _config["Tokens:Audience"]
                        , claims
                        , expires: DateTime.UtcNow.AddMinutes(30)
                        , signingCredentials: creds
                        );
                    var results = new
                    {
                        token = new JwtSecurityTokenHandler().WriteToken(token)
                        , expiration = token.ValidTo
                    };
                    return Created("", results);
                }
            }


        }

        return BadRequest();
    }

最后,对于我的控制器,我拥有名称空间

[Route("api/[Controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

我正在对Postman进行测试,并且总是得到401 Unauthorized,我读过几篇类似的文章,但是大多数答案都说它是在startup.cs上

    app.UseAuthentication();

应该先去

    app.UseAuthorization();

我的代码的那一部分似乎正确,请帮助

0 个答案:

没有答案