我已经创建了一个Angular 5 + Asp.Core应用程序并在现有用户数据库上添加了JWT身份验证
public void ConfigureServices(IServiceCollection services)
{
.............
var appSettings = appSettingsSection.Get<UserSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
}
登录控制器:
public class LoginController : Controller
{
private readonly Entities db;
private readonly UserSettings appSettings;
public LoginController(Entities _db, IOptionsSnapshot<UserSettings> _appSettings)
{
db = _db;
appSettings = _appSettings.Value;
}
[Route("/api/login")]
[HttpPost]
public IActionResult Login([FromBody] LoginData logindata)
{
var user = db.HT_USERS
.SingleOrDefault(u => u.USERNAME == logindata.Username &&
DecryptString128Bit(u.PASSW, "passwkey") == logindata.Password);
if (user == null)
{
return NotFound();
}
else
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier , user.ID.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return Ok(new
{
username = user.NAME,
token = tokenString
});
}
}
}
从Angular我从Login控制器获取令牌并将其存储到localStorage
在Angular中我得到这样的用户登录状态:
isLoggedIn() {
if (localStorage.getItem(this.tokenName)) {
return true;
}
return false;
}
一切似乎都有效,但我不知道如果用户从2台设备登录会发生什么,两者都会存储有效的令牌,但是如果它会更改帐户 密码,当前设备令牌将被更新,如果第二个设备,旧令牌仍然有效,直到它到期, 如何根据用户密码的方式生成更安全的令牌?
上面的代码怎么样,在生产中使用它是否足够安全? 感谢