public void UseTokenAuthentication(IApplicationBuilder app) { app.Use(async (context, next) => { var authHeader = context.Request.Headers["Authorization"].ToString(); if (authHeader != null && authHeader.StartsWith("bearer", StringComparison.OrdinalIgnoreCase)) { var tokenStr = authHeader.Substring("Bearer ".Length).Trim(); System.Console.WriteLine(tokenStr); var handler = new JwtSecurityTokenHandler(); if (handler.ReadToken(tokenStr) is JwtSecurityToken token) { var nameid = token.Claims.First(claim => claim.Type == "nameid").Value; var identity = new ClaimsIdentity(token.Claims); context.User = new ClaimsPrincipal(identity); } } await next(); }); } private string BuildToken(IUserSession userSession, LoginCredentials credentials) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, credentials.Username), new Claim(JwtRegisteredClaimNames.Sid, userSession.SessionId), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Issuer"], claims, expires: userSession.ExpiresAt.DateTime, signingCredentials: creds); return new JwtSecurityTokenHandler().WriteToken(token); }
123900cookie-checkC# JWT Token