private string GetSecurityToken() { string issuer = ConfigurationManager.AppSettings["issuer"]; string audience = ConfigurationManager.AppSettings["audience"]; string signingKey = ConfigurationManager.AppSettings["signingKey"]; List <Claim> claims = new List <Claim>(); claims.Add(new Claim("http://pegasusmission.io/claims/name", Guid.NewGuid().ToString())); claims.Add(new Claim("http://pegasusmission.io/claims/role", "gateway")); return(JwtSecurityTokenBuilder.Create(issuer, audience, claims, 2000, signingKey)); }
private void SetupJwtTokenAuthentication(IServiceCollection services, IConfiguration configuration) { var jwtPrivateKeyEnvironmentVariable = configuration["Authentication:Jwt:PrivateKeyEnvironmentVariable"]; SymmetricSecurityKey privateKey; try { privateKey = new SymmetricSecurityKey(Convert.FromBase64String(Secrets.Get(jwtPrivateKeyEnvironmentVariable))); } catch (KeyNotFoundException) { using var rng = new RNGCryptoServiceProvider(); var bytes = new byte[32]; rng.GetBytes(bytes); privateKey = new SymmetricSecurityKey(bytes); Console.WriteLine( $"JWT private key candidate: {Convert.ToBase64String(bytes)}. Store this as environment variable '{jwtPrivateKeyEnvironmentVariable}'."); } services.AddAuthentication( x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer( options => { options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = privateKey, ValidateIssuer = false, // TODO Change after move to production environment ValidateAudience = false // TODO Change after move to production environment }; }); var jwtTokenBuilder = new JwtSecurityTokenBuilder(privateKey, TimeSpan.FromMinutes(60)); services.AddSingleton <ISecurityTokenBuilder>(jwtTokenBuilder); }