.NET中使用JWT
在控制台中使用JWT#
新建测试项目并安装包#
dotnet new sln
dotnet new console
dotnet sln add .
dotnet add package System.IdentityModel.Tokens.Jwt
生成JWT的代码#
/// <summary>
/// 创建新的Jwt
/// </summary>
public static string CreateNewJwt()
{
var claims = new List<Claim>();
//添加负载
claims.Add(new Claim(ClaimTypes.NameIdentifier, "6"));
claims.Add(new Claim(ClaimTypes.Name, "Panda"));
claims.Add(new Claim(ClaimTypes.Role, "User"));
claims.Add(new Claim(ClaimTypes.Role, "Manager"));
claims.Add(new Claim(ClaimTypes.Role, "Admin"));
claims.Add(new Claim("SomeCode", "Panda666com"));
//密钥
string key = "fasdfad&9045dafz222#fadpio@0232";
//设置过期时间
DateTime expires = DateTime.Now.AddDays(1);
byte[] secBytes = Encoding.UTF8.GetBytes(key);
var secKey = new SymmetricSecurityKey(secBytes);
var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
var tokenDescriptor = new JwtSecurityToken(claims: claims,
expires: expires, signingCredentials: credentials);
//生成jwt字符串
string jwt = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
return jwt;
}
解码JWT的代码#
/// <summary>
/// 解码JWT
/// </summary>
/// <param name="jwtString"></param>
/// <returns></returns>
public static string DecodeJwt(string jwtString)
{
string jwt = jwtString;
string[] segments = jwt.Split('.');
string head = JwtDecode(segments[0]);
string payload = JwtDecode(segments[1]);
Console.WriteLine("--------head--------");
Console.WriteLine(head);
Console.WriteLine("--------payload--------");
Console.WriteLine(payload);
string JwtDecode(string s)
{
s = s.Replace('-', '+').Replace('_', '/');
switch (s.Length % 4)
{
case 2:
s += "==";
break;
case 3:
s += "=";
break;
}
var bytes = Convert.FromBase64String(s);
return Encoding.UTF8.GetString(bytes);
}
return "";
}
验证JWT并解码#
使用JwtSecurityTokenHandler类
/// <summary>
/// 验证Jwt字符串
/// </summary>
/// <param name="jwtString"></param>
public static Dictionary<string,string> ValidJwt(string jwtString)
{
string secKey = "fasdfad&9045dafz222#fadpio@0232";
JwtSecurityTokenHandler tokenHandler = new();
TokenValidationParameters valParam = new();
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secKey));
valParam.IssuerSigningKey = securityKey;
valParam.ValidateIssuer = false;
valParam.ValidateAudience = false;
//返回值
Dictionary<string, string> result = new Dictionary<string, string>();
try
{
//解析Jwt
ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(jwtString,
valParam, out SecurityToken secToken);
foreach (var claim in claimsPrincipal.Claims)
{
result[claim.Type] = claim.Value;
}
}
catch(Exception ex)
{
}
finally
{
}
return result;
}
完整源代码#
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace Test
{
public class Program
{
public static void Main(string[] args)
{
//创建新的Jwt
string jwtEncodeString = CreateNewJwt();
Console.WriteLine(jwtEncodeString);
//读取Jwt
string jwtDecodeString = DecodeJwt(jwtEncodeString);
Console.WriteLine(jwtDecodeString);
//验证Jwt
Dictionary<string,string> result = ValidJwt(jwtEncodeString);
foreach (var item in result)
{
Console.WriteLine($"{item.Key}-{item.Value}");
}
Console.WriteLine("Success");
}
/// <summary>
/// 创建新的Jwt
/// </summary>
public static string CreateNewJwt()
{
var claims = new List<Claim>();
//添加负载
claims.Add(new Claim(ClaimTypes.NameIdentifier, "6"));
claims.Add(new Claim(ClaimTypes.Name, "Panda"));
claims.Add(new Claim(ClaimTypes.Role, "User"));
claims.Add(new Claim(ClaimTypes.Role, "Manager"));
claims.Add(new Claim(ClaimTypes.Role, "Admin"));
claims.Add(new Claim("SomeCode", "Panda666com"));
//密钥
string key = "fasdfad&9045dafz222#fadpio@0232";
//设置过期时间
DateTime expires = DateTime.Now.AddDays(1);
byte[] secBytes = Encoding.UTF8.GetBytes(key);
var secKey = new SymmetricSecurityKey(secBytes);
var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
var tokenDescriptor = new JwtSecurityToken(claims: claims,
expires: expires, signingCredentials: credentials);
//生成jwt字符串
string jwt = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
return jwt;
}
/// <summary>
/// 解码JWT
/// </summary>
/// <param name="jwtString"></param>
/// <returns></returns>
public static string DecodeJwt(string jwtString)
{
string jwt = jwtString;
string[] segments = jwt.Split('.');
string head = JwtDecode(segments[0]);
string payload = JwtDecode(segments[1]);
Console.WriteLine("--------head--------");
Console.WriteLine(head);
Console.WriteLine("--------payload--------");
Console.WriteLine(payload);
string JwtDecode(string s)
{
s = s.Replace('-', '+').Replace('_', '/');
switch (s.Length % 4)
{
case 2:
s += "==";
break;
case 3:
s += "=";
break;
}
var bytes = Convert.FromBase64String(s);
return Encoding.UTF8.GetString(bytes);
}
return "";
}
/// <summary>
/// 验证Jwt字符串
/// </summary>
/// <param name="jwtString"></param>
public static Dictionary<string,string> ValidJwt(string jwtString)
{
string secKey = "fasdfad&9045dafz222#fadpio@0232";
JwtSecurityTokenHandler tokenHandler = new();
TokenValidationParameters valParam = new();
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secKey));
valParam.IssuerSigningKey = securityKey;
valParam.ValidateIssuer = false;
valParam.ValidateAudience = false;
//返回值
Dictionary<string, string> result = new Dictionary<string, string>();
try
{
//解析Jwt
ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(jwtString,
valParam, out SecurityToken secToken);
foreach (var claim in claimsPrincipal.Claims)
{
result[claim.Type] = claim.Value;
}
}
catch(Exception ex)
{
}
finally
{
}
return result;
}
}
}
ASP.NET Core中使用JWT#
创建测试项目和安装包#
dotnet new sln
dotnet new webapi
dotnet sln add .
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
注册服务#
Services.Configure<JWTOptions>(builder.Configuration.GetSection("JWT"));
Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(x =>
{
var jwtOpt = builder.Configuration.GetSection("JWT").Get<JWTOptions>();
byte[] keyBytes = Encoding.UTF8.GetBytes(jwtOpt.SigningKey);
var secKey = new SymmetricSecurityKey(keyBytes);
x.TokenValidationParameters = new()
{
ValidateIssuer=false, ValidateAudience=false, ValidateLifetime=true,
ValidateIssuerSigningKey=true, IssuerSigningKey=secKey
};
});
使用服务#
在Program.cs的app.UseAuthorization之前添加:
app.UseAuthentication();
在控制器中使用(创建Token)#
[HttpPost(Name = "CreateJwt")]
[AllowAnonymous]
public async Task<string> CreateJwt(string userName = "",string password = "")
{
//如果验证用户名和密码出现错误
if (false)
{
return "";
}
var claims = new List<Claim>();
//添加负载
//用户Id
claims.Add(new Claim(ClaimTypes.NameIdentifier,"UserId"));
//用户名
claims.Add(new Claim(ClaimTypes.Name, "UserName"));
//用户角色
var roles = new List<string>() { "User", "Manager", "Admin" };
foreach (string role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
//其他内容
claims.Add(new Claim("SomeCode", "Panda666com"));
//创建jwtToken
string jwtToken = CreateNewJwt(claims, "fasdfad&9045dafz222#fadpio@0232");
return jwtToken;
}
/// <summary>
/// 创建新的Jwt
/// </summary>
/// <param name="claims">负载</param>
/// <param name="key">密钥</param>
/// <returns></returns>
public string CreateNewJwt(List<Claim> claims, string key)
{
//设置过期时间
DateTime expires = DateTime.Now.AddDays(1);
byte[] secBytes = Encoding.UTF8.GetBytes(key);
var secKey = new SymmetricSecurityKey(secBytes);
var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
var tokenDescriptor = new JwtSecurityToken(claims: claims,
expires: expires, signingCredentials: credentials);
//生成jwt字符串
string jwt = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
return jwt;
}
在控制器中使用(验证Token)#
注意:需要登录才能访问的控制器类上添加[Authorize]特性
[HttpPost(Name = "ValidJwt")]
public IActionResult ValidJwt(string jwtString)
{
string secKey = "fasdfad&9045dafz222#fadpio@0232";
JwtSecurityTokenHandler tokenHandler = new();
TokenValidationParameters valParam = new();
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secKey));
valParam.IssuerSigningKey = securityKey;
valParam.ValidateIssuer = false;
valParam.ValidateAudience = false;
//返回值
Dictionary<string, string> result = new Dictionary<string, string>();
try
{
//解析Jwt
ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(jwtString,
valParam, out SecurityToken secToken);
foreach (var claim in claimsPrincipal.Claims)
{
result[claim.Type] = claim.Value;
}
}
catch (Exception ex)
{
}
finally
{
}
string temp = "";
foreach (var item in result)
{
temp += $"{item.Key}-{item.Value}";
}
return Ok($"{temp}");
}
作者:重庆熊猫
出处:https://www.cnblogs.com/cqpanda/p/17012151.html
版权:本作品采用「不论是否商业使用都不允许转载,否则按3元1字进行收取费用」许可协议进行许可。
本文来自博客园,作者:重庆熊猫,转载请注明原文链接:https://www.cnblogs.com/cqpanda/p/17012151.html
Buy me a cup of coffee ☕.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具