private void Application_AuthenticateRequest(object sender, EventArgs e) { FormsAuthenticationTicket ticket = null; HttpApplication application = (HttpApplication)sender; HttpContext context = application.Context; if ((context.Request.Url.ToString().IndexOf("/Install/Default.aspx", StringComparison.OrdinalIgnoreCase) < 0) && (context.Request.Url.ToString().IndexOf("/Install/Upgrade.aspx", StringComparison.OrdinalIgnoreCase) < 0)) { //获取用于存储 Forms 身份验证票证的 Cookie 名称 string name = FormsAuthentication.FormsCookieName + "AdminCookie"; ticket = ExtractTicketFromCookie(context, name); if (ticket != null) { SlidingExpiration(context, ticket, name); AdminPrincipal principal = AdminPrincipal.CreatePrincipal(ticket); if (principal.Identity.IsAuthenticated) { principal.AdministratorInfo = Administrators.GetAdministratorByAdminName(principal.AdminName); //在这里获取管理员的权限列表 principal.Roles = RoleMembers.GetRoleIdListByAdminId(principal.AdministratorInfo.AdminId); PEContext.Current.Admin = principal; } } } }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { try { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); PrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject <PrincipalSerializeModel>(authTicket.UserData); AdminPrincipal newUser = new AdminPrincipal(authTicket.Name); newUser.UserID = serializeModel.UserID; newUser.FullName = serializeModel.FullName; newUser.LastName = serializeModel.LastName; newUser.Roles = serializeModel.Roles; newUser.AuthTocken = serializeModel.AuthTocken; newUser.Email = serializeModel.Email; newUser.Mobile = serializeModel.Mobile; newUser.Role = serializeModel.Role; newUser.Logo = serializeModel.Logo; newUser.LoginCount = serializeModel.LoginCount; HttpContext.Current.User = newUser; } catch (System.Security.Cryptography.CryptographicException cex) { FormsAuthentication.SignOut(); } } }
public void Initialize(IAppBuilder appBuilder) { /* * * Globals * *********************************/ // JsonConvert.DefaultSettings = () => new SharedJsonSettings(); /* * * DI / IoC Registrar * *********************************/ var container = GetContiner(); var domainAssemblies = GetKnownDomainAssemblies(); // container.Register <AdminStore>(); container.Register <AdminUserManager>(); container.Register <AdminSignInManager>(); container.Register(() => appBuilder.GetDataProtectionProvider()); container.Register(() => { if (AdvancedExtensions.IsVerifying(container) || HttpContext.Current == null) { return(new OwinContext().Authentication); } return(HttpContext.Current.GetOwinContext().Authentication); }); // var cloudName = AppSettings.Cloudinary.CloudName; var cloudApiKey = AppSettings.Cloudinary.CloudApiKey; var cloudApiSecret = AppSettings.Cloudinary.CloudApiSecret; var azureBlobsConnection = AppSettings.Azure.BlobsConnection; var azureBlobsDefaultContainer = AppSettings.Azure.BlobsDefaultContainer; var fileSystemStorageFolder = AppSettings.FileSystem.StorageFolder; var activeStorageService = AppSettings.ActiveStorageService; var cloudinaryStorage = Lifestyle.Singleton.CreateRegistration <IBlobStorageService>( () => new CloudinaryStorageService(cloudName, cloudApiKey, cloudApiSecret), container); var azureBlobsStorage = Lifestyle.Singleton.CreateRegistration <IAzureStorageService>( () => new AzureStorageService(azureBlobsConnection, azureBlobsDefaultContainer), container); var fileSystemStorage = Lifestyle.Singleton.CreateRegistration <IBlobStorageService>( () => new FileSystemStorageService(fileSystemStorageFolder), container); container.RegisterConditional(typeof(IBlobStorageService), cloudinaryStorage, context => "cloudinary".Equals(activeStorageService)); container.RegisterConditional(typeof(IBlobStorageService), azureBlobsStorage, context => "azurestorage".Equals(activeStorageService)); container.RegisterConditional(typeof(IBlobStorageService), fileSystemStorage, context => !context.Handled); // Defaults to filesystem var cloudinaryThumbService = Lifestyle.Singleton.CreateRegistration <ICloudinaryThumbService>( () => new CloudinaryThumbService(cloudName), container); var imageResizerThumbService = Lifestyle.Singleton.CreateRegistration <IImageResizerThumbService>( () => new ImageResizerThumbService(), container); container.RegisterConditional(typeof(IBlobThumbService), cloudinaryThumbService, context => "cloudinary".Equals(activeStorageService)); container.RegisterConditional(typeof(IBlobThumbService), imageResizerThumbService, context => !context.Handled); // Defaults to image resizer // var connectionString = WebConfigurationManager.ConnectionStrings["SqlServerConnection"].ConnectionString; container.Register <IDbConnectionFactory>(() => new SqlConnectionFactory(connectionString)); container.Register <IBlobsRepository, BlobsRepository>(); container.Register <ILogsRepository, LogsRepository>(); container.Register <IIdentityRepository, IdentityRepository>(); container.Register <IUsersRepository, UsersRepository>(); // var mailGunApiKey = AppSettings.MailGun.ApiKey; var mailGunDomainName = AppSettings.MailGun.DomainName; var defaultFromAddress = new MailAddress( AppSettings.Emails.DefaultEmailFromAddress, AppSettings.Emails.DefaultEmailFromDisplayName ); var activeEmailDispatcherService = AppSettings.ActiveEmailDispatcherService; var mailGunDispatcherService = container.Options.DefaultLifestyle.CreateRegistration <IMailGunApiEmailDispatcherService>( () => new MailGunApiEmailDispatcherService(mailGunApiKey, mailGunDomainName, defaultFromAddress), container); var netSmtpDispatcherService = container.Options.DefaultLifestyle.CreateRegistration <ISystemNetSmtpEmailDispatcherService>( () => new SystemNetSmtpEmailDispatcherService(defaultFromAddress), container); container.RegisterConditional(typeof(IEmailDispatcherService), mailGunDispatcherService, context => "mailgun".Equals(activeEmailDispatcherService)); container.RegisterConditional(typeof(IEmailDispatcherService), netSmtpDispatcherService, context => !context.Handled); // Default // container.RegisterSingleton(() => new BlobServiceConfigs() { DefaultThumbBackgroundHexColor = AppSettings.Blobs.DefaultThumbBackgroundHexColor, DefaultThumbForegroundHexColor = AppSettings.Blobs.DefaultThumbForegroundHexColor }); container.Register <IBlobService, BlobService>(); container.Register <IGlobalizationService, GlobalizationService>(); container.Register <IRealtimeService, RealtimeService>(); // container.Register(typeof(IValidator <>), domainAssemblies); container.Register(() => { if (AdvancedExtensions.IsVerifying(container) || HttpContext.Current == null) { return(SharedContext.Null); } var currentPrincipal = new AdminPrincipal(HttpContext.Current.User); return(new SharedContext( userId: currentPrincipal.Id )); }); // container.Register <IPasswordHasher, PasswordHasher>(); // container.RegisterSingleton <ILogger>(() => { var logger = new LoggerConfiguration(); var loggerFilePath = Path.Combine( AppDomain.CurrentDomain.BaseDirectory, AppSettings.Logger.StorageFolder.Trim('~').Trim('\\', '/').Replace("/", "\\"), "log_.txt" ); logger = logger.Enrich.With <SerilogActivityIdEnricher>(); logger = logger.WriteTo.Async((log) => log.File( new SerilogTextFormatter(), loggerFilePath, rollingInterval: RollingInterval.Day, shared: true )); logger = logger.WriteTo.Async((log) => log.MSSqlServer( connectionString, tableName: "Logs", autoCreateSqlTable: true )); return(logger.CreateLogger()); }); // container.Register <DatabusHub>(); // container.Verify(); /* * * Init Functionalities * *********************************/ // appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions { CookieName = AppSettings.Auth.CookieName, AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString(AppSettings.Auth.LogInPath), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <AdminUserManager, AdminUserEntity, int>( validateInterval: TimeSpan.FromMinutes(0), regenerateIdentityCallback: (manager, user) => { var currentPricipal = HttpContext.Current.User; var currentAdminPrincipal = new AdminPrincipal(currentPricipal); var currentIsPersistentState = currentAdminPrincipal.IsPersistent; var currentScreenLockState = currentAdminPrincipal.ScreenLocked; return(user.GenerateUserIdentityAsync( manager, isPersistentState: currentIsPersistentState, screenLockedState: currentScreenLockState )); }, getUserIdCallback: (user) => { return(user.GetUserId <int>()); } ) } }); // var imageResizerBlobsInfraPlugin = new ImageResizerThumbPlugin( blobService: container.GetInstance <IBlobStorageService>() ); imageResizerBlobsInfraPlugin.Install(ImageResizer.Configuration.Config.Current); // ValidatorOptions.LanguageManager = new ValidationLanguageManager(); FluentValidationModelValidatorProvider.Configure(config => { config.ValidatorFactory = new SimpleInjectorValidatorFactory(container); }); // DependencyResolver.SetResolver( new SimpleInjectorDependencyResolver(container) ); // var serializer = JsonSerializer.Create(new SharedJsonSettings() { ContractResolver = new SignalRCamelCaseJsonResolver() }); // GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer); GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => new UserIdProvider()); GlobalHost.DependencyResolver.Register(typeof(IHubActivator), () => new HubsActivator()); // appBuilder.MapSignalR(); }
protected void IbtnEnter_Click(object sender, EventArgs e) { string str = (string)this.Session["LoginName"]; string str2 = (string)this.Session["password"]; if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(str2)) { AdminPage.WriteErrMsg("<li>操作超时</li>", "Login.aspx"); } string str4 = base.Request.Form[str]; string str5 = base.Request.Form[str2]; AdministratorInfo info = Administrators.AuthenticateAdmin(str4.Trim(), str5.Trim()); if (info.IsLock) { AdminPage.WriteErrMsg("<li>此管理员已经被锁定,请联系网站管理员!</li>", "Login.aspx"); } LogInfo info2 = new LogInfo(); info2.UserName = info.AdminName; info2.UserIP = PEContext.Current.UserHostAddress; info2.ScriptName = base.Request.RawUrl; info2.Timestamp = DateTime.Now; info2.Source = ""; ILog log = LogFactory.CreateLog(); if (!info.IsNull && (string.Compare(info.AdminName, str4.Trim(), StringComparison.OrdinalIgnoreCase) == 0)) { AdminPrincipal principal = new AdminPrincipal(); principal.UserName = info.UserName; principal.AdminName = info.AdminName; principal.RndPassword = info.RndPassword; string userData = principal.SerializeToString(); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, info.AdminName, DateTime.Now, DateTime.Now.AddMinutes((double)SiteConfig.SiteOption.TicketTime), false, userData); string str8 = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName + "AdminCookie", str8); cookie.HttpOnly = true; cookie.Path = FormsAuthentication.FormsCookiePath; cookie.Secure = FormsAuthentication.RequireSSL; base.Response.Cookies.Add(cookie); if (base.Request.Cookies[FormsAuthentication.FormsCookieName] == null) { UserInfo usersByUserName = Users.GetUsersByUserName(principal.UserName); if (!usersByUserName.IsNull && (usersByUserName.Status == UserStatus.None)) { string str9 = DataSecurity.MakeRandomString(10); usersByUserName.LogOnTimes++; usersByUserName.LastLogOnTime = new DateTime?(DateTime.Now); usersByUserName.LastLogOnIP = PEContext.Current.UserHostAddress; usersByUserName.LastPassword = str9; Users.Update(usersByUserName); UserPrincipal principal2 = new UserPrincipal(); principal2.UserName = principal.UserName; principal2.LastPassword = str9; FormsAuthenticationTicket ticket2 = new FormsAuthenticationTicket(1, principal.UserName, DateTime.Now, DateTime.Now.AddDays(1.0), false, principal2.SerializeToString()); string str10 = FormsAuthentication.Encrypt(ticket2); HttpCookie cookie2 = new HttpCookie(FormsAuthentication.FormsCookieName, str10); cookie2.HttpOnly = true; cookie2.Path = FormsAuthentication.FormsCookiePath; cookie2.Secure = FormsAuthentication.RequireSSL; this.Session["UserName"] = principal2.UserName; base.Response.Cookies.Add(cookie2); } } info2.PostString = ""; info2.Category = LogCategory.LogOnOk; info2.Message = "登录成功"; info2.Title = info.AdminName + " 登录成功"; info2.Priority = LogPriority.Normal; log.Add(info2); BasePage.ResponseRedirect("Index.aspx", true); } else { info2.PostString = "\r\nFORM: " + HttpContext.Current.Request.Form.ToString() + "\r\nQUERYSTRING: " + HttpContext.Current.Request.QueryString.ToString(); info2.Category = LogCategory.LogOnFailure; info2.Message = "登录失败"; info2.Title = str4.Trim() + " 登录失败"; info2.Priority = LogPriority.Highest; log.Add(info2); AdminPage.WriteErrMsg("<li>用户登录名称或用户密码不对!</li>"); } }
public string GetUserId(IRequest request) { var user = new AdminPrincipal(request?.User); return((user?.Id ?? 0).ToString()); }