我正在使用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);
}
注意:这里要进行测试,我正在使用字典,但是我想从数据库中检查用户
如果有人共享教程链接,我将非常感谢。 谢谢您的帮助