// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapGrpcService <GreeterService>(); endpoints.MapGet("/token", async context => { var jwtConfig = new JwtConfig(); configuration.GetSection("Jwt").Bind(jwtConfig); var token = JwtHelper.CreateAccessToken(context.Request.Query["name"], jwtConfig); await context.Response.WriteAsync(token); }); }); }
public static string CreateAccessToken(string userName, JwtConfig jwtConfig) { var authTime = DateTime.UtcNow; var expiresAt = authTime.AddDays(7); var claims = new Claim[] { new Claim(JwtClaimTypes.Name, userName), }; var keyByteArray = Encoding.ASCII.GetBytes(jwtConfig.Key); var signingKey = new SymmetricSecurityKey(keyByteArray); var jwt = new JwtSecurityToken( issuer: jwtConfig.Iss, audience: jwtConfig.Aud, claims: claims, notBefore: authTime, expires: expiresAt, signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)); return(new JwtSecurityTokenHandler().WriteToken(jwt)); }