首页 > 解决方案 > 真正的 Jwt 令牌认证

问题描述

我使用 jwt 令牌进行身份验证,我想从数据库中查找,但我不知道如何访问数据库以检查用户而不是硬编码用户名

请看下面的代码=>

启动 :

          var key = "123456789fsdphvsaihbviasvsifhdsfdsilafhiopadhfiafosia";
        services.AddSingleton<IJwtAuthentication>(new JwtAuthentication(key)); 

        services.AddAuthentication(z =>
        {
            z.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            z.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(z =>
        {
            z.RequireHttpsMetadata = false;
            z.SaveToken = true;
            z.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtSettings.Secret)),
                ValidateIssuer = false,
                ValidateAudience = false,
                ValidateLifetime = true
            };
        });

我的 jwt 令牌管理器:

 public class JwtAuthentication : IJwtAuthentication
{
    private readonly DataContext _db;
    private readonly string _key;
    private IDictionary<string, string> db;
    public JwtAuthentication(/*DataContext db,*/ string key)
    {
        // _db = db; 
         db = new Dictionary<string, string>();
        db.Add("user", "password"); 
        _key = key;
    }
    public string Authenticate(string username, string password)
    {
        /*  if (!_db.Set<Account>().Any(z => z.UserName == username && z.Password == password.Hash()))
              return null;*/
        if (!db.Any(z => z.Key == username && z.Value == password))
        {
            return null;
        }

        var tokenHandler = new JwtSecurityTokenHandler();
        var tokenKey = Encoding.UTF8.GetBytes(_key);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, username)/*,
                new Claim("Authenticated","true")*/
            }),
            Expires = DateTime.UtcNow.AddMinutes(10),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenKey), SecurityAlgorithms.HmacSha512Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }
}

jwt管理界面:

 public interface IJwtAuthentication
{
    string Authenticate(string username, string password);
}

注意:在这里进行测试我使用的是字典,但我想从我的数据库中检查用户

如果有人分享教程链接,我将非常感激。感谢您的帮助

标签: c#asp.net-coreauthenticationjwttoken

解决方案


是我个人遵循的一些很好的例子。它在某些部分可能已经过时,但仍然有效。


推荐阅读