以下是一个使用Asp.net Core进行身份认证的示例代码:
首先,确保你的项目已经添加了Microsoft.AspNetCore.Authentication和Microsoft.AspNetCore.Authentication.JwtBearer NuGet包。
在Startup.cs文件中,配置身份认证服务:
public void ConfigureServices(IServiceCollection services)
{
// 添加身份认证服务
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your-issuer",
ValidAudience = "your-audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
};
});
// 其他配置...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// 启用身份认证中间件
app.UseAuthentication();
// 其他中间件配置...
}
[Authorize]
public class ProtectedController : Controller
{
// ...
}
这样,只有经过认证的用户才能访问ProtectedController中的Action。
public async Task Login(LoginModel model)
{
// 验证用户名和密码...
// 如果验证通过,生成JWT
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("your-secret-key");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, model.Username)
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
// 返回JWT
return Ok(new { Token = tokenString });
}
在上述代码中,你可以根据需要自定义生成JWT的逻辑和过期时间。
希望这个例子可以帮助到你!