ASP.NET Core 6 Web API中实现登录流程的方法可以按以下步骤进行:
public class UserModel
{
public string Username { get; set; }
public string Password { get; set; }
}
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
private readonly IConfiguration _config;
public LoginController(IConfiguration config)
{
_config = config;
}
[HttpPost]
public IActionResult Login(UserModel login)
{
bool isUserValid = false;
// 在此处编写比较用户输入的登录用户名和密码与存储在数据库中的用户名和密码的比较代码
if (isUserValid)
{
var tokenString = GenerateJSONWebToken(login);
return Ok(new { token = tokenString });
}
else
{
return Unauthorized();
}
}
private string GenerateJSONWebToken(UserModel userInfo)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
_config["Jwt:Issuer"],
null,
expires: DateTime.Now.AddMinutes(120),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
在上述代码中,需要编写比较用户输入的用户名和密码与存储在数据库中的用户名和密码的比较代码。若比较结果为正确,则需要生成一个JSON Web Token并返回给客户端。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
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"]))
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
app.UseRouting();