c# - 真正的 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);
}
注意:在这里进行测试我使用的是字典,但我想从我的数据库中检查用户
如果有人分享教程链接,我将非常感激。感谢您的帮助
解决方案
这是我个人遵循的一些很好的例子。它在某些部分可能已经过时,但仍然有效。
推荐阅读
- python - 强制 Django 在同一个应用程序中识别多个“模型”文件夹?
- python - 熊猫 concat 的奇怪行为
- wordpress - Gridsome + WordPress:发布内容搜索
- php - 注意未定义的变量:“字符串”(PHP)
- javascript - 在 Razor 页面中发布 JQuery/Ajax 并重定向到从 MVC 操作返回的视图(又名表单提交)
- matlab - Matlab中不定义符号变量的匿名函数的导数
- java - 根据字符串键中的标记对 JAVA Map 键进行分组
- python - Keras RNN 如何预测超过数据集
- javascript - 将完整日历中的选择事件显示到弹出窗口中
- excel - 如何在没有性能问题的情况下从 VBA 字典更新工作表?