NetCore JWT LogIn
程序员文章站
2023-12-28 14:33:52
...
<form action="/Home/logIn" method="post">
@Html.AntiForgeryToken()
<div class="container">
<div class="row">
<div class="col-md-6">
<h1> Fast Flow System</h1>
<h3> Log In </h3>
<h3> </h3>
<h3> </h3>
</div>
<div class="col-md-6">
<div class="left">
<div class="form-bottom">
<div class="form-group">
<label class="sr-only" for="form-username">Username</label>
<input type="text" name="username" class="form-control" placeholder="请输入用户名" aria-describedby="basic-addon1">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="请输入密码" aria-describedby="basic-addon1">
<label class="sr-only" for="form-password">Password</label>
</div>
<button type="submit" id="btnsend" Class="form-control" style="background-color:#00C1DE;" >Log In</button>
<a href="ChangePassword.html">ChangePassword</a>
</div>
</div>
<div class="right">
<asp:Label ID="lblres" runat="server" Visible="false" ForeColor="Red" Font-Size="Medium"></asp:Label>
</div>
</div>
</div>
</div>
</form>
public async Task<IActionResult> OnPost(string userName, string password)
{
string returnUrl = "http://localhost:5000/";
var list = new List<dynamic> {
new { UserName = "gary", Password = "123", Role = "admin",Name="gary" },
new { UserName = "aaa", Password = "666", Role = "system",Name="garyx" }
};
var user = list.SingleOrDefault(s => s.UserName == userName && s.Password == password);
if (user != null)
{
string tokenstr = BuildToken(userName, password);
HttpContext.Response.OnStarting(state => {
HttpContext.Response.Cookies.Append("qmtoken", tokenstr);
return Task.FromResult(0);
}, HttpContext);
if (returnUrl == null)
{
returnUrl = TempData["returnUrl"]?.ToString();
}
if (returnUrl != null)
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Home", "Home");
}
}
else
{
const string badUserNameOrPasswordMessage = "用户名或密码错误!";
return BadRequest(badUserNameOrPasswordMessage);
}
}
private string BuildToken(string userid,string username)
{
DateTime UTC = DateTime.UtcNow;
Claim[] claims = new Claim[]
{
new Claim("UserID",userid),//Subject,
new Claim("Role","Admin")//Subject,
//Issued At,JWT颁发的时间,采用标准unix时间,用于验证过期
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSettings:SecretKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_config["JwtSettings:Issuer"],
_config["JwtSettings:Issuer"], claims,
expires: DateTime.Now.AddHours(12),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}