ASP.NET Core 8.0 JWT安全实践:从认证到授权的全链路实现 ...

打印 上一主题 下一主题

主题 2131|帖子 2131|积分 6393

一、认证与授权的区别

1、概念焦点差别‌

<hr> 认证(Authentication)‌
验证用户身份的过程,确认用户是否正当且“是否是他所声称的人”。比方用户通过用户名暗码登录系统时,系统会验证凭证的有效性。


  • 在.NET中,认证的底层实现通常与 IIdentity 接口相关,该接口存储用户的根自己份信息(如用户名)。
  • 常见的认证方式包罗:Cookie 认证、JWT(JSON Web Tokens)、OAuth 2.0 等。
<hr> 授权(Authorization)‌
确定用户是否有权限访问特定资源或执行利用。比方,管理员登录后可管理系统设置,而普通用户只能检察基础数据。


  • 在.NET中,授权依赖于 IPrincipal 接口,该接口包罗用户的脚色或权限信息。
  • 实现方式包罗:基于脚色的授权、策略授权、声明(Claims)授权等。
2、功能阶段划分‌

<hr> 认证是前置条件‌
用户必须先通过认证(如登录乐成)后,系统才进一步处理授权逻辑。比方,ASP.NET Core 中的认证中间件会先验证哀求中的身份标识(如 Cookie 或 Token),若无效则直接拒绝访问。
<hr> 授权是后续决策‌
认证乐成后,系统根据用户身份(脚色、权限等)动态控制其对资源的访问权限。比方,通过 [Authorize(Roles = “Admin”)] 属性限定只有管理员脚色才气访问某个接口。
3、技术实现差别‌

    维度‌   认证(Authentication)‌   授权(Authorization)‌         焦点接口‌   ‌IIdentity(存储用户身份信息)   ‌ IPrincipal(存储用户脚色/权限信息)       ‌典范场景‌   ‌用户登录、Token 签发   ‌权限校验、资源访问控制       ‌设置方式‌   ‌通过 AddAuthentication 设置认证方案   ‌ 通过 AddAuthorization 定义策略或脚色要求   4、实际应用示例‌



  • 认证示例‌
    用户通过表单提交用户名暗码,系统验证后生成 Cookie 或 JWT,并返回给客户端。
  • 授权示例‌
    已认证的用户访问管理页面时,系统查抄其脚色是否为“Admin”,若否则返回 403 错误。
总结

认证解决“你是谁”,授权解决“你能做什么”。在.NET中,二者通过不同接口和中间件分离实现,但需协同工作以构建安全的应用程序。
二、认证(Authenication)

1、创建项目

  1. dotnet new webapi -controllers -f net8.0
复制代码

2、安装 Nuget 包

  1. # Microsoft.AspNetCore.Authentication.JwtBearer
  2. dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer -v 8.0.7
复制代码

3、生成秘钥

我们需要一个密钥用于加密和验证 JWT,可以利用利用 RandomNumberGenerator 类生成随机字节。
  1. using System;
  2. using System.Security.Cryptography;
  3. // 使用示例:
  4. var secretKey = JwtKeyGenerator.GenerateSecureSecret();
  5. Console.WriteLine($"Generated SecretKey: {
  6.      secretKey}");
  7. public class JwtKeyGenerator
  8. {
  9.    
  10.     public static string GenerateSecureSecret(int keyLengthInBytes = 32)
  11.     {
  12.    
  13.         // 生成加密安全的随机字节数组(推荐256位即32字节)
  14.         byte[] keyBytes = new byte[keyLengthInBytes];
  15.         using (var rng = RandomNumberGenerator.Create())
  16.         {
  17.    
  18.             rng.GetBytes(keyBytes);
  19.         }
  20.         // 将字节数组转换为 Base64 字符串(更紧凑且适合配置)
  21.         return Convert.ToBase64String(keyBytes);
  22.     }
  23. }
复制代码
  1. Generated SecretKey: pEZADfw6uJe8MOAozDoaAuXC+/ATW4XysMtQwH7wFmw=
复制代码
4、设置信息

