用Net Core写一个登录功能,要求使用Token和有权限功能
时间: 2024-02-05 18:10:30 浏览: 19
好的,下面是一个简单的示例代码,实现了基于Token的登录和权限验证功能。
```
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace YourNamespace
{
[ApiController]
[Route("[controller]")]
public class LoginController : ControllerBase
{
private readonly string _secretKey = "YourSecretKey";
[HttpPost]
[AllowAnonymous]
public IActionResult Login(string username, string password)
{
// TODO: 验证用户名和密码是否正确,如果正确则生成Token返回给客户端
if (username == "test" && password == "123456")
{
var token = GenerateToken(username);
return Ok(new { token });
}
else
{
return Unauthorized();
}
}
[HttpGet]
[Authorize]
public IActionResult TestAuthorize()
{
// TODO: 在这里添加需要权限验证的业务逻辑
return Ok("Authorized");
}
private string GenerateToken(string username)
{
var claims = new[] {
new Claim(ClaimTypes.Name, username),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "YourIssuer",
audience: "YourAudience",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}
```
在上面的代码中,我们使用了 `JwtBearer` 和 `Authorize` 这两个 ASP.NET Core 提供的特性。`JwtBearer` 可以帮助我们验证客户端发送过来的 Token 是否合法,而 `Authorize` 可以帮助我们实现基于 Token 的权限验证。
在 `Login` 方法中,我们验证了用户名和密码是否正确,如果正确则生成 Token 并返回给客户端。在 `TestAuthorize` 方法中,我们添加了一个 `Authorize` 特性,表示这个方法需要进行权限验证。如果客户端发送过来的 Token 没有包含正确的权限信息,则会返回 401 Unauthorized 响应。
注意,在实际项目中,我们需要将 `_secretKey` 和一些其他的配置信息放到配置文件中,避免硬编码。此外,我们还需要使用 HTTPS 协议来保证通信的安全性。