public static string GetToken(TokenModelJwt user)
        {
            var _jwtSetting = ServerJwtSetting.GetJwtSetting();
            // 创建用户身份标识
            var claims = new Claim[]
            {
                new Claim(JwtClaimTypes.JwtId, Guid.NewGuid().ToString()),
                new Claim(JwtClaimTypes.Id, user.Uid.ToString(), ClaimValueTypes.Integer32),
                new Claim(JwtClaimTypes.Name, user.Name, ClaimValueTypes.String),
                new Claim(JwtClaimTypes.Role, user.Role?.ToString(), ClaimValueTypes.Integer32)
            };

            // 创建令牌
            var token = new JwtSecurityToken(
                issuer: _jwtSetting.Issuer,
                audience: _jwtSetting.Audience,
                signingCredentials: _jwtSetting.Credentials,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddSeconds(_jwtSetting.ExpireSeconds)
                );

            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return(jwtToken);
        }
Exemple #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddGrpc();
            services.AddSingleton(new Appsettings());
            services.AddScoped <ICache, MemoryCaching>();
            services.AddScoped <IUser, AspNetUser>();
            services.AddSingleton <TemplateConfig>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IMemoryCache>(factory =>
            {
                var cache = new MemoryCache(new MemoryCacheOptions());
                return(cache);
            });
            services.AddScoped <SqlSugar.ISqlSugarClient>(p => DBClientManage.GetSqlSugarClient());
            services.AddSingleton <QuartzServicesClient>(p =>
            {
                Channel _channel = new Channel(Appsettings.app(new string[] { "AppSettings", "gRPCClient", "ConnectionString" }), ChannelCredentials.Insecure);
                return(new QuartzServicesClient(_channel));
            });
            services.AddSignalR();
            services.AddScoped <ICodeContext, CodeContext>();
            services.AddAutoMapperSetup();
            services.AddWebSocketManager();
            services.AddQuartzManager();
            var jwtSetting = ServerJwtSetting.GetJwtSetting();

            // 角色与接口的权限要求参数
            var permissionRequirement = new PermissionRequirement(
                "/api/error",                             // 拒绝授权的跳转地址(目前无用)
                new List <PermissionItemView>(),
                ClaimTypes.Role,                          //基于角色的授权
                jwtSetting.Issuer,                        //发行人
                jwtSetting.Audience,                      //听众
                jwtSetting.Credentials,                   //签名凭据
                expiration: TimeSpan.FromSeconds(60 * 60) //接口的过期时间
                );

            services.AddAuthorization(options =>
            {
                options.AddPolicy("public", policy => policy.RequireRole("public").Build());
            });
            // 3、复杂的策略授权
            services.AddAuthorization(options =>
            {
                options.AddPolicy(Permissions.Name,
                                  policy => policy.Requirements.Add(permissionRequirement));
            });

            // 注入权限处理器
            services.AddScoped <IAuthorizationHandler, PermissionHandler>();
            services.AddSingleton(permissionRequirement);

            services.AddAuthentication(o =>
            {
                o.DefaultScheme          = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = nameof(ApiResponseHandler);
                o.DefaultForbidScheme    = nameof(ApiResponseHandler);
            })
            .AddJwtBearer(options =>
            {
                options.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = context =>
                    {
                        // 如果过期,则把<是否过期>添加到,返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = jwtSetting.Issuer,
                    ValidAudience    = jwtSetting.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.SecurityKey)),
                    ClockSkew        = TimeSpan.Zero
                };
            })
            .AddScheme <AuthenticationSchemeOptions, ApiResponseHandler>(nameof(ApiResponseHandler), o => { });

            services.AddSwaggerGen(option =>
            {
                option.SwaggerDoc("BlogVue", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "Framework.Core API",
                    Description = "API for Framework.Core",
                });
                // 开启加权小锁
                option.OperationFilter <AddResponseHeadersFilter>();
                option.OperationFilter <AppendAuthorizeToSummaryOperationFilter>();

                // 在header中添加token,传递到后台
                option.OperationFilter <SecurityRequirementsOperationFilter>();

                // 必须是 oauth2
                option.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权在下框中输入 Bearer Token值(注意两者之间是一个空格)",
                    Name        = "Authorization",          //jwt默认的参数名称
                    In          = ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = SecuritySchemeType.ApiKey
                });
                //// 配置apixml名称
                option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml"), true);
            });

            services.AddControllers(o =>
            {
                // 全局异常过滤
                //o.Filters.Add(typeof(GlobalExceptionsFilter));
            });
            //去除Json序列化DateTime类型 T字符
            services.AddControllers().AddJsonOptions(configure =>
            {
                configure.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
            });
            //DBStartup.SeedAsync().Wait();
        }