Ejemplo n.º 1
0
 // This method gets called by the runtime. Use this method to add services to the container.
 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
 public void ConfigureServices(IServiceCollection services)
 {
     //
     services.AddIdentityServer()
     .AddDeveloperSigningCredential()
     .AddInMemoryApiResources(IS4Config.GetApiResources())
     .AddInMemoryClients(IS4Config.GetClients());
 }
Ejemplo n.º 2
0
        public override void ConfigureServices(IServiceCollection services)
        {
            // regist states
            services.AddSingleton <IStateProvider, UserStateProvider>();

            // regist schema
            services.AddSingleton <IStoreSchema, RbacSchema>();

            // regist services
            services.AddSingleton <IObjectService, ObjectService>();
            services.AddSingleton <IRoleService, RoleService>();
            services.AddSingleton <IPAService, PAService>();
            services.AddSingleton <IUserService, UserService>();
            services.AddSingleton <IUAService, UAService>();
            services.AddSingleton <IScaleService, ScaleService>();

            // regist AccessControl to DI for requtest scope
            services.AddScoped <IAccessControl, AccessControl>();

            // add oauth client. https://identitymodel.readthedocs.io/en/latest/client/discovery.html
            //services.AddSingleton<IDiscoveryCache>(r =>
            //{
            //    var factory = r.GetRequiredService<IHttpClientFactory>();
            //    return new DiscoveryCache(Constants.Authority, () => factory.CreateClient());
            //});

            // add identityserver
            var settings = App.AppConfig.Settings;
            var certPath = settings.GetValue <string>("oauth.certpath");
            var certPwd  = settings.GetValue <string>("oauth.certpwd");

            services.AddTransient <IResourceOwnerPasswordValidator, UserValidator>()
            .AddIdentityServer(opts =>
            {
                opts.Authentication = new AuthenticationOptions
                {
                    //CheckSessionCookieName = settings.GetValue("oauth.authcookie", "AceAuth"),
                    CookieLifetime          = TimeSpan.FromDays(settings.GetValue("oauth.expiredays", 15)),
                    CookieSlidingExpiration = true,
                    RequireAuthenticatedUserForSignOutMessage = true
                };
                opts.Caching = new CachingOptions
                {
                    ClientStoreExpiration   = TimeSpan.FromHours(24.0),
                    ResourceStoreExpiration = TimeSpan.FromHours(24.0),
                    CorsExpiration          = TimeSpan.FromHours(24.0 * 15)
                };
                #region option

                /*opts.Events = new EventsOptions
                 * {
                 *  RaiseErrorEvents = true,
                 *  RaiseFailureEvents = true,
                 *  RaiseSuccessEvents = true,
                 *  RaiseInformationEvents = true
                 * };
                 * opts.InputLengthRestrictions = new InputLengthRestrictions
                 * {
                 *  AcrValues = 100,
                 *  AuthorizationCode = 100,
                 *  ClientId = 100,
                 *  ClientSecret = 1000
                 * };
                 * opts.UserInteraction = new UserInteractionOptions
                 * {
                 *  LoginReturnUrlParameter = "returnurl",
                 *  LoginUrl = settings.GetValue("auth.loginurl", "/plat/account/login"),
                 *  LogoutUrl = settings.GetValue("auth.logouturl", "/plat/account/logout")
                 * };
                 * opts.Cors = new CorsOptions
                 * {
                 *  CorsPaths = new PathString[] { "/" },
                 *  CorsPolicyName = "all",
                 *  PreflightCacheDuration = new TimeSpan(1, 0, 0)
                 * };*/
                #endregion
            })
            .AddSigningCredential(new X509Certificate2(certPath, certPwd))
            .AddClientStore <ClientStore>()
            .AddInMemoryApiResources(IS4Config.GetApiResources());
        }
Ejemplo n.º 3
0
 public Task <Client> FindClientByIdAsync(string clientId)
 {
     return(Task.FromResult(IS4Config.GetClients().Single((Client c) => c.ClientId == clientId)));
 }
Ejemplo n.º 4
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool <GHDbContext>(option =>
            {
                option.UseMySql(Configuration["DbConnString"]);
            });
            //允许跨域请求
            services.AddCors(option => option.AddPolicy("cors",
                                                        policy => policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins(new[] { "http://xxx.xxx.com" })));

            //注册IS4服务
            var is4Buider = services.AddIdentityServer()
                            .AddDeveloperSigningCredential()
                            .AddInMemoryApiResources(IS4Config.GetApiResources())           //IS4 导入定义的应用资源API
                            .AddInMemoryIdentityResources(IS4Config.GetIdentityResources()) //IS4 自身API
                            .AddInMemoryClients(IS4Config.GetClients())                     //IS4 导入定义的客户端
                            .AddResourceOwnerValidator <IS4UserValidator>()                 //IS4 自数据库验证用户类
                            .AddProfileService <IS4ProfileService>();                       //IS4 自数据库验证用户类


            //注册验证(*用于被保护的API资源,与IS4无关* )
            string ProtectApiUrl = Configuration["ProtectApiUrl"];

            services.AddAuthentication("Bearer").AddJwtBearer(r =>
            {
                //是否必需HTTPS
                r.RequireHttpsMetadata = false;
                //认证服务地址(由于本项目APi资源与IS4服务器均在一起,故地址相同)
                r.Authority = ProtectApiUrl;
                //权限标识
                r.Audience = "PlatformApis";
            });

            services.AddControllers().AddNewtonsoftJson(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不更改元数据的key的大小写
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            })
            .AddXmlDataContractSerializerFormatters()      //添加XML数据格式支持
            .ConfigureApiBehaviorOptions(setup =>
            {
                //自定义验证错误信息。
                setup.InvalidModelStateResponseFactory = context =>
                {
                    var problemDetails = new ValidationProblemDetails(context.ModelState)
                    {
                        Type     = "Office/Work/Platform/Api",
                        Title    = "模型状态错误",
                        Status   = StatusCodes.Status422UnprocessableEntity,
                        Detail   = "一般为数据模型绑定时验证错误!",
                        Instance = context.HttpContext.Request.Path
                    };
                    problemDetails.Extensions.Add("TraceId", context.HttpContext.TraceIdentifier);
                    return(new UnprocessableEntityObjectResult(problemDetails)
                    {
                        ContentTypes = { "applaication/problem+json" }
                    });
                };
            });

            services.Configure <Microsoft.AspNetCore.Http.Features.FormOptions>(x =>
            {
                x.ValueLengthLimit         = int.MaxValue; //设置表单键值对中值的长度限制
                x.MultipartBodyLengthLimit = int.MaxValue; //设置文件上传的大小限制
                x.MemoryBufferThreshold    = int.MaxValue; //设置multipart头长度的限制
            });

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "Ver:1.0.0",
                    Title       = "Office.Work.Platform.Api",
                    Description = "政工业务平台API服务,包括:人员信息、劳资管理等"
                });
            });
        }