我正在尝试学习如何将Add Jwt用于我正在使用的API。 关于如何使用Jwt构建API,我已经跟进了这个introduction。 我的应用程序现在确实生成了Jwt代码但是当我调用API的Authorize部分时,使用Authorization标头和Bearer使用post man我得到401 Unauthrized响应。 我的代码是
StattUp.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();
}
}
TokenController.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/"
}
}
P.S 我试过打电话给http://localhost:50431/api/books 使用邮递员
授权:承载eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MjE1NzgxMTgsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTA0MzEvIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo1MDQzMS8ifQ.D4o7ruHv4d6QFKQvOFTmtKwlbIgvTF-PnYJXUdaRCg8
我没有运气,所以任何帮助都会受到赞赏
答案 0 :(得分:5)
这是一个非常常见的错误。您应该在MVC中间件之前添加身份验证中间件。这个命令真的很重要。
请按以下方式修复问题更改Startup.Configure
方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
查看以下文章了解更多详情: