C# Jwt代码在.NET Core 2上不起作用
我正在尝试学习如何将Jwt添加到我正在开发的API中。 我随后介绍了如何使用Jwt构建API。 我的应用程序现在确实生成了Jwt代码,但是当我调用API的Authorize部分时,使用postman的Authorization头和Bearer,我得到了401个未授权的响应。 我的代码是 StattUp.csC# Jwt代码在.NET Core 2上不起作用,c#,api,asp.net-core,jwt,asp.net-core-2.0,C#,Api,Asp.net Core,Jwt,Asp.net Core 2.0,我正在尝试学习如何将Jwt添加到我正在开发的API中。 我随后介绍了如何使用Jwt构建API。 我的应用程序现在确实生成了Jwt代码,但是当我调用API的Authorize部分时,使用postman的Authorization头和Bearer,我得到了401个未授权的响应。 我的代码是 StattUp.cs public class Startup { public Startup(IConfiguration configuration) { Configura
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; }
}
}
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; }
}
BooksController.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; }
}
}
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; }
}
附言
我试过打电话给警察
使用邮递员
授权:持票人EYJHBGCIOIJIUZI1NIISINR5CCIKPXVCJ9.EYJLEHAIOJE1MJE1NZGXMTGSIMLZCYI6IMH0DHA6Y9SB2HBGHVC3Q6NTA0MZEVIWIYXVKIJOIAHR0CDOVL2XVY2FSAG9ZDDO1MDQZMS8IFQ.D4RUHV4D6QFVOFTKWLBIGVTF-PNYXUDARCG8
而且我运气不好,所以任何帮助都将不胜感激这是一个非常常见的错误。您应该在MVC中间件之前添加认证中间件。这里的秩序很重要 因此,要解决问题,请更改
启动。按以下方式配置方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
查看以下文章了解更多详细信息:
授权:和持有人之间是否有空格?我想您需要在它们之间留一个空格,例如授权:bearier ey…@SimplyGed我已经尝试了空格和空格之外的方式,两者都返回401