public async Task <Position> GetPosition() { var settings = await _documentRepository .SingleOrDefault(s => s.Tenant == TenantId.ToString(), TenantId); if (settings != null) { return(settings.Position); } settings = SubscriptionSettings.For(TenantId.ToString()); await _documentRepository.Insert(settings); return(settings.Position); }
/// <summary> /// Converts an <see cref="UserAssignedIdentity"/> object into a <see cref="JsonElement"/>. /// </summary> /// <param name="writer"> Utf8JsonWriter object to which the output is going to be written. </param> void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } writer.WritePropertyName("principalId"); if (!Optional.IsDefined(PrincipalId)) { writer.WriteStringValue("null"); } else { writer.WriteStringValue(PrincipalId.ToString()); } writer.WritePropertyName("tenantId"); if (!Optional.IsDefined(TenantId)) { writer.WriteStringValue("null"); } else { writer.WriteStringValue(TenantId.ToString()); } writer.Flush(); }
public string AssembleAuthorizationUrl(bool include_offline_access = true, bool always_show_consent = true) { string ToReturn = login_base_url + "/" + TenantId.ToString() + "/" + authorize_endpoint; ToReturn = ToReturn + "?client_id=" + ClientId.ToString(); ToReturn = ToReturn + "&response_type=code"; //Standard ToReturn = ToReturn + "&redirect_uri=" + RedirectUrl; ToReturn = ToReturn + "&response_mode=query"; //Standard //Scopes List <string> ScopesToUse = new List <string>(); if (Scope != null) { ScopesToUse.AddRange(Scope); } if (ScopesToUse.Contains("offline_access") == false) { ScopesToUse.Add("offline_access"); } ToReturn = ToReturn + "&scope=" + UrlEncodeScopes(ScopesToUse.ToArray()); if (always_show_consent) { ToReturn = ToReturn + "&prompt=consent"; } return(ToReturn); }
/// <inheritdoc/> public ScoreOf <Context> From(TenantId tenantId, Project project, string commit, bool isPullRequest) { var basePath = Environment.GetEnvironmentVariable("BASE_PATH") ?? string.Empty; var projectPath = Path.Combine(basePath, tenantId.ToString(), project.Id.ToString()); var buildNumber = GetBuildNumberForCurrentBuild(projectPath); var sourceControl = new SourceControlContext(project.Repository, commit, isPullRequest); var context = new Context(tenantId, project, sourceControl, projectPath, buildNumber); var score = new ScoreOf <Context>(context); score.AddStep <GetLatest>(); score.AddStep <GetVersion>(); score.AddStep <BuildJobs>(); /* * if there are package sources configured, add steps per package source - the performer decides if it is going to be performed * * if there are container registries configured, add steps per registry - the performer decides if it is going to be performed * * if there are notification channels - add each * * if there are project cascades - add step for each */ return(score); }
private void DoBackupStorage(IDataWriteOperator writer, List <IGrouping <string, BackupFileInfo> > fileGroups) { Logger.Debug("begin backup storage"); foreach (var group in fileGroups) { var filesProcessed = 0; var filesCount = group.Count(); var storage = StorageFactory.GetStorage(ConfigPath, TenantId.ToString(), group.Key); foreach (var file in group) { ActionInvoker.Try(state => { var f = (BackupFileInfo)state; using (var fileStream = storage.GetReadStream(f.Domain, f.Path)) { var tmp = Path.GetTempFileName(); try { using (var tmpFile = File.OpenWrite(tmp)) { fileStream.CopyTo(tmpFile); } writer.WriteEntry(KeyHelper.GetFileZipKey(file), tmp); } finally { if (File.Exists(tmp)) { File.Delete(tmp); } } } }, file, 5, error => Logger.Warn("can't backup file ({0}:{1}): {2}", file.Module, file.Path, error)); SetCurrentStepProgress((int)(++filesProcessed * 100 / (double)filesCount)); } } var restoreInfoXml = new XElement( "storage_restore", fileGroups .SelectMany(group => group.Select(file => (object)file.ToXElement())) .ToArray()); var tmpPath = Path.GetTempFileName(); using (var tmpFile = File.OpenWrite(tmpPath)) { restoreInfoXml.WriteTo(tmpFile); } writer.WriteEntry(KeyHelper.GetStorageRestoreInfoZipKey(), tmpPath); File.Delete(tmpPath); Logger.Debug("end backup storage"); }
private IFileDao <T> GetFileDao <T>() { // hack: create storage using webConfigPath and put it into DataStoreCache // FileDao will use this storage and will not try to create the new one from service config StorageFactory.GetStorage(WebConfigPath, TenantId.ToString(), "files"); return(DaoFactory.GetFileDao <T>()); }
/// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { StringBuilder toolTipInfo = new StringBuilder(); toolTipInfo.AppendLine(string.Format("Resource Id: {0}", Id.ToString())); toolTipInfo.AppendLine(string.Format("Name: {0}", Name)); if (!string.IsNullOrEmpty(TypeName)) { toolTipInfo.AppendLine(string.Format("Type Name: {0}", TypeName)); } else { toolTipInfo.AppendLine(string.Format("Type Id: {0}", TypeId.ToString())); } if (!string.IsNullOrEmpty(SolutionName)) { toolTipInfo.AppendLine(string.Format("Solution Name: {0}", SolutionName)); } else { toolTipInfo.AppendLine(string.Format("Solution Id: {0}", SolutionId.ToString())); } if (!string.IsNullOrEmpty(TenantName)) { toolTipInfo.AppendLine(string.Format("Tenant Name: {0}", TenantName)); } else { toolTipInfo.AppendLine(string.Format("Tenant Id: {0}", TenantId.ToString())); } return(toolTipInfo.ToString()); }
/// <summary> /// 获取要加密签名的串 /// </summary> /// <param name="separator"></param> /// <returns></returns> protected internal virtual StringBuilder GetSignContent(char separator) { var strTicketParas = new StringBuilder(); if (AppClient > 0) { AddSignDataValue("ac", AppClient.ToString(), separator, strTicketParas); } AddSignDataValue("as", AppSource, separator, strTicketParas); AddSignDataValue("av", AppVersion, separator, strTicketParas); AddSignDataValue("did", DeviceId, separator, strTicketParas); AddSignDataValue("ip", IpAddress, separator, strTicketParas); AddSignDataValue("pc", ProCode, separator, strTicketParas); if (TenantId > 0) { AddSignDataValue("tid", TenantId.ToString(), separator, strTicketParas); } AddSignDataValue("ts", TimeSpan.ToString(), separator, strTicketParas); AddSignDataValue("tn", Token, separator, strTicketParas); AddSignDataValue("wb", WebBrowser, separator, strTicketParas); return(strTicketParas); }
/// <summary> /// 获取要加密签名的串 /// </summary> /// <param name="separator"></param> /// <returns></returns> protected override StringBuilder GetSignContent(char separator) { var strTicketParas = new StringBuilder(); if (AppClient > 0) { AddTicketProperty("app_client", AppClient.ToString(), separator, strTicketParas); } AddTicketProperty("app_source", AppSource, separator, strTicketParas); AddTicketProperty("app_version", AppVersion, separator, strTicketParas); AddTicketProperty("device_id", DeviceId, separator, strTicketParas); AddTicketProperty("ip_address", IpAddress, separator, strTicketParas); AddTicketProperty("pro_code", ProCode, separator, strTicketParas); if (TenantId > 0) { AddTicketProperty("tenant_id", TenantId.ToString(), separator, strTicketParas); } AddTicketProperty("timespan", TimeSpan.ToString(), separator, strTicketParas); AddTicketProperty("token", Token, separator, strTicketParas); AddTicketProperty("web_browser", WebBrowser, separator, strTicketParas); return(strTicketParas); }
public UserEntity(TenantId tenant, UserId id, RoleId role) { PartitionKey = tenant.ToString(); RowKey = id.ToString(); RoleId = role?.ToString(); }
public EitherAsync <Error, List <PlayerDto> > Execute(TenantId tenant) { return(PerformStorageOperation(_options.PlayersTable, tableRef => { var filter = TableQuery.GenerateFilterCondition( nameof(PlayerEntity.PartitionKey), QueryComparisons.Equal, tenant.ToString()); var query = new TableQuery <PlayerEntity> { FilterString = filter }; // We are taking first segment for now as we don't have other cases yet // once it is not working feel free to refactor heavily var continuationToken = new TableContinuationToken(); var getResult = Prelude .TryAsync(tableRef.ExecuteQuerySegmentedAsync(query, continuationToken)) .ToEither(MapStorageError); return getResult.Match( tableResult => tableResult.Results .Select(p => _mapper.Map <PlayerEntity, PlayerDto>(p)) .ToList(), MapError ).ToAsync(); }, "Get All Player")); }
private Dictionary <string, DataServiceContextBase> CreateDataServiceContexts() { Contract.Requires(null != ApiBaseUri); Contract.Requires(null != Credential); Contract.Ensures(Contract.Result <Dictionary <string, DataServiceContextBase> >().ContainsKey(nameof(Api::Net.Appclusive.Api.Core.Core))); var dataServiceContexts = new Dictionary <string, DataServiceContextBase>(); var credential = Credential.GetNetworkCredential(); var dataServiceContextTypes = typeof(DataServiceContextBase).Assembly.DefinedTypes.Where( t => t.BaseType == typeof(DataServiceContextBase)); foreach (var dataServiceContextType in dataServiceContextTypes) { var serviceRootUri = new Uri(UriHelper.ConcatUri(ApiBaseUri.AbsoluteUri, dataServiceContextType.Name)); var dataServiceContext = (DataServiceContextBase)Activator.CreateInstance(dataServiceContextType, serviceRootUri); dataServiceContext.Credentials = credential; if (default(Guid) != TenantId) { dataServiceContext.TenantId = TenantId.ToString(); } dataServiceContext.Format.UseJson(); dataServiceContexts.Add(dataServiceContextType.Name, dataServiceContext); } return(dataServiceContexts); }
public override string ToString() { if (DefaultDomain == null) { return(TenantId.ToString()); } else { return(DefaultDomain.Name + " (" + TenantId + ")"); } }
public override ActionResult Index(WeiChat_Pay model) { if ((Request.Files.Count > 0) && (Request.Files["PayCertFile"].ContentLength > 0) && (Path.GetExtension(Request.Files["PayCertFile"].FileName).ToLower() != ".p12")) { ModelState.AddModelError("PayCertFile", "上传的支付证书文件有误!"); } if (string.IsNullOrWhiteSpace(model.CertPassword)) { ModelState.AddModelError("CertPassword", "证书密钥是必须的!"); } if (string.IsNullOrWhiteSpace(model.MchId)) { ModelState.AddModelError("MchId", "商户Id是必须的!"); } if (string.IsNullOrWhiteSpace(model.Notify)) { ModelState.AddModelError("Notify", "回调地址是必须的!"); } if (string.IsNullOrWhiteSpace(model.TenPayKey)) { ModelState.AddModelError("TenPayKey", "支付密钥是必须的!"); } if (ModelState.IsValid) { if ((Request.Files.Count > 0) && (Request.Files["PayCertFile"].ContentLength > 0) && (Path.GetExtension(Request.Files["PayCertFile"].FileName).ToLower() == ".p12")) { var file = Request.Files["PayCertFile"]; #region 保存证书,用于红包发放等接口 var path = Path.Combine(Server.MapPath("~/App_Data"), "certs", TenantId.ToString()); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = Path.Combine(path, "pay.p12"); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } file.SaveAs(path); #endregion model.PayCertPath = string.Format("/App_Data/certs/{0}/pay.p12", TenantId); } model.Notify = GetNotifyUrl(); SetModelWithSaveChanges(model, model.Id); } return(View(model)); }
public Dictionary <string, string> ToDictionary() { return(new Dictionary <string, string>() { { ClaimTypes.Sid, UserId.ToString() }, { ClaimTypes.Name, UserName }, { ClaimTypes.GroupSid, TenantId.ToString() }, { ClaimTypes.GivenName, TenantName }, { ClaimTypes.NameIdentifier, UserType.ToString() }, { ClaimTypes.Locality, IdentityType.ToString() }, { ClaimTypes.System, FuncModule.ToString() } }); }
public ClaimsIdentity ToClaimsIdentity() { return(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Sid, UserId.ToString()), new Claim(ClaimTypes.Name, UserName), new Claim(ClaimTypes.GroupSid, TenantId.ToString()), new Claim(ClaimTypes.GivenName, TenantName), new Claim(ClaimTypes.NameIdentifier, UserType.ToString()), new Claim(ClaimTypes.Locality, IdentityType.ToString()), new Claim(ClaimTypes.System, FuncModule.ToString()), })); }
public async Task GetAccessTokenAsync(string authorization_code) { //Assemble the URL to request from using the code string ReqUrl = login_base_url + "/" + TenantId.ToString() + "/" + token_endpoint; List <KeyValuePair <string, string> > KVPs = new List <KeyValuePair <string, string> >(); KVPs.Add(new KeyValuePair <string, string>("client_id", ClientId.ToString())); //Scopes // List<string> ScopesToUse = new List<string>(); // if (Scope != null) // { // ScopesToUse.AddRange(Scope); // } // if (ScopesToUse.Contains("offline_access") == false) // { // ScopesToUse.Add("offline_access"); // } // KVPs.Add(new KeyValuePair<string, string>("scope",UrlEncodeScopes(ScopesToUse.ToArray()))); KVPs.Add(new KeyValuePair <string, string>("code", authorization_code)); KVPs.Add(new KeyValuePair <string, string>("redirect_uri", RedirectUrl)); KVPs.Add(new KeyValuePair <string, string>("grant_type", "authorization_code")); string asstr = await new FormUrlEncodedContent(KVPs).ReadAsStringAsync(); //Make the request HttpClient hc = new HttpClient(); HttpRequestMessage reqmsg = new HttpRequestMessage(); reqmsg.RequestUri = new Uri(ReqUrl); reqmsg.Method = HttpMethod.Post; reqmsg.Content = new StringContent(asstr, Encoding.UTF8, "application/x-www-form-urlencoded"); HttpResponseMessage hrm = await hc.SendAsync(reqmsg); string content = await hrm.Content.ReadAsStringAsync(); if (hrm.StatusCode != HttpStatusCode.OK) { throw new Exception("Error code \"" + hrm.StatusCode.ToString() + "\" returned. Content: " + content); } //Parse into token payload MicrosoftGraphTokenPayload tokenpayload = new MicrosoftGraphTokenPayload(content); //Store for later LastReceivedTokenPayload = tokenpayload; }
public ClaimsIdentity ToClaimsIdentity(string authenticationType = null) { const string ObjectIdClaimType = "http://schemas.microsoft.com/identity/claims/objectidentifier"; const string TenantIdClaimType = "http://schemas.microsoft.com/identity/claims/tenantid"; var claims = new List <Claim>() { new Claim(ObjectIdClaimType, Id.ToString()), new Claim(TenantIdClaimType, TenantId.ToString()), new Claim(ClaimTypes.Name, Name) }; return(new ClaimsIdentity(claims, authenticationType)); }
private void BuildDefaultAttributeValue(object entity) { var sourceProperties = GetScaffoldableProperties(entity).ToArray(); for (var i = 0; i < sourceProperties.Count(); i++) { if (sourceProperties.ElementAt(i).GetCustomAttributes(true).Any(attr => attr.GetType().Name == typeof(MustHaveTenantAttribute).Name)) { if (TenantId.HasValue) { sourceProperties.ElementAt(i).SetValue(entity, TenantId.ToString()); } } } }
public Task <Result <User> > Get(TenantId tenant, UserId id) { return(PerformStorageOperation <User>(async tableRef => { var getOperation = TableOperation.Retrieve <UserEntity>(tenant.ToString(), id.ToString()); var result = await tableRef.ExecuteAsync(getOperation); if (result.Result is UserEntity userEntity) { return new User(new UserId(userEntity.RowKey), new TenantId(userEntity.PartitionKey)); } return Error.NotFound(); }, "Get User")); }
public EitherAsync <Error, Player> Get(TenantId tenant, PlayerId id) { return(PerformStorageOperation(_options.PlayersTable, tableRef => { var getOperation = TableOperation.Retrieve <PlayerEntity>(tenant.ToString(), id.ToString()); EitherAsync <Error, TableResult> getResult = tableRef.ExecuteAsync(getOperation); return getResult.Match <Either <Error, Player> >( tableResult => tableResult.Result switch { PlayerEntity playerEntity => _playerFactory.Create( _mapper.Map <PlayerEntity, PlayerFactoryDto>(playerEntity)), _ => Error.NotFound() },
public IHttpActionResult UploadPhotos(Guid typeId) { var ids = HttpContext.Current.Request.Form["mediaIds"].Trim(',').Split(','); foreach (var mediaId in ids) { var fileName = DateTime.Now.ToString("yyyy-MM-dd"); //文件保存的名字 var fileSaveName = Guid.NewGuid().ToString("N") + ".png"; //租户Id var dirName = TenantId.ToString(); var path = Path.Combine(HttpContext.Current.Server.MapPath("~/MediaFiles"), dirName); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = Path.Combine(path, fileSaveName); //从临时素材获取 using (var stream = File.Create(path)) { //TODO:切换SDK MediaApi.Get(WeChatConfigManager.Current.GetAccessToken(), mediaId, stream); } //上传到永久素材 var result = MediaApi.UploadForeverMedia(AccessToken, path); if (!string.IsNullOrWhiteSpace(result.errmsg)) { return(BadRequest(result.errmsg)); } //写入数据 var pic = new Site_Image { IsFrontCover = !db.Site_Images.Any(p => p.ResourcesTypeId == typeId), MediaId = result.media_id, Name = fileName, //站内地址 SiteUrl = string.Format("/MediaFiles/{0}/{1}", dirName, fileSaveName), Url = result.url, ResourcesTypeId = typeId }; SetModel(pic, default(Guid)); db.Site_Images.Add(pic); db.SaveChanges(); } return(Ok()); }
/// <summary> /// Gets the IdentityUser. /// </summary> /// <returns>Dictionary of User.</returns> public Dictionary <string, object> ToDictionary() { return(new Dictionary <string, object> { { nameof(UserId), UserId.ToString() }, { nameof(TenantId), TenantId.ToString() }, { nameof(TenantName), TenantName }, { nameof(TenantDisplayName), TenantDisplayName }, { nameof(Email), Email }, { nameof(GivenName), GivenName }, { nameof(FirstName), FirstName }, { nameof(LastName), LastName }, { nameof(Products), Products?.ToJson() }, { nameof(Roles), Roles?.ToJson() }, { nameof(Permissions), Permissions?.ToJson() } }); }
public ActionResult Upload(HttpPostedFileBase upImg) { //定义允许上传的文件扩展名 const string fileTypes = "gif,jpg,png,bmp"; string fileExt = Path.GetExtension(upImg.FileName); if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1) { return(Json(new { error = "上传文件不支持文件格式!" }, "text/html")); } //设置最大文件大小(2M) const int maxSize = 2050000; if (upImg.ContentLength > maxSize) { return(Json(new { error = "上传文件中的图片大小超出2M!!" }, "text/html")); } //存储文件名 string fileName = DateTime.Now.ToString("yyyyMMddhhmmssff") + CreateRandomCode(8) + "_" + System.IO.Path.GetFileName(upImg.FileName); //租户id var dirName = TenantId.ToString(); string virtualPath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), fileName); string imgUrl = "", error = "", msg = ""; imgUrl = Path.Combine(HttpContext.Server.MapPath("..\\Uploads"), fileName); try { upImg.SaveAs(virtualPath); msg = "上传成功!"; //var pic = new Site_Image //{ // Name = fileName, // SiteUrl = imgUrl, //}; //db.Site_Images.Add(pic); //db.SaveChanges(); } catch (Exception ex) { error = "上传失败!"; throw new Exception("上传失败!", ex); } return(Json(new { msg = msg, imgUrl = imgUrl, error = error }, "text/html")); //return Json(new { msg = "ok", imgUrl = "url", error = "" }, "text/html"); }
public void ValueEquality() { WebhookId webhookId = RandomWebhookId(); TenantId tenantId = RandomTenantId(); IEnumerable <EventTypeId> eventIds = ListOfDistinctEventIds(); var webhook = new Webhook(webhookId, tenantId, eventIds, "postbackUrl", "secret"); sut.Add(webhook); WebhookId webhookIdCopy = new Guid(webhookId.ToString()); TenantId tenantIdCopy = new Guid(tenantId.ToString()); sut.Get(webhookIdCopy, tenantIdCopy).Match ( none: () => Assert.Fail(), some: (result) => Assert.AreEqual(result, webhook) ); }
private void DoTransferStorage(ColumnMapper columnMapper) { Logger.Debug("begin transfer storage"); var fileGroups = GetFilesToProcess(TenantId).GroupBy(file => file.Module).ToList(); var groupsProcessed = 0; foreach (var group in fileGroups) { var baseStorage = StorageFactory.GetStorage(ConfigPath, TenantId.ToString(), group.Key); var destStorage = StorageFactory.GetStorage(ToConfigPath, columnMapper.GetTenantMapping().ToString(), group.Key); var utility = new CrossModuleTransferUtility(Options, baseStorage, destStorage); foreach (var file in group) { var adjustedPath = file.Path; var module = ModuleProvider.GetByStorageModule(file.Module, file.Domain); if (module == null || module.TryAdjustFilePath(false, columnMapper, ref adjustedPath)) { try { utility.CopyFile(file.Domain, file.Path, file.Domain, adjustedPath); } catch (Exception error) { Logger.WarnFormat("Can't copy file ({0}:{1}): {2}", file.Module, file.Path, error); } } else { Logger.WarnFormat("Can't adjust file path \"{0}\".", file.Path); } } SetCurrentStepProgress((int)(++groupsProcessed * 100 / (double)fileGroups.Count)); } if (fileGroups.Count == 0) { SetStepCompleted(); } Logger.Debug("end transfer storage"); }
private void DoDeleteStorage() { Logger.Debug("begin delete storage"); List <string> storageModules = StorageFactory.GetModuleList(ConfigPath).Where(IsStorageModuleAllowed).ToList(); int modulesProcessed = 0; foreach (string module in storageModules) { IDataStore storage = StorageFactory.GetStorage(ConfigPath, TenantId.ToString(), module); List <string> domains = StorageFactory.GetDomainList(ConfigPath, module).ToList(); foreach (var domain in domains) { ActionInvoker.Try(state => storage.DeleteFiles((string)state, "\\", "*.*", true), domain, 5, onFailure: error => Logger.WarnFormat("Can't delete files for domain {0}: \r\n{1}", domain, error)); } storage.DeleteFiles("\\", "*.*", true); SetCurrentStepProgress((int)((++modulesProcessed * 100) / (double)storageModules.Count)); } Logger.Debug("end delete storage"); }
public override string ToString() { var token = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, notBefore: DateTime.UtcNow, signingCredentials: new SigningCredentials( key: new SymmetricSecurityKey( key: Encoding.ASCII.GetBytes(_jwtOptions.Secret) ), algorithm: SecurityAlgorithms.HmacSha256 ), claims: new[] { new Claim("TenantId", TenantId.ToString()), new Claim("UserId", UserId.ToString()) } ); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public void RunJob()//DistributedTask distributedTask, CancellationToken cancellationToken) { using var scope = ServiceProvider.CreateScope(); var scopeClass = scope.ServiceProvider.GetService <QuotaSyncScope>(); var(tenantManager, storageFactoryConfig, storageFactory) = scopeClass; tenantManager.SetCurrentTenant(TenantId); var storageModules = storageFactoryConfig.GetModuleList(string.Empty).ToList(); foreach (var module in storageModules) { var storage = storageFactory.GetStorage(TenantId.ToString(), module); storage.ResetQuota(""); var domains = storageFactoryConfig.GetDomainList(string.Empty, module).ToList(); foreach (var domain in domains) { storage.ResetQuota(domain); } } }
/// <summary> /// Retrieves the principal's context. /// </summary> public virtual IPrincipal GetUserContext() { var claims = new List <Claim>(); if (!string.IsNullOrEmpty(UserId)) { claims.Add(new Claim("sub", UserId.ToString())); } if (!string.IsNullOrEmpty(ClientId)) { claims.Add(new Claim("client_id", ClientId.ToString())); } if (TenantId != default(Guid)) { claims.Add(new Claim(BasicClaimTypes.TenantId, TenantId.ToString())); } if (!string.IsNullOrEmpty(User)) { claims.Add(new Claim("name", User)); } var delegatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "WorkerAuth")); return(delegatedUser); }