In general projects, token authentication user information is required for docking login. Recently, we have constructed a back-end system framework based on.NET Core. The problems encountered in the process of JWT integration are shared with you below. Implementation logic:
- After login, the token is generated using JWT and the basic user information is returned to the front end
- The front-end takes the token and stores it in the front-end and passes it to the back-end with each request to the back-end interface
- The back end can receive tokens passed in by the front end and parse them using JOSE
This article mainly explains the back-end implementation, the way of front-end token storage and transfer to the back-end. Later, this article will explain separately
Firstly, the first step is to implement login and encapsulate the user information after successful login into token. The following code is attached:
[AllowAnonymous]
[HttpGet]
public IActionResult Login(string userName, string pwd)
{
var pwdMd5 = Md5Helper.Md5(Md5Helper.Md5(pwd));
if(! authService.AccountExist(userName, pwdMd5)) {return BadRequest(new { message = "Wrong username or password" });
}
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
new Claim(ClaimTypes.Name, userName),
new Claim("userId"."test"),
new Claim("name", userName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: Const.Domain,
audience: Const.Domain,
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
Copy the code
The implementation of login is not explained here, but what we need to know is that after login, we can use the following code to encapsulate part of the login user information into the token
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
new Claim(ClaimTypes.Name, userName),
new Claim("userId"."test"),
new Claim("name", userName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: Const.Domain,
audience: Const.Domain,
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
Copy the code
Here, new Claim(“userId”, “test”) and new Claim(“name”, userName) are encapsulated information of our system login user and sent to the front end. When the interface is called, it can also identify the current user according to this part of information carried in the token. Conconst.SecurityKey is the JWT encryption key and conconst.Domain is the site address configured as follows
/// <summary>
///JWT configuration class
/// </summary>
public static class Const
{
public const string SecurityKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVL G5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB";
/// <summary>
///The site address
/// </summary>
public const string Domain = "http://localhost:5000";
public static stringValidAudience; }}Copy the code
Once encapsulation is complete, a token can be generated from the encapsulated information using new JwtSecurityTokenHandler().WriteToken(token), which is then returned to the front end.
Then, when the front-end invokes the interface, it will attach the token obtained in the previous step to the Authorization field of the request header. When the back-end receives the interface request, it will obtain the token string in the request through the following codes
var headers = _httpContextAccessor.HttpContext.Request.Headers["Authorization"];
Copy the code
Jose can parse the token string as follows:
public static Object decode2(string token) {
var authInfo = Jose.JWT.Payload<UserInfo>(token.Replace("Bearer ".""));
return authInfo;
}
Copy the code
UserInfo is a user-defined user class whose field name is the same as the field name encapsulated to the token after successful login. It is used to receive the user information that is successfully resolved. In this way, you can get the user information in the token returned to the front end after successful login.
Time is tight in overtime, JWT integration and Jose installation will be explained later.