Im using jwt token for authentication, i want to find from database but i dont know how to access database for checking user instead of hard code usernames
please look the following code =>
start up:
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
};
});
my jwt token manager:
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 manager interface:
public interface IJwtAuthentication
{
string Authenticate(string username, string password);
}
NOTE: here for test i was using a dictionary but i want to check the user from my database
i would be really thankful if anyone share a tutorial link. thank for your help
Here is some good example that I personally followed. It may be outdated in some parts but still works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.