.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}");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值