一、认证与授权的区别
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、创建项目
- dotnet new webapi -controllers -f net8.0
复制代码
2、安装 Nuget 包
- # Microsoft.AspNetCore.Authentication.JwtBearer
- dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer -v 8.0.7
复制代码
3、生成秘钥
我们需要一个密钥用于加密和验证 JWT,可以利用利用 RandomNumberGenerator 类生成随机字节。
- using System;
- using System.Security.Cryptography;
- // 使用示例:
- var secretKey = JwtKeyGenerator.GenerateSecureSecret();
- Console.WriteLine($"Generated SecretKey: {
- secretKey}");
- public class JwtKeyGenerator
- {
-
- public static string GenerateSecureSecret(int keyLengthInBytes = 32)
- {
-
- // 生成加密安全的随机字节数组(推荐256位即32字节)
- byte[] keyBytes = new byte[keyLengthInBytes];
- using (var rng = RandomNumberGenerator.Create())
- {
-
- rng.GetBytes(keyBytes);
- }
- // 将字节数组转换为 Base64 字符串(更紧凑且适合配置)
- return Convert.ToBase64String(keyBytes);
- }
- }
复制代码- Generated SecretKey: pEZADfw6uJe8MOAozDoaAuXC+/ATW4XysMtQwH7wFmw=
复制代码 4、设置信息
在 appsettings.json 中新增节点信息:
- "JwtConfig": {
-
- "SecretKey": "pEZADfw6uJe8MOAozDoaAuXC+/ATW4XysMtQwH7wFmw=",
- "Audience": "test",
- "Issuer": "test",
- "Expired": 5
- }
复制代码
5、JwtConfig
新增 JwtConfig 对象类,用于读取设置文件信息:
- using System.Text;
- using Microsoft.IdentityModel.Tokens;
- namespace JwtDemo.Config
- {
-
- public class JwtConfig
- {
-
- /// <summary>
- /// 原始密钥
- /// </summary>
- public string? SecretKey {
- get; set; }
- /// <summary>
- /// 接收者
- /// </summary>
- public string? Issuer {
- get; set; }
- /// <summary>
- /// 生效时间(分钟)
- /// </summary>
- public int Expired {
- get; set; }
- /// <summary>
- /// 颁发者
- /// </summary>
- public string? Audience {
- get; set; }
- /// <summary>
- /// 生效时间
- /// </summary>
- public DateTime NoteBeofre => DateTime.Now;
- /// <summary>
- /// 过期时间
- /// </summary>
- public DateTime Expiration => DateTime.Now.AddMinutes(Expired);
- /// <summary>
- /// 安全密钥
- /// </summary>
- public SecurityKey SignKey => new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey));
- /// <summary>
- /// 签名凭证
- /// </summary>
- public SigningCredentials SigningCredentials => new SigningCredentials(SignKey, SecurityAlgorithms.HmacSha256);
- }
- }
复制代码 6、JwtHelper
新增 JwtHelper 工具类,主要用于生成息争析 Token:
- using System.IdentityModel.Tokens.Jwt;
- using System.Security.Claims;
- using JwtDemo.Config;
- namespace JwtDemo.Helper
- {
-
- public class JwtHelper
- {
-
- private JwtConfig _jwtConfig;
- public JwtHelper(JwtConfig config)
- {
-
- _jwtConfig = config;
- }
- public string GetAccessToken(string userId,string password)
- {
-
- var claims = new List<Claim>() {
-
- new Claim("UserId", userId),
- new Claim("Password", password)
- };
- var jwtSecurityToken = new JwtSecurityToken(
- issuer: _jwtConfig.Issuer,
- audience: _jwtConfig.Audience,
- claims,
- notBefore: _jwtConfig.NoteBeofre,
- expires: _jwtConfig.Expiration,
- signingCredentials: _jwtConfig.SigningCredentials
- );
- var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
- return token;
- }
- public List<Claim> GetClaims(HttpRequest request)
- {
-
- var authorization = request.Headers["Authorization"].ToString();
- var auth = authorization.Split(" ")[1];
- var handler = new JwtSecurityTokenHandler();
- //反解密,获取其中的Claims
- var payload = handler.ReadJwtToken(auth).Payload;
- var claims = payload.Claims;
- return claims.ToList();
- }
- }
- }
复制代码 7、JwtService
在这里针对 services 新增一个扩展方法 JwtService,用于注册 Jwt 服务:
- using JwtDemo.Config;
- using JwtDemo.Helper;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
- namespace JwtDemo.Service
- {
-
- public static class JwtService
- {
-
- public static void AddJwtService(this IServiceCollection services, ConfigurationManager config)
-
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |