Example #1
0
        public static async Task <PersonalCard> Create(
            IdentityInfo identityToken,
            string privateKeyPassword = null,
            Dictionary <string, string> customData = null)
        {
            var nativeKeyPair = privateKeyPassword != null ? new VirgilKeyPair(privateKeyPassword.GetBytes()) : new VirgilKeyPair();

            using (nativeKeyPair)
            {
                var privateKey = new PrivateKey(nativeKeyPair);
                var publicKey  = new PublicKey(nativeKeyPair);

                var services = ServiceLocator.Services;

                var cardDto = await services.Cards.Create(
                    identityToken,
                    publicKey,
                    privateKey,
                    privateKeyPassword : privateKeyPassword,
                    customData : customData
                    ).ConfigureAwait(false);

                return(new PersonalCard(cardDto, privateKey));
            }
        }
        /// <inheritdoc/>
        public override IdentityInfo GetIdentityInfo()
        {
            var identityInfo = new IdentityInfo();

            identityInfo.Features = IdentityFeatures.Seed | IdentityFeatures.AutoIncrement | IdentityFeatures.AutoIncrementSettingsInMemory;
            return(identityInfo);
        }
Example #3
0
        private readonly IdentityInfo _IdentityInfo; // 获取当前登录角色相关信息

        public Repository(IUnitOfWork unitOfWork, IdentityInfo identityInfo)
        {
            UnitOfWork    = unitOfWork;
            _IdentityInfo = identityInfo;
            _StDb         = UnitOfWork.GetDb();
            _Entities     = _StDb.Set <TEntity>();
        }
 /// <summary>
 /// 权限检测
 /// </summary>
 /// <param name="filterContext"></param>
 private void AuthenCheck(ActionExecutingContext filterContext)
 {
     if (!AuthenCheckManager.IsCheck)
     {
         return;
     }
     object[] attrs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(NoAuthenCheckAttribute), false);
     if (attrs != null && attrs.Length > 0)
     {
     }
     else
     {
         if (this.LoginIdentity == null)
         {
             filterContext.Result = new RedirectResult("/Account/Login");
         }
         else
         {
             IdentityInfo identity   = this.LoginIdentity;
             string       actionName = filterContext.ActionDescriptor.ActionName.Trim();
             string       ctrlName   = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Trim();
             if (!identity.IsHasAsccessPower(actionName, ctrlName))
             {
                 filterContext.Result = new RedirectResult("/Account/Login");
             }
         }
     }
 }
Example #5
0
		/// <summary>
		///     Initializes a new instance of the CultureContextData class.
		/// </summary>
        public RequestContextData( IdentityInfo identity, TenantInfo tenant, string culture, IdentityInfo secondaryIdentity = null)
		{
			_identity = identity;
			_secondaryIdentity = secondaryIdentity;
            _tenant = tenant;
			_culture = culture;
		}
Example #6
0
        /// <summary>
        ///		Sets the context.
        /// </summary>
        /// <param name="identity">The identity.</param>
        /// <param name="tenant">The tenant.</param>
        /// <param name="culture">The culture.</param>
        /// <param name="timeZone">The time zone.</param>
        /// <param name="secondaryIdentity">The secondary identity.</param>
        public static void SetContext(IdentityInfo identity, TenantInfo tenant, string culture, string timeZone, IdentityInfo secondaryIdentity = null)
        {
            // Set the default request context data in the logical context
            var contextData = new RequestContextData(identity, tenant, culture, timeZone, secondaryIdentity);

            SetContext(contextData);
        }
Example #7
0
        /// <summary>
        ///     Sets the context data within the logical thread.
        /// </summary>
        /// <param name="identity">The identity.</param>
        /// <param name="tenant">The tenant.</param>
        /// <param name="culture">The culture.</param>
        public static void SetContext(IdentityInfo identity, TenantInfo tenant, string culture)
        {
            // Set the default request context data in the logical context
            var contextData = new RequestContextData(identity, tenant, culture);

            SetContext(contextData);
        }
Example #8
0
        public void TestIDisposable( )
        {
            RequestContext originalContext = RequestContext.GetContext( );

            try
            {
                /////
                // Create a dummy context.
                /////
                var identity = new IdentityInfo(0, "TestUser");
                var tenant   = new TenantInfo(9999);

                RequestContext.SetContext(identity, tenant, "en-US");

                /////
                // Run the administrator context.
                /////
                using (new AdministratorContext( ))
                {
                    /////
                    // Obtain the current context.
                    /////
                    RequestContext currentContext = RequestContext.GetContext( );

                    /////
                    // Confirm the current context is the administrator context.
                    /////
                    Assert.IsNotNull(currentContext);
                    Assert.IsNotNull(currentContext.Tenant);
                    Assert.IsNotNull(currentContext.Identity);
                    Assert.AreEqual(0, currentContext.Tenant.Id);
                    Assert.AreEqual(SpecialStrings.GlobalTenant, currentContext.Tenant.Name);
                    Assert.AreEqual(string.Empty, currentContext.Tenant.Description);
                    Assert.AreEqual(0, currentContext.Identity.Id);
                    Assert.AreEqual(SpecialStrings.SystemAdministratorUser, currentContext.Identity.Name);
                }

                /////
                // The current context should have reverted to the dummy context.
                /////
                RequestContext revertedContext = RequestContext.GetContext( );

                Assert.IsNotNull(revertedContext);
                Assert.IsNotNull(revertedContext.Tenant);
                Assert.IsNotNull(revertedContext.Identity);
                Assert.AreEqual(tenant.Id, revertedContext.Tenant.Id);
                Assert.AreEqual(0, revertedContext.Identity.Id);
                Assert.AreEqual(identity.Name, revertedContext.Identity.Name);
            }
            finally
            {
                /////
                // Restore any context that was active at the start of the test.
                /////
                if (originalContext.IsValid)
                {
                    RequestContext.SetContext(originalContext);
                }
            }
        }
Example #9
0
        public static async Task <PersonalCard> LoadLatest(IdentityInfo token, string privateKeyPassword = null)
        {
            var services     = ServiceLocator.Services;
            var searchResult = await services.Cards.Search(token.Value, token.Type)
                               .ConfigureAwait(false);

            var card = searchResult
                       .OrderByDescending(it => it.CreatedAt)
                       .Select(it => new { PublicKeyId = it.PublicKey.Id, Id = it.Id })
                       .FirstOrDefault();

            if (card == null)
            {
                throw new CardNotFoundException("Card not found");
            }

            var grabResponse = await services.PrivateKeys.Get(card.Id, token)
                               .ConfigureAwait(false);

            if (!VirgilKeyPair.CheckPrivateKeyPassword(grabResponse.PrivateKey, privateKeyPassword.GetBytes()))
            {
                throw new WrongPrivateKeyPasswordException("Wrong password");
            }

            var privateKey = new PrivateKey(grabResponse.PrivateKey);

            var cards = await services.Cards.GetCardsRealtedToThePublicKey(card.PublicKeyId, card.Id, privateKey, privateKeyPassword)
                        .ConfigureAwait(false);

            return
                (cards.Select(it => new PersonalCard(it, privateKey))
                 .OrderByDescending(it => it.CreatedAt)
                 .FirstOrDefault());
        }
Example #10
0
        public UserEntity GenerateUser()
        {
            UserEntity user = new UserEntity();

            user.Login = _repository.GetRandomLogin();

            IdentityInfo identityName = _repository.GetRandomName();

            user.Name    = identityName.Identity;
            user.Surname = _repository.GetRandomSurname(identityName.Gender);

            bool isPatronymicExist = _random.Next(100) != 0;

            if (isPatronymicExist)
            {
                user.Patronymic = _repository.GetRandomPatronymic(identityName.Gender);
            }


            user.Password = _random.Next(1000, 10000).ToString();
            user.Email    = string.Format(@"{0}@{1}", user.Login, _repository.GetRandomMailDomain());

            int year  = _random.Next(2010, 2017);
            int month = _random.Next(1, 13);
            int day   = _random.Next(1, 29);

            if (year == 2016 && month > 2)
            {
                month = 2;
            }
            user.RegistrationDate = new DateTime(year, month, day);

            return(user);
        }
Example #11
0
        public IdentityInfo LoginCheck(LoginModel loginMdl)
        {
            IdentityInfo identity  = new IdentityInfo();
            LoginStatus  status    = new LoginStatus();
            var          loginUser = registerRep.Entities.FirstOrDefault(e => e.UserId == loginMdl.UserId);

            if (loginUser != null)
            {
                if (loginUser.Password == loginMdl.Password)
                {
                    status.StatusCode = 0;
                    identity          = LoginHandler.CollectUserInfoWhenLogined(identity, loginMdl.UserId);
                }
                else
                {
                    status.StatusCode = 2;
                }
            }
            else
            {
                status.StatusCode = 1;
            }
            identity.LoginStatus = status;
            return(identity);
        }
Example #12
0
        protected async void Page_Load(object sender, EventArgs e)
        {
            // Get identity information from the Todo List Web API.
            var relatedApplicationIdentities = new List <IdentityInfo>();

            try
            {
                var todoListWebApiClient = await GetTodoListClient(this.User);

                var todoListWebApiIdentityInfoRequest  = new HttpRequestMessage(HttpMethod.Get, SiteConfiguration.TodoListWebApiRootUrl + "api/identity");
                var todoListWebApiIdentityInfoResponse = await todoListWebApiClient.SendAsync(todoListWebApiIdentityInfoRequest);

                todoListWebApiIdentityInfoResponse.EnsureSuccessStatusCode();
                var todoListWebApiIdentityInfoResponseString = await todoListWebApiIdentityInfoResponse.Content.ReadAsStringAsync();

                var todoListWebApiIdentityInfo = JsonConvert.DeserializeObject <IdentityInfo>(todoListWebApiIdentityInfoResponseString);
                relatedApplicationIdentities.Add(todoListWebApiIdentityInfo);
            }
            catch (Exception exc)
            {
                relatedApplicationIdentities.Add(IdentityInfoFactory.FromException("Todo List Web API", exc));
            }

            // Gather identity information from the current application and aggregate it with the identity information from the Web API.
            var graphClient = default(AadGraphClient);

            if (StsConfiguration.StsType == StsType.AzureActiveDirectory)
            {
                graphClient = new AadGraphClient(StsConfiguration.Authority, StsConfiguration.AadTenant, SiteConfiguration.TodoListWebFormsClientId, SiteConfiguration.TodoListWebFormsClientSecret);
            }
            this.identity = await IdentityInfoFactory.FromPrincipal(this.User, "ID Token", SiteConfiguration.ApplicationName, relatedApplicationIdentities, graphClient);
        }
Example #13
0
        /// <summary>
        /// Impersonate an admin of this tenant and return the context object, which must be disposed.
        /// </summary>
        public IDisposable GetTenantAdminContext( )
        {
            if (TenantAdminIdentityInfo == null)
            {
                using (GetSystemAdminContext( ))
                {
                    Role        role        = Entity.Get <Role>("core:administratorRole");
                    UserAccount userAccount = role.RoleMembers.FirstOrDefault( );
                    if (userAccount == null)
                    {
                        throw new Exception($"Tenant '{TenantName}' has no administrator.");
                    }

                    TenantAdminIdentityInfo = new IdentityInfo(userAccount.Id, userAccount.Name);
                }
            }

            // Set context
            var tenantInfo = new EDC.ReadiNow.Metadata.Tenants.TenantInfo(TenantId);
            RequestContextData contextData = new RequestContextData(TenantAdminIdentityInfo, tenantInfo, CultureHelper.GetUiThreadCulture(CultureType.Neutral));

            RequestContext.SetContext(contextData);

            // Return delegate to revoke context
            return(ContextHelper.Create(RequestContext.FreeContext));
        }
Example #14
0
        public override IdentityInfo GetIdentityInfo()
        {
            var identityInfo = new IdentityInfo();

            identityInfo.Features = IdentityFeatures.None;
            return(identityInfo);
        }
Example #15
0
        /// <summary>
        /// Is used to parse indentity info from user claims
        /// </summary>
        /// <param name="identityClaims">Identity Claims</param>
        /// <returns>Identity Info</returns>
        /// <exception cref="System.ArgumentException">Thrown when identity claims are null or empty</exception>
        public static Task <IdentityInfo> ParseIdentityInfoFromIdentityClaimsAsync(IDictionary <string, string> identityClaims)
        {
            if (identityClaims == null || identityClaims.Count == 0)
            {
                throw new ArgumentException(nameof(identityClaims));
            }

            string grantedRolesValue;

            if (!identityClaims.TryGetValue(GrantedRolesClaimKey, out grantedRolesValue))
            {
                grantedRolesValue = null;
            }
            string grantedPermissionsValue;

            if (!identityClaims.TryGetValue(GrantedPermissionsClaimKey, out grantedPermissionsValue))
            {
                grantedPermissionsValue = null;
            }
            IdentityInfo result = new IdentityInfo(
                Int32.Parse(identityClaims[UserIdClaimKey]),
                identityClaims[UsernameClaimKey],
                String.IsNullOrEmpty(grantedRolesValue) ? new string[0] : grantedRolesValue.Split(','),
                String.IsNullOrEmpty(grantedPermissionsValue) ? new string[0] : grantedPermissionsValue.Split(','));

            return(Task.FromResult(result));
        }
Example #16
0
        private async Task <PrivateKeyModel> DownloadPrivateKey(IdentityInfo token)
        {
            PrivateKeyModel grabResponse = await ServiceLocator.Services.PrivateKeys.Get(this.recipientCard.Id, token)
                                           .ConfigureAwait(false);

            return(grabResponse);
        }
Example #17
0
        /// <summary>
        /// Get the request context this workflow will be running as, taking into account triggering user and owner.
        /// </summary>
        private RequestContextData GetEffectiveSecurityContext(WorkflowRun run, WorkflowMetadata metaData)
        {
            var effectiveUser  = GetEffectiveUser(run, metaData);
            var triggeringUser = GetTriggeringUser(run);

            // Error! The caller will deal with the missing info. We can't throw becasue RunState is needed for the error reporting
            if (effectiveUser == null)
            {
                return(null);
            }

            if (metaData.WfRunAsOwner && metaData.WfSecurityOwner == null)
            {
                return(null);
            }

            var identityInfo = new IdentityInfo(effectiveUser.Id, effectiveUser.Name);


            var context = RequestContext.GetContext();

            var effectiveSecurityContext = new RequestContextData(context);

            effectiveSecurityContext.Identity = identityInfo;

            // If we are running as someone other than the triggerer, set the secondary identity to the triggerer.
            // NOTE: This could potentially cause a problem in the case where a wf triggering another wf scenario.
            // It's possible that the user will see stale data. The risk should be quite low.
            if (triggeringUser != null && triggeringUser.Id != effectiveUser.Id)
            {
                effectiveSecurityContext.SecondaryIdentity = new IdentityInfo(triggeringUser.Id, triggeringUser.Name);
            }

            return(effectiveSecurityContext);
        }
Example #18
0
        public IdentityInfo ReadIdentityInfo(JsonReader reader)
        {
            IdentityInfo info = new IdentityInfo();

            reader.Read();
            while (reader.TokenType == JsonToken.PropertyName)
            {
                switch ((string)reader.Value)
                {
                case "toStr": info.ToStr = reader.ReadAsString(); break;

                case "id": info.Id = reader.ReadAsString(); break;

                case "isNew": info.IsNew = reader.ReadAsBoolean(); break;

                case "Type": info.Type = reader.ReadAsString(); break;

                case "ticks": info.Ticks = long.Parse(reader.ReadAsString()); break;

                case "modified": info.Modified = bool.Parse(reader.ReadAsString()); break;

                default: return(info);
                }

                reader.Read();
            }

            if (info.Type == null)
            {
                throw new JsonSerializationException($"Expected member 'Type' not found in {reader.Path}");
            }

            return(info);
        }
Example #19
0
        public void TestSetActualUserRequestContext()
        {
            try
            {
                // Ensure the initial context is clear
                RequestContext.FreeContext();

                // Create a context.
                var identity1 = new IdentityInfo(1234, "TestUser1");
                var tenant1   = new TenantInfo(1111);
                RequestContext.SetContext(identity1, tenant1, "en-US");

                var context1 = RequestContext.GetContext();

                // This should contain the actual user context
                var actualUserContext1 = ActualUserRequestContext.GetContext();

                Assert.IsTrue(actualUserContext1.IsValid);
                Assert.AreSame(context1.Identity, actualUserContext1.Identity);
                Assert.AreSame(context1.Tenant, actualUserContext1.Tenant);

                // Create a sys admin context.
                var identity2 = new IdentityInfo(0, "Admin");
                var tenant2   = new TenantInfo(1111);
                RequestContext.SetContext(identity2, tenant2, "en-US");

                // This should contain the initial actual user context
                var actualUserContext2 = ActualUserRequestContext.GetContext();
                Assert.IsTrue(actualUserContext2.IsValid);
                Assert.AreSame(context1.Identity, actualUserContext2.Identity);
                Assert.AreSame(context1.Tenant, actualUserContext2.Tenant);

                // Create a new user context.
                var identity3 = new IdentityInfo(456, "TestUser1");
                var tenant3   = new TenantInfo(1111);
                RequestContext.SetContext(identity3, tenant3, "en-US");

                var context3 = RequestContext.GetContext();

                // Set and reset an admin context
                using (new AdministratorContext())
                {
                }

                // This should still contain the new actual user context
                var actualUserContext3 = ActualUserRequestContext.GetContext();
                Assert.IsTrue(actualUserContext3.IsValid);
                Assert.AreSame(context3.Identity, actualUserContext3.Identity);
                Assert.AreSame(context3.Tenant, actualUserContext3.Tenant);

                RequestContext.FreeContext();

                var actualUserContext4 = ActualUserRequestContext.GetContext();
                Assert.IsFalse(actualUserContext4.IsValid);
            }
            finally
            {
                RequestContext.FreeContext();
            }
        }
Example #20
0
        /// <summary>
        ///     Sets the tenant.
        /// </summary>
        /// <param name="tenantId">The tenant identifier.</param>
        private void SetTenant(long tenantId)
        {
            var identity = new IdentityInfo(0, "TestUser");
            var tenant   = new TenantInfo(tenantId);

            RequestContext.SetContext(identity, tenant, "en-US");
        }
Example #21
0
        public Auth(AuthRequiredOption option)
        {
            _option = option;
            var resolver = DependencyResolver.Current;

            _identity = resolver.GetService <IdentityInfo>();
        }
Example #22
0
        public UserEntity GenerateUser()
        {
            UserEntity   entity       = new UserEntity();
            IdentityInfo identityName = _repository.GetRandomName();

            entity.Name       = identityName.Identity;
            entity.Surname    = _repository.GetRandomSurname(identityName.Gender);
            entity.Patronymic = _repository.GetRandomPatronymic(identityName.Gender);
            entity.Login      = _repository.GetRandomUniqLogin();

            string randomEmailDomain = _repository.GetRandomEmailDomain();

            entity.Email    = string.Format("{0}@{1}", entity.Login, randomEmailDomain);
            entity.Password = _random.Next(1000, 10000).ToString();

            int year  = _random.Next(2010, 2017);
            int month = _random.Next(1, 13);
            int day   = _random.Next(1, 29);

            if (year == 2016 && month > 8)
            {
                month = 8;
            }
            entity.RegistrationDate = new DateTime(year, month, day);

            return(entity);
        }
        /// <summary>
        /// 建立会话
        /// </summary>
        /// <param name="identityInfo"></param>
        /// <param name="sessionContex"></param>
        private static void EstablishSession(IdentityInfo identityInfo, HttpContext sessionContex)
        {
            sessionContex.Session["UserId"] = identityInfo.UserKey;     // 兼容CQS

            sessionContex.Session["UID"] = identityInfo.UserKey;
            sessionContex.Session["UserName"] = identityInfo.UserName;
            sessionContex.Session["Cookie"] = true;

            PublishAuthCookie(sessionContex, identityInfo);
        }
Example #24
0
        public async Task <IActionResult> Identity()
        {
            var relatedApplicationIdentities = new List <IdentityInfo>();

            try
            {
                // Request identity information as seen by the back-end Web API.
                var client = this.httpClientFactory.CreateClient(Startup.SampleApiHttpClientName);
                // Fetch the access token from the current user's claims to avoid the complexity of an external token cache (see Startup.cs).
                var accessTokenClaim = this.User.Claims.SingleOrDefault(c => c.Type == Startup.ClaimTypeAccessToken);
                if (accessTokenClaim != null)
                {
                    // Call the back-end Web API using the bearer access token.
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessTokenClaim.Value);
                    var response = await client.GetAsync("api/identity");

                    response.EnsureSuccessStatusCode();

                    // Deserialize the response into an IdentityInfo instance.
                    var apiIdentityInfoValue = await response.Content.ReadAsStringAsync();

                    var apiIdentityInfo = JsonConvert.DeserializeObject <IdentityInfo>(apiIdentityInfoValue);
                    relatedApplicationIdentities.Add(apiIdentityInfo);
                }
            }
            catch (Exception exc)
            {
                relatedApplicationIdentities.Add(new IdentityInfo
                {
                    Source          = "Exception",
                    Application     = "Sample API",
                    IsAuthenticated = false,
                    Claims          = new[] { new ClaimInfo {
                                                  Type = "ExceptionMessage", Value = exc.Message
                                              }, new ClaimInfo {
                                                  Type = "ExceptionDetail", Value = exc.ToString()
                                              } }
                });
            }
            // Return identity information as seen from this application, including related applications.
            var identityInfo = new IdentityInfo
            {
                Source             = "ID Token",
                Application        = "Sample Client",
                IsAuthenticated    = this.User.Identity.IsAuthenticated,
                Name               = this.User.Identity.Name,
                AuthenticationType = this.User.Identity.AuthenticationType,
                Claims             = this.User.Claims.Select(c => new ClaimInfo {
                    Type = c.Type, Value = c.Value
                }).ToList(),
                RelatedApplicationIdentities = relatedApplicationIdentities
            };

            return(View(identityInfo));
        }
Example #25
0
        public static IdentityInfo GetIdentityInfo(this HttpRequestMessage request)
        {
            IdentityInfo identityInfo = null;
            object       obj;

            if (request.Properties.TryGetValue(IdentityInfo_Context_Key, out obj))
            {
                return((IdentityInfo)obj);
            }
            return(identityInfo);
        }
Example #26
0
        public static IdentityInfo GetIdentityInfo(this HttpRequestBase request)
        {
            IDictionary  items        = request.RequestContext.HttpContext.Items;
            IdentityInfo identityInfo = null;

            if (items.Contains(IdentityInfo_Context_Key))
            {
                return((IdentityInfo)items[IdentityInfo_Context_Key]);
            }
            return(identityInfo);
        }
Example #27
0
 public static void SetIdentityInfo(this HttpRequestMessage request, IdentityInfo identityInfo)
 {
     if (!request.Properties.ContainsKey(IdentityInfo_Context_Key))
     {
         request.Properties.Add(IdentityInfo_Context_Key, identityInfo);
     }
     else
     {
         request.Properties[IdentityInfo_Context_Key] = identityInfo;
     }
 }
Example #28
0
        public void GatewayDetermination(HttpContext context, IdentityInfo identityInfo)
        {
            if (DbGateway == null)
            {
                return;
            }

            var conn = DbGateway.Process(context, identityInfo);

            identityInfo.GatewayBag.Add("ReadConnectionString", conn.ReadConnectionString);
            identityInfo.GatewayBag.Add("WriteConnectionString", conn.WriteConnectionString);
        }
Example #29
0
        /// <summary>
        ///     Set the system administrator context data.
        /// </summary>
        internal static void SetSystemAdministratorContext( )
        {
            /////
            // EntityId should be always set to zero for administrator context.
            /////
            var tenantInfo = new TenantInfo(0);

            var    identityInfo = new IdentityInfo(0, SpecialStrings.SystemAdministratorUser);
            string culture      = CultureHelper.GetUiThreadCulture(CultureType.Neutral);

            // Set the request context data
            RequestContext.SetContext(identityInfo, tenantInfo, culture);
        }
Example #30
0
        public static void SetIdentityInfo(this HttpRequestBase request, IdentityInfo identityInfo)
        {
            IDictionary items = request.RequestContext.HttpContext.Items;

            if (!items.Contains(IdentityInfo_Context_Key))
            {
                items.Add(IdentityInfo_Context_Key, identityInfo);
            }
            else
            {
                items[IdentityInfo_Context_Key] = identityInfo;
            }
        }
Example #31
0
        private T BuildItem <T>(IdentityInfo identityInfo, SizeInfo sizeInfo, CreatorInfo creatorInfo, CatalogInfo catalogInfo, TargetInfo targetInfo, UserInfo userInfo, ThumbnailInfo thumbnailInfo)
            where T : class, IMetadata
        {
            var builder = new MediaItemBuilder <T>(securityContext, mediaFactory)
                          .Identity(identityInfo.Name, identityInfo.Summary, identityInfo.FromDate, identityInfo.ToDate, identityInfo.Number, identityInfo.Location)
                          .Size(sizeInfo.Duration, sizeInfo.Height, sizeInfo.Width)
                          .Creator(creatorInfo.Location, creatorInfo.Name)
                          .Catalog(catalogInfo.Location, catalogInfo.Name)
                          .Target(targetInfo.Location, targetInfo.Type)
                          .User(userInfo.Location, userInfo.Name)
                          .Thumbnail(thumbnailInfo.Location, thumbnailInfo.Data);

            return(builder.ToMediaItem());
        }
        public IdentityInfo ReadIdentityInfo(JsonReader reader)
        {
            IdentityInfo info = new IdentityInfo();
            reader.Read();
            while (reader.TokenType == JsonToken.PropertyName)
            {
                switch ((string)reader.Value)
                {
                    case "toStr": info.ToStr = reader.ReadAsString(); break;
                    case "id": info.Id = reader.ReadAsString(); break;
                    case "isNew": info.IsNew = reader.ReadAsBoolean(); break;
                    case "Type": info.Type = reader.ReadAsString(); break;
                    case "ticks": info.Ticks = long.Parse(reader.ReadAsString()); break;
                    case "modified": info.Modified = bool.Parse(reader.ReadAsString()); break;
                    default: return info;
                }

                reader.Read();
            }

            if (info.Type == null)
                throw new JsonSerializationException($"Expected member 'Type' not found in {reader.Path}");

            return info;
        }
        private static void PublishAuthCookie(HttpContext context, IdentityInfo identityInfo)
        {
            #region 如果支持持久性身份验证Cookie

            string userData = null;
            using (MemoryStream buffer = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(buffer, identityInfo);
                buffer.Position = 0;
                userData = System.Convert.ToBase64String(buffer.ToArray());
            }

            // 使用本地日期和时间
            FormsAuthenticationTicket tk = new FormsAuthenticationTicket(1, identityInfo.UserName,
                DateTime.Now, DateTime.Now.AddMinutes((double)Settings.GetAuthCookieTimeOut()),
                true, userData, Settings.GetAuthCookiePath());
            string encryptedTicket = FormsAuthentication.Encrypt(tk);   //加密身份验票
            System.Web.HttpCookie authCookie = new HttpCookie(Settings.GetAuthCookieName(), encryptedTicket);
            authCookie.Path = Settings.GetAuthCookiePath();
            authCookie.Domain = Settings.GetAuthCookieDomain();
            authCookie.Expires = tk.Expiration;
            authCookie.Secure = Settings.GetAuthCookieRequireSSL();
            context.Response.Cookies.Add(authCookie);

            #endregion
        }