用Net Core写一个登录功能,要求使用Token和有权限功能
时间: 2023-05-25 13:04:07 浏览: 49
好的,下面是用 .NET Core 实现登录功能,并使用 Token 和权限的建议步骤:
1. 首先,需要在 .NET Core 项目中添加所需的 NuGet 包,例如:Microsoft.AspNetCore.Authentication.JwtBearer。
2. 然后,在 Startup.cs 文件的 ConfigureServices 方法中,启用 JWT 身份验证:
```
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
```
3. 在 Startup.cs 文件的 Configure 方法中,启用身份验证中间件:
```
app.UseAuthentication();
```
4. 在登录控制器中,需要验证用户名和密码。如果验证通过,可以使用 JWT 库生成 Token:
```
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(Configuration["Jwt:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.Id.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
```
5. 最后,可以在控制器的 Action 方法上使用 [Authorize] 特性来控制对某