using System; using System.Text; using GxPress.Auth; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.IdentityModel.Tokens; namespace GxPress.Api.ServiceExtensions { public static class AuthenticationExtension { /// /// 添加Jwt认证授权 /// /// /// /// public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration) { var jwtSection = configuration.GetSection("JwtOptions"); var jwtOptions = new JwtOptions { Key = jwtSection["Key"], Issuer = jwtSection["Issuer"], Audience = jwtSection["Audience"], Expires = TimeSpan.FromDays(int.Parse(jwtSection["Expires"])) }; services.AddHttpContextAccessor(); services.Configure(jwtSection); services.TryAddSingleton(); ////添加授权 //services.AddAuthorization(options => //{ // options.AddPolicy("Permission", policy => // { // policy.Requirements.Add(new PermissionRequirement()); // }); //}); //services.AddSingleton(); //添加认证 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ClockSkew = TimeSpan.FromMinutes(5), ValidIssuer = jwtOptions.Issuer, ValidAudience = jwtOptions.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.Key)) }; }); return services; } /// /// 使用jwt认证 /// /// /// public static IApplicationBuilder UseJwtAuthorization(this IApplicationBuilder app) { app.UseAuthentication(); app.UseAuthorization(); return app; } } }