protected PathServerUtility() { IHostingEnvironment val = ServiceCollectionExtension.Get <IHostingEnvironment>(); _HostingEnvironment = val; _WebPhysicalPath = val.WebRootPath; _ContentPhysicalPath = val.ContentRootPath; if (ServiceCollectionExtension.HttpContext == null) { _WebVirtualPath = "/"; _AbsoluteUrl = "/"; } else { HttpRequest val2 = ServiceCollectionExtension.HttpContext.Request; PathString pathBase = val2.PathBase; _WebVirtualPath = pathBase.Value; if (string.IsNullOrWhiteSpace(_WebVirtualPath)) { _WebVirtualPath = "/"; } string scheme = val2.Scheme; HostString host = val2.Host; string value = host.Value; pathBase = val2.PathBase; _AbsoluteUrl = $"{scheme}://{value}{pathBase.Value}/"; } }
// 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 http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { #region "add nlogger service dependency" //adding logger dependency using extension method ServiceCollectionExtension.ConfigureLoggerService(services); //we can also use below line //services.AddSingleton<ILoggerManager, LoggerManager>(); #endregion #region "XmlInput Output formatter" //Adding support for xml input formatter and output as xml foter //Reason of adding XmlDataContractSerializerOutputFormatter as xml input formatter //is bcoz it provides datetimeoffset option while sending input services.AddMvc(setupAction => { setupAction.ReturnHttpNotAcceptable = true; setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); setupAction.InputFormatters.Add(new XmlDataContractSerializerInputFormatter()); }); #endregion // register the DbContext on the container, getting the connection string from // appSettings (note: use this during development; in a production environment, // it's better to store the connection string in an environment variable) var connectionString = Configuration["connectionStrings:libraryDBConnectionString"]; services.AddDbContext <LibraryContext>(o => o.UseSqlServer(connectionString)); // register the repository services.AddScoped <ILibraryRepository, LibraryRepository>(); }
/// <summary> /// 程序启动将任务调度表里所有状态为 执行中 任务启动起来 /// </summary> /// <param name="serviceCollection"></param> /// <returns></returns> public static IServiceCollection AddJobService(this IServiceCollection serviceCollection) { serviceCollection.BuildServiceProvider().RegisterServiceProvider(); var jobCenter = ServiceCollectionExtension.Get <IJobCenter>(); var dbContext = ServiceCollectionExtension.New <BaoDianContext>(); var jobInfoList = dbContext.TaskSchedule .Where(t => t.RunStatus.Equals((int)TaskJobStatus.DoJob)) .Select(t => new TaskScheduleModel { Id = t.Id, JobGroup = t.JobGroup, JobName = t.JobName, CronExpress = t.CronExpress, StarRunTime = t.StarRunTime, EndRunTime = t.EndRunTime, NextRunTime = t.NextRunTime, RunStatus = t.RunStatus }).ToList(); jobInfoList.ForEach(async t => { await jobCenter.AddScheduleJobAsync(t); }); return(serviceCollection); }
//========== #region auto log in public override void OnActionExecuting(ActionExecutingContext context) { var provider = ServiceCollectionExtension.Get <IActionDescriptorCollectionProvider>(); var desc1 = (context.ActionDescriptor as ControllerActionDescriptor); var desc2 = provider.ActionDescriptors.Items.Cast <ControllerActionDescriptor>() .Where(t => t.MethodInfo.GetCustomAttribute <ActionAttribute>() != null && t.DisplayName == desc1.DisplayName).FirstOrDefault(); var desc3 = desc2 ?? desc1; var action = desc3.MethodInfo.GetCustomAttribute <ActionAttribute>(); if (action != null) { var actions = ServiceCollectionExtension.Get <IPermissionService>(); if (actions != null && !actions.HasPermission(context, desc3.Id)) { return; } } if (desc3.ActionName == "Index" && desc3.ControllerName == "Home") { if (User.Identity.IsAuthenticated) { string path = HttpContext.Request.Query["from"]; if (string.IsNullOrEmpty(path)) { path = CookieUtility.GetCookie(TbConstant.LAST_LOGIN_PATH); } if (!string.IsNullOrEmpty(path) && path != "/") { context.Result = Redirect(path); } } } base.OnActionExecuting(context); }
/// <summary> /// 检查返回的token /// </summary> /// <param name="token"></param> /// <returns></returns> protected ResponsResult CheckToken(string token) { ResponsResult rModel = new ResponsResult(); try { string json = ServiceCollectionExtension.Decrypt(token); if (string.IsNullOrEmpty(json)) { return(rModel.SetStatus(ErrorCode.Relogin, "token不正确.请重新登录!")); } this.TokenModel = json.GetModel <TokenModel>(); if (this.TokenModel == null) { return(rModel.SetStatus(ErrorCode.InvalidToken, "非法请求.")); } if (string.IsNullOrEmpty(this.TokenModel.Id)) { return(rModel.SetStatus(ErrorCode.InvalidToken, "无效token.")); } //缓存+token对比时间做单点登录 //检查token里的token是否在系统注册 //Bicycle.Service.RegistActions //if (!Bicycle.Data.Entity.SystemToken.Tokens.Exists(t => this.Token.Token == t.Token)) //{ // return rModel.SetError("不匹配,非法请求.", ResponseStatus.NotAcceptable); //} } catch (Exception ex) { return(rModel.SetStatus(ErrorCode.SystemError, $"请求失败.{ex.Message}")); } return(rModel); }
/// <summary> /// 公用方法 /// </summary> /// <param name="account"></param> /// <param name="source"></param> /// <returns></returns> private ApiAccountModel GetApiAccountViewModel(Account account, SourceType source) { ApiAccountModel aModel = null; if (account.AccountStatus != (int)AccountStatus.Disabled) { aModel = new ApiAccountModel { HeadPicture = account.HeaderPic.GetPWFullPath(SystemSettingService.SystemSetting.WebSite), CreateTime = account.CreateTime, LastLoginTime = account.LastLoginTime, AccountStatus = (AccountStatus)account.AccountStatus, FullName = account.RealName, NickName = account.NicikName, Mobile = account.RealName, Token = ServiceCollectionExtension.Encrypt(new TokenModel { Id = account.Id, Mobile = account.RealName, Type = (AccountType)account.AccountType, Source = source, }.GetJson()) }; } return(aModel); }
/// <summary> /// 获取后台用户登录Cookie信息 /// </summary> /// <returns></returns> public BackstageCookie GetUserCook() { string cookie = ServiceCollectionExtension.Decrypt(CookieUtility.GetCookie(TbConstant.WEBSITE_AUTHENTICATION_SCHEME)); BackstageCookie back = new BackstageCookie(); back = cookie.GetModel <BackstageCookie>(); return(back); }
public IActionResult ValidateCode() { ValidateCode _vierificationCodeServices = new ValidateCode(); string code = ""; System.IO.MemoryStream ms = _vierificationCodeServices.Create(out code); CookieUtility.AppendCookie(TbConstant.WEBSITE_VERIFICATION_CODE, ServiceCollectionExtension.Encrypt(code)); return(File(ms.ToArray(), @"image/png")); }
/// <summary> /// 后端用户登录操作 /// </summary> /// <param name="model">AccountViewModel实体</param> /// <returns></returns> public ResponsResult Login(BackstageUserAdd model) { ResponsResult result = new ResponsResult(); string sessionCode = string.Empty; try { var code = CookieUtility.GetCookie(TbConstant.WEBSITE_VERIFICATION_CODE); if (code != null) { sessionCode = ServiceCollectionExtension.Decrypt(code); } } catch (Exception ex) { Log4Net.Debug(ex); } if (model.ErrCount >= 3) { if (!model.VerCode.ToString().ToLower().Equals(sessionCode.ToLower())) { return(result.SetStatus(ErrorCode.NotFound, "验证码输入不正确!")); } } BackstageUser account = this.First <BackstageUser>(t => t.LoginName == model.LoginName); if (account == null) { return(result.SetStatus(ErrorCode.NotFound, "账号不存在!")); } string pwd = Security.MD5(model.Password); if (!account.Password.Equals(pwd, StringComparison.OrdinalIgnoreCase)) { return(result.SetStatus(ErrorCode.InvalidPassword)); } switch (account.AccountStatus) { case (int)AccountStatus.Disabled: return(result.SetStatus(ErrorCode.AccountDisabled, "账号不可用!")); } account.LastLoginTime = DateTime.Now; account.LastLoginIp = ""; this.Update(account, true); MvcIdentity identity = new MvcIdentity(account.Id, account.LoginName, account.LoginName, account.Email, (int)account.AccountType, null, account.LastLoginTime); identity.Login(TbConstant.WEBSITE_AUTHENTICATION_SCHEME, x => { x.Expires = DateTime.Now.AddHours(25);//滑动过期时间 x.HttpOnly = true; }); return(result); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddAutoMapper(_ => { }, GetType().Assembly); services.AddDbContext <StarWarsContext>(opt => { opt.UseSqlite("Data Source=starwars.db", b => b.MigrationsAssembly("GraphQL.StarWars.Repositories")); }); ServiceCollectionExtension.AddGraphQL(services.AddRepositories() .AddGraphTypes()); return(services.BuildServiceProvider()); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SensorTrackingDbContext dbContext) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); ServiceCollectionExtension.FillDatabase(dbContext); } app.UseRouting(); app.UseAuthorization(); app.UseCors(option => option.AllowAnyOrigin()); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
static WebBase() { try { var actions = ServiceCollectionExtension.Get <IPermissionService>(); if (actions != null) { var provider = ServiceCollectionExtension.Get <IActionDescriptorCollectionProvider>(); var descriptorList = provider.ActionDescriptors.Items.Cast <ControllerActionDescriptor>() .Where(t => t.MethodInfo.GetCustomAttribute <ActionAttribute>() != null).ToList(); actions.RegistAction(descriptorList); actions.RegistRole(); } } catch (Exception ex) { Log4Net.Error(ex); } }
// 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.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); ServiceCollectionExtension.UpdateDatabase(app); }
public ResponsResult Login(string mobile, string code, string sign, string apiKey, SourceType source) { if (mobile == "18333103619") { ResponsResult result = new ResponsResult(); result.Data = new ApiAccountModel { HeadPicture = "images/baodian28.png".GetPWFullPath(SystemSettingService.SystemSetting.WebSite), CreateTime = DateTime.Now, LastLoginTime = DateTime.Now, AccountStatus = AccountStatus.Normal, FullName = "测试", NickName = "测试", Mobile = mobile, HasOrders = false, ApproveModel = ApproveModel.AutoApprove, Token = ServiceCollectionExtension.Encrypt(new TokenModel { Id = "1", Mobile = mobile, Type = AccountType.StandardUser, Source = source, }.GetJson()), }; return(result); } var _result = ApiVerifyCode(mobile, code, apiKey, sign); if (_result.Success) { var account = this.Single <Account>(t => t.AccountType == (int)AccountType.StandardUser && t.RealName == mobile); if (account == null) { account = new Account { RealName = mobile, AccountStatus = (int)AccountStatus.Normal, AccountType = (int)AccountType.StandardUser, CreateTime = DateTime.Now, PassWord = "", LastLoginTime = DateTime.Now, HeaderPic = "/images/baodian28.png".GetPWFullPath(SystemSettingService.SystemSetting.WebSite), }; base.Add(account, true); } //重置token,单设备登录! //account.Token = Guid.NewGuid(); if (account.AccountStatus == (int)AccountStatus.Disabled) { return(_result.SetStatus(ErrorCode.AccountDisabled, "你的账户已禁用!")); } if (_result.Success) { var aModel = GetApiAccountViewModel(account, source); base.Update(account, true); _result.Data = aModel; } return(_result); } else { return(_result); } }
public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { try { #region var userAgent = context.HttpContext.Request.Headers["User-Agent"].ToString(); if (userAgent.Contains("MicroMessenger")) { SourceType = SourceType.WeChatApp; ApiKey = TbConstant.WeChatApp_ApiKey; } else if (userAgent.Contains("iPhone") || userAgent.Contains("iPod") || userAgent.Contains("iPad")) { SourceType = SourceType.IOS; ApiKey = TbConstant.iOS_ApiKey; } else if (userAgent.Contains("Android")) { SourceType = SourceType.Android; ApiKey = TbConstant.Android_ApiKey; } foreach (var kv in context.HttpContext.Request.Query) { RequestParams[kv.Key] = kv.Value.ToString(); } if (context.HttpContext.Request.HasFormContentType) { foreach (var kv in context.HttpContext.Request.Form) { RequestParams[kv.Key] = kv.Value.ToString(); } } var values = context.HttpContext.GetValues(); foreach (var kv in values) { RequestParams[kv.Key] = kv.Value.ToString(); } var dict = new Dictionary <string, string>(); foreach (var kv in RequestParams) { if (kv.Value.Length > 500) { dict[kv.Key] = kv.Value.Substring(0, 500); } else { dict[kv.Key] = kv.Value; } } if (SourceType != SourceType.Unknown) { //context.Result = new ObjectResult(new Result().SetStatus(ErrorCode.Unauthorized, "请设置User-Agent请求头: 如:iPhone 或者 Android")); } else { var token = string.Empty; if (RequestParams.ContainsKey(TOKEN_Name)) { token = RequestParams[TOKEN_Name]; } if (string.IsNullOrEmpty(token)) { token = context.HttpContext.Request.Cookies["token"]; //token = CookieUtility.GetCookie("token"); } if (!context.ActionDescriptor.FilterDescriptors.Any(t => t.Filter is AllowAnonymousFilter)) { if (string.IsNullOrEmpty(token)) { context.Result = new ObjectResult(new ResponsResult(ErrorCode.Unauthorized, "The request is not contains parameter 'token'")); } else { var model = CheckToken(token); if (model.Success) { if (string.IsNullOrEmpty(this.TokenModel.Id)) { model.SetStatus(ErrorCode.Relogin, "请登录"); } else { //检查用户的token是否匹配 //var _db = ContextHelper.New<DataContext>(); //if (!_db.Account.Any(t => t.Id == Token.Id && t.Token == Token.UserToken)) //{ // model.SetError("你的账户已在其他设备登录,请重新登录!", ResponseStatus.Relogin); //} } } if (!model.Success) { context.Result = new ObjectResult(model); } } } else { string json = ServiceCollectionExtension.Decrypt(token); if (string.IsNullOrEmpty(json)) { this.TokenModel = new TokenModel(); } else { this.TokenModel = json.GetModel <TokenModel>(); } } } #endregion } catch (Exception ex) { Log4Net.Debug(ex); } return(base.OnActionExecutionAsync(context, next)); }
public void Login(string scheme, Action <CookieOptions> options = null) { CookieUtility.AppendCookie(scheme, ServiceCollectionExtension.Encrypt(JsonConvert.SerializeObject(this)), true, options); }
public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context) { if (context == null) { throw new ArgumentNullException("context"); } AuthorizationPolicy effectivePolicy = Policy; if (effectivePolicy == null) { if (PolicyProvider == null) { throw new InvalidOperationException("An AuthorizationPolicy cannot be created without a valid instance of IAuthorizationPolicyProvider."); } effectivePolicy = await AuthorizationPolicy.CombineAsync(PolicyProvider, AuthorizeData); } if (effectivePolicy != null) { MvcPrincipal newPrincipal = null; string currentScheme = effectivePolicy.AuthenticationSchemes.FirstOrDefault(); if (!string.IsNullOrEmpty(currentScheme)) { if (!(context.HttpContext.User.Identity is MvcIdentity) || !context.HttpContext.User.Identity.IsAuthenticated) { string cookie = CookieUtility.GetCookie(currentScheme, true); if (!string.IsNullOrEmpty(cookie)) { try { string value = ServiceCollectionExtension.Decrypt(cookie); MvcIdentity identity = JsonExtensions.GetModel <MvcIdentity>(value, ""); if (identity != null) { newPrincipal = identity.GetPrincipal(); } } catch { } } } else { newPrincipal = (context.HttpContext.User as MvcPrincipal); } } if (newPrincipal == null) { context.HttpContext.User = MvcIdentity.Instance.GetPrincipal(); } else { context.HttpContext.User = newPrincipal; } if (!context.Filters.Any((IFilterMetadata item) => item is IAllowAnonymousFilter)) { if (context.HttpContext.User.Identity.IsAuthenticated) { if (AuthorizeFilter == null) { AuthorizeFilter = ServiceProviderServiceExtensions.GetService <IAuthorizeFilter>(context.HttpContext.RequestServices); } if (AuthorizeFilter != null) { await AuthorizeFilter.OnAuthorizedAsync(context, currentScheme); } } else { context.Result = new ChallengeResult(effectivePolicy.AuthenticationSchemes.ToArray()); } } } }