在 appsettings.json 中新增节点信息:
  1.   "JwtConfig": {
  2.    
  3.     "SecretKey": "pEZADfw6uJe8MOAozDoaAuXC+/ATW4XysMtQwH7wFmw=",
  4.     "Audience": "test",
  5.     "Issuer": "test",
  6.     "Expired": 5
  7.   }
复制代码

5、JwtConfig

新增 JwtConfig 对象类,用于读取设置文件信息:
  1. using System.Text;
  2. using Microsoft.IdentityModel.Tokens;
  3. namespace JwtDemo.Config
  4. {
  5.    
  6.     public class JwtConfig
  7.     {
  8.    
  9.         /// <summary>
  10.         /// 原始密钥
  11.         /// </summary>
  12.         public string? SecretKey {
  13.     get; set; }
  14.         /// <summary>
  15.         /// 接收者
  16.         /// </summary>
  17.         public string? Issuer {
  18.     get; set; }
  19.         /// <summary>
  20.         /// 生效时间(分钟)
  21.         /// </summary>
  22.         public int Expired {
  23.     get; set; }
  24.         /// <summary>
  25.         /// 颁发者
  26.         /// </summary>
  27.         public string? Audience {
  28.     get; set; }
  29.         /// <summary>
  30.         /// 生效时间
  31.         /// </summary>
  32.         public DateTime NoteBeofre => DateTime.Now;
  33.         /// <summary>
  34.         /// 过期时间
  35.         /// </summary>
  36.         public DateTime Expiration => DateTime.Now.AddMinutes(Expired);
  37.         /// <summary>
  38.         /// 安全密钥
  39.         /// </summary>
  40.         public SecurityKey SignKey => new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey));
  41.         /// <summary>
  42.         /// 签名凭证
  43.         /// </summary>
  44.         public SigningCredentials SigningCredentials => new SigningCredentials(SignKey, SecurityAlgorithms.HmacSha256);
  45.     }
  46. }
复制代码
6、JwtHelper

新增 JwtHelper 工具类,主要用于生成息争析 Token:
  1. using System.IdentityModel.Tokens.Jwt;
  2. using System.Security.Claims;
  3. using JwtDemo.Config;
  4. namespace JwtDemo.Helper
  5. {
  6.    
  7.     public class JwtHelper
  8.     {
  9.    
  10.         private JwtConfig _jwtConfig;
  11.         public JwtHelper(JwtConfig config)
  12.         {
  13.    
  14.             _jwtConfig = config;
  15.         }
  16.         public string GetAccessToken(string userId,string password)
  17.         {
  18.    
  19.             var claims = new List<Claim>() {
  20.    
  21.                 new Claim("UserId", userId),
  22.                 new Claim("Password", password)
  23.             };
  24.             var jwtSecurityToken = new JwtSecurityToken(
  25.                     issuer: _jwtConfig.Issuer,
  26.                     audience: _jwtConfig.Audience,
  27.                     claims,
  28.                     notBefore: _jwtConfig.NoteBeofre,
  29.                     expires: _jwtConfig.Expiration,
  30.                     signingCredentials: _jwtConfig.SigningCredentials
  31.                 );
  32.             var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
  33.             return token;
  34.         }
  35.         public List<Claim> GetClaims(HttpRequest request)
  36.         {
  37.    
  38.             var authorization = request.Headers["Authorization"].ToString();
  39.             var auth = authorization.Split(" ")[1];
  40.             var handler = new JwtSecurityTokenHandler();
  41.             //反解密,获取其中的Claims
  42.             var payload = handler.ReadJwtToken(auth).Payload;
  43.             var claims = payload.Claims;
  44.             return claims.ToList();
  45.         }
  46.     }
  47. }
复制代码
7、JwtService

在这里针对 services 新增一个扩展方法 JwtService,用于注册 Jwt 服务:
  1. using JwtDemo.Config;
  2. using JwtDemo.Helper;
  3. using Microsoft.AspNetCore.Authentication.JwtBearer;
  4. namespace JwtDemo.Service
  5. {
  6.    
  7.     public static class JwtService
  8.     {
  9.    
  10.         public static void AddJwtService(this IServiceCollection services, ConfigurationManager config)
  11.         
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

守听

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表