用Net Core写一个登录功能,要求使用Token和有权限功能
时间: 2024-03-06 22:46:20 浏览: 23
好的,我可以为您提供一个简单的示例代码,使用JWT Token进行身份验证和授权。
首先,您需要在NuGet包管理器中安装以下两个包:
- Microsoft.AspNetCore.Authentication.JwtBearer
- System.IdentityModel.Tokens.Jwt
然后,在Startup.cs文件中配置身份验证和授权服务:
```csharp
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
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"))
};
});
// 添加授权服务
services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy => policy.RequireRole("admin"));
});
// 其他服务的配置...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 启用身份验证中间件
app.UseAuthentication();
// 启用授权中间件
app.UseAuthorization();
// 其他中间件的配置...
}
```
在上面的代码中,我们配置了使用JWT Token进行身份验证和授权。我们需要提供一个密钥(your_secret_key),用于签署和验证Token。我们还指定了一个颁发者(your_issuer)和一个受众(your_audience),这些信息将用于验证Token的有效性。
现在,我们可以编写一个控制器来处理登录请求和生成Token:
```csharp
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
private readonly IConfiguration _config;
public AuthController(IConfiguration config)
{
_config = config;
}
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel login)
{
// 检查用户名和密码是否正确(此处省略)
// 创建JWT Token
var token = GenerateJwtToken(login.Username);
return Ok(new { token });
}
private string GenerateJwtToken(string username)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Role, "admin") // 设置用户角色
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:SecretKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.Now.AddDays(Convert.ToDouble(_config["Jwt:ExpirationInDays"]));
var token = new JwtSecurityToken(
_config["Jwt:Issuer"],
_config["Jwt:Audience"],
claims,
expires: expires,
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
```
在上面的代码中,我们首先检查用户名和密码是否正确,然后创建一个JWT Token,并将其作为响应返回给客户端。
最后,我们可以编写另一个控制器来演示如何使用授权:
```csharp
[Authorize(Policy = "AdminOnly")]
[ApiController]
[Route("[controller]")]
public class AdminController : ControllerBase
{
[HttpGet("secret")]
public IActionResult Secret()
{
return Ok("This is a secret message for admins only.");
}
}
```
在上面的代码中,我们将控制器标记为需要“AdminOnly”策略的授权。这意味着只有具有“admin”角色的用户才能访问此控制器的操作。如果未经授权的用户尝试访问此操作,将会收到401未授权错误。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)