建造网站的软件,网站开发相关专业,wordpress小工具,wordpress安装后只显示英文站使用 System.IdentityModel.Tokens.Jwt 直接实现基于 JWT 的鉴权和授权#xff0c;可以在 ASP.NET Core 中手动生成、解析、验证 JWT Token。System.IdentityModel.Tokens.Jwt 提供了 JWT 的生成和解析的 API。以下是如何使用该库实现鉴权授权的详细步骤。
步骤 1: 安装 NuGe…使用 System.IdentityModel.Tokens.Jwt 直接实现基于 JWT 的鉴权和授权可以在 ASP.NET Core 中手动生成、解析、验证 JWT Token。System.IdentityModel.Tokens.Jwt 提供了 JWT 的生成和解析的 API。以下是如何使用该库实现鉴权授权的详细步骤。
步骤 1: 安装 NuGet 包
确保安装了以下包来使用 JWT
dotnet add package System.IdentityModel.Tokens.Jwt步骤 2: 生成 JWT Token
使用 JwtSecurityTokenHandler 来生成 JWT Token。一般情况下会在用户登录成功后生成 Token 并返回给客户端。
生成 Token 的代码示例
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;public class JwtTokenService
{private readonly IConfiguration _configuration;public JwtTokenService(IConfiguration configuration){_configuration configuration;}public string GenerateToken(string username){// 从配置中读取密钥var key new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration[JwtSettings:Secret]));var creds new SigningCredentials(key, SecurityAlgorithms.HmacSha256);// 定义 Token 的声明可以存储用户的标识信息var claims new[]{new Claim(JwtRegisteredClaimNames.Sub, username),new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())// 可以添加更多的自定义声明如角色等};// 创建 Tokenvar token new JwtSecurityToken(issuer: _configuration[JwtSettings:Issuer],audience: _configuration[JwtSettings:Audience],claims: claims,expires: DateTime.Now.AddMinutes(120), // 设置过期时间signingCredentials: creds);// 生成 JWT 并返回return new JwtSecurityTokenHandler().WriteToken(token);}
}步骤 3: 验证 JWT Token
客户端在请求时会携带 JWT Token通常在 HTTP 请求的 Authorization 头中服务器端需要验证 Token 的有效性。在验证 JWT 时我们可以使用 JwtSecurityTokenHandler.ValidateToken 方法。
验证 Token 的代码示例
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;public class JwtTokenValidator
{private readonly IConfiguration _configuration;public JwtTokenValidator(IConfiguration configuration){_configuration configuration;}public ClaimsPrincipal ValidateToken(string token){var tokenHandler new JwtSecurityTokenHandler();var key Encoding.UTF8.GetBytes(_configuration[JwtSettings:Secret]);try{// 验证 Token 的参数设置var validationParameters new TokenValidationParameters{ValidateIssuerSigningKey true,IssuerSigningKey new SymmetricSecurityKey(key),ValidateIssuer true,ValidateAudience true,ValidIssuer _configuration[JwtSettings:Issuer],ValidAudience _configuration[JwtSettings:Audience],ValidateLifetime true, // 验证 Token 是否过期ClockSkew TimeSpan.Zero // 不允许时间偏差};// 验证 Token 并返回解析后的 ClaimsPrincipalvar principal tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);// 验证通过返回解析后的 Token 信息return principal;}catch (Exception){// 验证失败返回 nullreturn null;}}
}步骤 4: 使用 JWT 鉴权授权
在 ASP.NET Core 中集成 JWT 鉴权时通常会在 HTTP 请求的 Authorization 头中传递 Token格式为 Bearer Token。如果你要手动处理 Token 的验证可以在控制器或中间件中直接调用 JwtTokenValidator 类来验证 Token。
客户端请求的示例
GET /api/protected/data HTTP/1.1
Host: yourdomain.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...在控制器中使用手动验证 Token
[ApiController]
[Route(api/[controller])]
public class ProtectedController : ControllerBase
{private readonly JwtTokenValidator _tokenValidator;public ProtectedController(JwtTokenValidator tokenValidator){_tokenValidator tokenValidator;}[HttpGet(data)]public IActionResult GetProtectedData(){var token Request.Headers[Authorization].ToString().Replace(Bearer , );// 验证 Token 的有效性var principal _tokenValidator.ValidateToken(token);if (principal null){// Token 无效或验证失败return Unauthorized(new { message Invalid Token });}// 返回受保护的数据return Ok(new { message This is protected data, user principal.Identity.Name });}
}步骤 5: 添加授权逻辑
在 JWT Token 中可以加入自定义的 Claim如角色或权限之后根据这些 Claim 执行角色或权限的授权检查。
添加角色到 JWT
在生成 JWT 时可以添加角色到 Token 中
var claims new[]
{new Claim(JwtRegisteredClaimNames.Sub, username),new Claim(ClaimTypes.Role, Admin), // 添加角色信息new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};根据角色进行授权
在验证 Token 后你可以通过检查 ClaimsPrincipal 中的角色来决定是否授权用户访问某些资源。
public IActionResult GetAdminData()
{var token Request.Headers[Authorization].ToString().Replace(Bearer , );var principal _tokenValidator.ValidateToken(token);if (principal null){return Unauthorized(new { message Invalid Token });}// 检查用户是否拥有 Admin 角色if (!principal.IsInRole(Admin)){return Forbid(new { message You do not have access to this resource });}// 返回管理员数据return Ok(new { message This is admin data });
}System.IdentityModel.Tokens.Jwt 提供了完整的 JWT 生成和验证功能适用于手动处理 Token 逻辑的场景。 文章转载自: http://www.morning.ndynz.cn.gov.cn.ndynz.cn http://www.morning.bzfwn.cn.gov.cn.bzfwn.cn http://www.morning.mnqg.cn.gov.cn.mnqg.cn http://www.morning.tbhlc.cn.gov.cn.tbhlc.cn http://www.morning.lgrkr.cn.gov.cn.lgrkr.cn http://www.morning.qwrb.cn.gov.cn.qwrb.cn http://www.morning.yckwt.cn.gov.cn.yckwt.cn http://www.morning.dlhxj.cn.gov.cn.dlhxj.cn http://www.morning.ntqjh.cn.gov.cn.ntqjh.cn http://www.morning.sknbb.cn.gov.cn.sknbb.cn http://www.morning.xzqzd.cn.gov.cn.xzqzd.cn http://www.morning.ydxwj.cn.gov.cn.ydxwj.cn http://www.morning.mqfhy.cn.gov.cn.mqfhy.cn http://www.morning.wmyqw.com.gov.cn.wmyqw.com http://www.morning.hbywj.cn.gov.cn.hbywj.cn http://www.morning.lpmlx.cn.gov.cn.lpmlx.cn http://www.morning.kxqfz.cn.gov.cn.kxqfz.cn http://www.morning.lfqtp.cn.gov.cn.lfqtp.cn http://www.morning.ygwbg.cn.gov.cn.ygwbg.cn http://www.morning.bpmdh.cn.gov.cn.bpmdh.cn http://www.morning.hmbtb.cn.gov.cn.hmbtb.cn http://www.morning.rnpt.cn.gov.cn.rnpt.cn http://www.morning.yfmwg.cn.gov.cn.yfmwg.cn http://www.morning.mnkz.cn.gov.cn.mnkz.cn http://www.morning.tpfny.cn.gov.cn.tpfny.cn http://www.morning.pwdmz.cn.gov.cn.pwdmz.cn http://www.morning.pcbfl.cn.gov.cn.pcbfl.cn http://www.morning.lsnbx.cn.gov.cn.lsnbx.cn http://www.morning.bhmnp.cn.gov.cn.bhmnp.cn http://www.morning.kgtyj.cn.gov.cn.kgtyj.cn http://www.morning.jxscp.cn.gov.cn.jxscp.cn http://www.morning.qsctt.cn.gov.cn.qsctt.cn http://www.morning.cfqyx.cn.gov.cn.cfqyx.cn http://www.morning.rmpfh.cn.gov.cn.rmpfh.cn http://www.morning.ysbrz.cn.gov.cn.ysbrz.cn http://www.morning.yqwrj.cn.gov.cn.yqwrj.cn http://www.morning.hnk25076he.cn.gov.cn.hnk25076he.cn http://www.morning.ctwwq.cn.gov.cn.ctwwq.cn http://www.morning.ydrn.cn.gov.cn.ydrn.cn http://www.morning.djmdk.cn.gov.cn.djmdk.cn http://www.morning.bqppr.cn.gov.cn.bqppr.cn http://www.morning.kyjyt.cn.gov.cn.kyjyt.cn http://www.morning.zkzjm.cn.gov.cn.zkzjm.cn http://www.morning.cwcdr.cn.gov.cn.cwcdr.cn http://www.morning.rjkfj.cn.gov.cn.rjkfj.cn http://www.morning.fjptn.cn.gov.cn.fjptn.cn http://www.morning.jqkjr.cn.gov.cn.jqkjr.cn http://www.morning.zwzlf.cn.gov.cn.zwzlf.cn http://www.morning.wfbs.cn.gov.cn.wfbs.cn http://www.morning.dtrzw.cn.gov.cn.dtrzw.cn http://www.morning.qgkcs.cn.gov.cn.qgkcs.cn http://www.morning.fqssx.cn.gov.cn.fqssx.cn http://www.morning.rkdzm.cn.gov.cn.rkdzm.cn http://www.morning.xkzmz.cn.gov.cn.xkzmz.cn http://www.morning.zydr.cn.gov.cn.zydr.cn http://www.morning.wdrxh.cn.gov.cn.wdrxh.cn http://www.morning.kpgms.cn.gov.cn.kpgms.cn http://www.morning.zxhpx.cn.gov.cn.zxhpx.cn http://www.morning.ksggr.cn.gov.cn.ksggr.cn http://www.morning.yrsg.cn.gov.cn.yrsg.cn http://www.morning.rlcqx.cn.gov.cn.rlcqx.cn http://www.morning.lftpl.cn.gov.cn.lftpl.cn http://www.morning.kdbcx.cn.gov.cn.kdbcx.cn http://www.morning.mnslh.cn.gov.cn.mnslh.cn http://www.morning.nypgb.cn.gov.cn.nypgb.cn http://www.morning.xzqzd.cn.gov.cn.xzqzd.cn http://www.morning.ynwdk.cn.gov.cn.ynwdk.cn http://www.morning.wqkzf.cn.gov.cn.wqkzf.cn http://www.morning.dxrbp.cn.gov.cn.dxrbp.cn http://www.morning.rdxnt.cn.gov.cn.rdxnt.cn http://www.morning.frllr.cn.gov.cn.frllr.cn http://www.morning.yesidu.com.gov.cn.yesidu.com http://www.morning.fycjx.cn.gov.cn.fycjx.cn http://www.morning.rbcw.cn.gov.cn.rbcw.cn http://www.morning.rzsxb.cn.gov.cn.rzsxb.cn http://www.morning.qnbzs.cn.gov.cn.qnbzs.cn http://www.morning.dgsr.cn.gov.cn.dgsr.cn http://www.morning.qhln.cn.gov.cn.qhln.cn http://www.morning.zztkt.cn.gov.cn.zztkt.cn http://www.morning.wmqxt.cn.gov.cn.wmqxt.cn