c#

如何在C#中生成和使用token

小樊
96
2024-08-30 22:56:44
栏目: 编程语言

在C#中生成和使用token通常涉及到身份验证和授权

  1. 安装System.IdentityModel.Tokens.Jwt和Microsoft.IdentityModel.Tokens包。在.NET项目中,打开NuGet包管理器控制台并运行以下命令:
Install-Package System.IdentityModel.Tokens.Jwt
Install-Package Microsoft.IdentityModel.Tokens
  1. 创建一个方法来生成token。首先,需要创建一个RSA(非对称加密)密钥对。可以使用以下代码生成密钥对并将其保存为XML字符串:
using System.Security.Cryptography;

private static string GenerateKeyPair()
{
    using (var rsa = new RSACryptoServiceProvider(2048))
    {
        return rsa.ToXmlString(true);
    }
}
  1. 使用以下代码生成token:
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

public static string GenerateToken(string keyPair, string issuer, string audience, int expirationMinutes)
{
    var securityKey = new RsaSecurityKey(new RSACryptoServiceProvider().FromXmlString(keyPair));
    var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256Signature);

    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, "your_subject"),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
    };

    var jwt = new JwtSecurityToken(
        issuer: issuer,
        audience: audience,
        claims: claims,
        notBefore: DateTime.UtcNow,
        expires: DateTime.UtcNow.AddMinutes(expirationMinutes),
        signingCredentials: signingCredentials);

    return new JwtSecurityTokenHandler().WriteToken(jwt);
}
  1. 验证和解析token:
public static ClaimsPrincipal ValidateToken(string token, string keyPair, string issuer, string audience)
{
    var validationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = issuer,
        ValidateAudience = true,
        ValidAudience = audience,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new RsaSecurityKey(new RSACryptoServiceProvider().FromXmlString(keyPair))
    };

    var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
    var principal = jwtSecurityTokenHandler.ValidateToken(token, validationParameters, out _);

    return principal;
}
  1. 在你的应用程序中使用这些方法。例如,在ASP.NET Core Web API中,可以在登录方法中生成token,并在需要身份验证的API方法中验证token。

生成token:

var keyPair = GenerateKeyPair();
var token = GenerateToken(keyPair, "issuer", "audience", 60);

验证token:

var principal = ValidateToken(token, keyPair, "issuer", "audience");
if (principal != null)
{
    // Token is valid, proceed with the authorized operation
}
else
{
    // Token is invalid, deny access
}

注意:在实际应用中,不要在内存中存储密钥对,而是将其安全地存储在配置文件或环境变量中。此外,确保在生产环境中使用更长的过期时间。

0
看了该问题的人还看了