public static string GetToken(User u) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(Const.GetKey()); var tokenDescriptor = new SecurityTokenDescriptor { Issuer = Const.GetIssuer(), Audience = Const.GetIssuer(), IssuedAt = DateTime.UtcNow, NotBefore = DateTime.UtcNow, Subject = new ClaimsIdentity(new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, u.UserName), new Claim(JwtRegisteredClaimNames.Email, $"{u.UserName}@mail.com"), new Claim(ClaimTypes.Name, u.UserName), new Claim(JwtRegisteredClaimNames.Birthdate, "2019-01-01"), new Claim(JwtRegisteredClaimNames.Jti, "000000") }), Expires = DateTime.UtcNow.AddMinutes(30), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Const.GetIssuer(), ValidAudience = Const.GetIssuer(), IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.GetKey())) }; } ); services.AddSignalR(); }