[英]Real Jwt token Authentication
我使用 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);
}
注意:在這里進行測試我使用的是字典,但我想從我的數據庫中檢查用戶
如果有人分享教程鏈接,我將非常感激。 感謝您的幫助
這是我個人遵循的一些很好的例子。 它在某些部分可能已經過時,但仍然有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.