gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:16:20 24 4
gpt4 key购买 nike

我正在尝试学习如何将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com