c# - Jwt 代码不适用于 .NET Core 2

标签 c# api asp.net-core jwt asp.net-core-2.0

我正在尝试学习如何将 Jwt 添加到我正在使用的 API。 我已经跟进了这个introduction关于如何使用 Jwt 构建 API。 我的应用程序现在确实生成了 Jwt 代码,但是当我调用 API 的授权部分时,使用授权 header 和 Bearer 使用 postman 我得到 401 Unauthrized 响应。 我的代码是

StatUp.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {


        /**/
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });

        /**/
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
        app.UseAuthentication();

    }
}

token Controller .cs

public class TokenController : Controller
{
    private IConfiguration _config;
    public TokenController (IConfiguration config)
    {
        _config = config;
    }

    [AllowAnonymous]
    [HttpPost]
    public IActionResult CreateToken (LoginModel login)
    {
        IActionResult response = Unauthorized();
        var user = Authenticate(login); 
        if (user != null)
        {
            var tokenString = BuildToken(user);
            response = Ok(new {token = tokenString });
        }
        return response;
    }
    private string BuildToken (UserModel user)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        var token = new JwtSecurityToken(_config["Jwt:Issuer"],
            _config["Jwt:Issuer"],
            expires: DateTime.Now.AddHours(30),
            signingCredentials: creds
            );

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

    private UserModel Authenticate(LoginModel login)
    {
        UserModel user = null;
        if (login.Username != null && login.Password != null)
        {
            if (login.Username.ToLower() == "r" && login.Password.ToLower() == "d")
            {
                user = new UserModel { Name = "R D", Email = "test@yahoo.com" };

            }
        }
        return user;
    }









    public class LoginModel
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

    private class UserModel
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public DateTime Birthdate { get; set; }
    }

}

BooksController.cs

 public class BooksController : Controller
{
    [HttpGet, Authorize]
    public IEnumerable<Book> Get()
    {
        var currentUser = HttpContext.User;
        var result = new Book[] {
                new Book { Author = "Ray Bradbury",Title = "Fahrenheit 451" },
                new Book { Author = "Gabriel García Márquez", Title = "One Hundred years of Solitude" },
                new Book { Author = "George Orwell", Title = "1984" },
                new Book { Author = "Anais Nin", Title = "Delta of Venus" , AgeRestriction = true}

        };
        return result; 
    }
}

public class Book
{

    public string Author { get; set; }
    public string Title { get; set; }
    public bool AgeRestriction { get; set; }
}

Appsetting.json

  {
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "Jwt": {
    "Key": "veryVerySecretKey",
    "Issuer": "http://localhost:50431/"
  }
}

附言 我试过调用http://localhost:50431/api/books 将 Postman 与

一起使用

Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MjE1NzgxMTgsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTA0MzEvIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo1MDQzMS8ifQ.D4o7ruHv4d6QFKQvOFTmtKwlbIgvTF-PnYJXUdaRCg8

我运气不好,所以任何帮助将不胜感激

最佳答案

这是一个很常见的错误。您应该在 MVC 中间件之前添加身份验证中间件。顺序在这里真的很重要。

因此,要解决此问题,请按以下方式更改 Startup.Configure 方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseAuthentication();
    app.UseMvc();
}

查看以下文章了解更多详情:

关于c# - Jwt 代码不适用于 .NET Core 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49365627/

相关文章:

api - Golang 向 API 的 POST 请求返回 400,而与 e. G。 postman 退回200

c# - 即使在 .NET Core 控制台应用程序中使用 Console.ReadLine(),docker 容器也会立即退出

asp.net - 未处理的拒绝(错误): Could not load settings for 'WebPortal' - ASP. NET Core React

c# - Linq 查询不会从另一个对象中的对象返回结果

C# 将字符串中每个句子的第一个字母大写

php - 使用 PHP 和 OAuth 访问 SkyDrive

azure - 如何诊断 AspNetCore 应用程序未在 Azure 应用服务上启动?

c# - 每次加载页面时随机显示三个不同的问题

c# - 为什么写入 MemoryStream 比写入文件慢?

c# - 是否有针对 C# 开发人员的 Microstation Api 教程?