/// <summary>
        /// 权限映射
        /// </summary>
        /// <param name="authority">权限领域模型</param>
        /// <param name="systemInfos">信息系统数据传输对象字典</param>
        /// <returns>权限数据传输对象</returns>
        public static AuthorityInfo ToDTO(this Authority authority, IDictionary <string, InfoSystemInfo> systemInfos)
        {
            AuthorityInfo authorityInfo = Transform <Authority, AuthorityInfo> .Map(authority);

            authorityInfo.InfoSystemInfo = systemInfos[authority.SystemNo];

            return(authorityInfo);
        }
        //Initializations

        #region 加载 —— void Load(AuthorityInfo authority)
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="authority">权限</param>
        public void Load(AuthorityInfo authority)
        {
            this.InfoSystemName = authority.InfoSystemInfo.Name;
            this.AuthorityId    = authority.Id;
            this.AuthorityName  = authority.Name;
            this.AuthorityPath  = authority.AuthorityPath;
            this.Description    = authority.Description;
        }
Esempio n. 3
0
 public override Empty ChangeCodeCheckController(AuthorityInfo input)
 {
     AssertSenderAddressWith(State.CodeCheckController.Value.OwnerAddress);
     Assert(CheckOrganizationExist(input),
            "Invalid authority input.");
     State.CodeCheckController.Value = input;
     return(new Empty());
 }
        /// <summary>
        /// 权限映射
        /// </summary>
        public static AuthorityInfo ToDTO(this Authority authority, IDictionary <string, InfoSystemInfo> infoSystemInfos)
        {
            AuthorityInfo authorityInfo = authority.Map <Authority, AuthorityInfo>();

            authorityInfo.InfoSystemInfo = infoSystemInfos?[authority.InfoSystemNo];

            return(authorityInfo);
        }
 public override Empty ChangeConfigurationController(AuthorityInfo input)
 {
     AssertPerformedByConfigurationController();
     Assert(input != null, "invalid input");
     Assert(CheckOrganizationExist(input), "Invalid authority input.");
     State.ConfigurationController.Value = input;
     return(new Empty());
 }
        /// <summary>
        /// 权限视图模型映射
        /// </summary>
        /// <param name="authorityInfo">权限数据传输对象</param>
        /// <returns>权限视图模型</returns>
        public static AuthorityView ToViewModel(this AuthorityInfo authorityInfo)
        {
            AuthorityView authorityView = Transform <AuthorityInfo, AuthorityView> .Map(authorityInfo);

            authorityView.SystemName = authorityInfo.InfoSystemInfo.Name;

            return(authorityView);
        }
        public async Task <AuthorityEndpoints> ResolveEndpointsAsync(
            AuthorityInfo authorityInfo,
            string userPrincipalName,
            RequestContext requestContext)
        {
            if (TryGetCacheValue(authorityInfo, userPrincipalName, out var endpoints))
            {
                requestContext.Logger.Info(LogMessages.ResolvingAuthorityEndpointsTrue);
                return(endpoints);
            }

            requestContext.Logger.Info(LogMessages.ResolvingAuthorityEndpointsFalse);

            var endpointManager = OpenIdConfigurationEndpointManagerFactory.Create(authorityInfo, _serviceBundle);

            string openIdConfigurationEndpoint = await endpointManager.ValidateAuthorityAndGetOpenIdDiscoveryEndpointAsync(
                authorityInfo,
                userPrincipalName,
                requestContext).ConfigureAwait(false);

            // Discover endpoints via openid-configuration
            var edr = await DiscoverEndpointsAsync(openIdConfigurationEndpoint, requestContext).ConfigureAwait(false);

            if (string.IsNullOrEmpty(edr.AuthorizationEndpoint))
            {
                throw new MsalClientException(
                          MsalError.TenantDiscoveryFailedError,
                          MsalErrorMessage.AuthorizeEndpointWasNotFoundInTheOpenIdConfiguration);
            }

            if (string.IsNullOrEmpty(edr.TokenEndpoint))
            {
                throw new MsalClientException(
                          MsalError.TenantDiscoveryFailedError,
                          MsalErrorMessage.TokenEndpointWasNotFoundInTheOpenIdConfiguration);
            }

            if (string.IsNullOrEmpty(edr.Issuer))
            {
                throw new MsalClientException(
                          MsalError.TenantDiscoveryFailedError,
                          MsalErrorMessage.IssuerWasNotFoundInTheOpenIdConfiguration);
            }

            var authority = Authority.CreateAuthority(authorityInfo);
            var tenantId  = authority.GetTenantId();

            string authorizationEndpoint = ReplaceTenantToken(edr.AuthorizationEndpoint, tenantId);
            string tokenEndpoint         = ReplaceTenantToken(edr.TokenEndpoint, tenantId);

            endpoints = new AuthorityEndpoints(
                authorizationEndpoint,
                tokenEndpoint,
                GetSelfSignedJwtAudience(edr.Issuer, tokenEndpoint, tenantId, authorityInfo.AuthorityType));

            Add(authorityInfo, userPrincipalName, endpoints);
            return(endpoints);
        }
Esempio n. 8
0
 Task <IReadOnlyList <IAccount> > IBroker.GetAccountsAsync(
     string clientID,
     string redirectUri,
     AuthorityInfo authorityInfo,
     ICacheSessionManager cacheSessionManager,
     IInstanceDiscoveryManager instanceDiscoveryManager)
 {
     throw new NotImplementedException();
 }
 public override Empty ChangeSideChainParliamentController(AuthorityInfo input)
 {
     AssertControllerForSideChainRental();
     Assert(input != null, "invalid input");
     Assert(input.ContractAddress == State.ParliamentContract.Value, "wrong organization type");
     Assert(CheckOrganizationExist(input), "new controller does not exist");
     State.SideRentalParliamentController.Value = input;
     return(new Empty());
 }
 public override Empty ChangeSymbolsToPayTXSizeFeeController(AuthorityInfo input)
 {
     AssertControllerForSymbolToPayTxSizeFee();
     Assert(input != null, "invalid input");
     Assert(input.ContractAddress == State.ParliamentContract.Value, "wrong organization type");
     Assert(CheckOrganizationExist(input), "new controller does not exist");
     State.SymbolToPayTxFeeController.Value = input;
     return(new Empty());
 }
Esempio n. 11
0
 /// <summary>
 /// iOS broker does not handle silent flow
 /// </summary>
 public Task <IReadOnlyList <IAccount> > GetAccountsAsync(
     string clientID,
     string redirectUri,
     AuthorityInfo authorityInfo,
     ICacheSessionManager cacheSessionManager,
     IInstanceDiscoveryManager instanceDiscoveryManager)
 {
     return(Task.FromResult(CollectionHelpers.GetEmptyReadOnlyList <IAccount>())); // nop
 }
        /// <summary>
        /// Figures out the authority based on the authority from the config and the authority from the request,
        /// and optionally the homeAccountTenantId, which has an impact on AcquireTokenSilent
        ///
        /// The algorithm is:
        ///
        /// 1. If there is no request authority (i.e. no authority override), use the config authority.
        ///     1.1. For AAD, if the config authority is "common" etc, try to use the tenanted version with the home account tenant ID
        /// 2. If there is a request authority, try to use it.
        ///     2.1. If the request authority is not "common", then use it
        ///     2.2  If the request authority is "common", ignore it, and use 1.1
        ///
        /// Special cases:
        ///
        /// - if the authority is not defined at the application level and the request level is not AAD, use the request authority
        /// - if the authority is defined at app level, and the request level authority of is of different type, throw an exception
        ///
        /// </summary>
        public static Authority CreateAuthorityForRequest(
            AuthorityInfo configAuthorityInfo,
            AuthorityInfo requestAuthorityInfo,
            string requestHomeAccountTenantId = null)
        {
            if (configAuthorityInfo == null)
            {
                throw new ArgumentNullException(nameof(configAuthorityInfo));
            }

            ValidateTypeMismatch(configAuthorityInfo, requestAuthorityInfo);

            switch (configAuthorityInfo.AuthorityType)
            {
            // ADFS and B2C are tenant-less, no need to consider tenant
            case AuthorityType.Adfs:
                return(requestAuthorityInfo == null ?
                       new AdfsAuthority(configAuthorityInfo) :
                       new AdfsAuthority(requestAuthorityInfo));

            case AuthorityType.B2C:

                if (requestAuthorityInfo != null)
                {
                    CheckB2CAuthorityHost(requestAuthorityInfo, configAuthorityInfo);
                    return(new B2CAuthority(requestAuthorityInfo));
                }
                return(new B2CAuthority(configAuthorityInfo));

            case AuthorityType.Aad:

                if (requestAuthorityInfo == null)
                {
                    return(CreateAuthorityWithTenant(configAuthorityInfo, requestHomeAccountTenantId));
                }

                // In case the authority is defined only at the request level
                if (configAuthorityInfo.IsDefaultAuthority &&
                    requestAuthorityInfo.AuthorityType != AuthorityType.Aad)
                {
                    return(CreateAuthority(requestAuthorityInfo));
                }

                var requestAuthority = new AadAuthority(requestAuthorityInfo);
                if (!requestAuthority.IsCommonOrganizationsOrConsumersTenant())
                {
                    return(requestAuthority);
                }

                return(CreateAuthorityWithTenant(configAuthorityInfo, requestHomeAccountTenantId));

            default:
                throw new MsalClientException(
                          MsalError.InvalidAuthorityType,
                          "Unsupported authority type");
            }
        }
Esempio n. 13
0
 public override Empty ChangeCodeCheckController(AuthorityInfo input)
 {
     AssertSenderAddressWith(State.CodeCheckController.Value.OwnerAddress);
     RequireParliamentContractAddressSet();
     Assert(State.ParliamentContract.Value == input.ContractAddress && CheckOrganizationExist(input),
            "Invalid authority input.");
     State.CodeCheckController.Value = input;
     return(new Empty());
 }
        public override Empty ChangeCrossChainTokenContractRegistrationController(AuthorityInfo input)
        {
            CheckCrossChainTokenContractRegistrationControllerAuthority();
            var organizationExist = CheckOrganizationExist(input);

            Assert(organizationExist, "Invalid authority input.");
            State.CrossChainTokenContractRegistrationController.Value = input;
            return(new Empty());
        }
 public override Empty ChangeDeveloperController(AuthorityInfo input)
 {
     AssertDeveloperFeeController();
     Assert(CheckOrganizationExist(input), "Invalid authority input.");
     State.DeveloperFeeController.Value.RootController       = input;
     State.DeveloperFeeController.Value.ParliamentController = null;
     State.DeveloperFeeController.Value.DeveloperController  = null;
     return(new Empty());
 }
        internal static Authority CreateAuthorityWithEnvironment(AuthorityInfo authorityInfo, string environment)
        {
            var uriBuilder = new UriBuilder(authorityInfo.CanonicalAuthority)
            {
                Host = environment
            };

            return(CreateAuthority(uriBuilder.Uri.AbsoluteUri, authorityInfo.ValidateAuthority));
        }
        /// <summary>
        /// 权限模型映射
        /// </summary>
        public static Authority ToModel(this AuthorityInfo authorityInfo)
        {
            Authority authority = authorityInfo.Map <AuthorityInfo, Authority>();

            authority.InfoSystemName      = authorityInfo.InfoSystemInfo.Name;
            authority.ApplicationTypeName = authorityInfo.ApplicationType.GetEnumMember();

            return(authority);
        }
        public async Task <AuthorityEndpoints> ResolveEndpointsAsync(
            AuthorityInfo authorityInfo,
            string userPrincipalName,
            RequestContext requestContext)
        {
            if (TryGetCacheValue(authorityInfo, userPrincipalName, out var endpoints))
            {
                requestContext.Logger.Info(LogMessages.ResolvingAuthorityEndpointsTrue);
                return(endpoints);
            }

            requestContext.Logger.Info(LogMessages.ResolvingAuthorityEndpointsFalse);

            var    authorityUri = new Uri(authorityInfo.CanonicalAuthority);
            string path         = authorityUri.AbsolutePath.Substring(1);
            string tenant       = path.Substring(0, path.IndexOf("/", StringComparison.Ordinal));

            var endpointManager = OpenIdConfigurationEndpointManagerFactory.Create(authorityInfo, _serviceBundle);

            string openIdConfigurationEndpoint = await endpointManager.ValidateAuthorityAndGetOpenIdDiscoveryEndpointAsync(
                authorityInfo,
                userPrincipalName,
                requestContext).ConfigureAwait(false);

            // Discover endpoints via openid-configuration
            var edr = await DiscoverEndpointsAsync(openIdConfigurationEndpoint, requestContext).ConfigureAwait(false);

            if (string.IsNullOrEmpty(edr.AuthorizationEndpoint))
            {
                throw new MsalClientException(
                          MsalError.TenantDiscoveryFailedError,
                          MsalErrorMessage.AuthorizeEndpointWasNotFoundInTheOpenIdConfiguration);
            }

            if (string.IsNullOrEmpty(edr.TokenEndpoint))
            {
                throw new MsalClientException(
                          MsalError.TenantDiscoveryFailedError,
                          MsalErrorMessage.TokenEndpointWasNotFoundInTheOpenIdConfiguration);
            }

            if (string.IsNullOrEmpty(edr.Issuer))
            {
                throw new MsalClientException(
                          MsalError.TenantDiscoveryFailedError,
                          MsalErrorMessage.IssuerWasNotFoundInTheOpenIdConfiguration);
            }

            endpoints = new AuthorityEndpoints(
                edr.AuthorizationEndpoint.Replace(Constants.Tenant, tenant),
                edr.TokenEndpoint.Replace(Constants.Tenant, tenant),
                ReplaceNonTenantSpecificValueWithTenant(edr, tenant));

            Add(authorityInfo, userPrincipalName, endpoints);
            return(endpoints);
        }
Esempio n. 19
0
 public override Empty ChangeCrossChainIndexingController(AuthorityInfo input)
 {
     AssertCrossChainIndexingControllerAuthority(Context.Sender);
     SetContractStateRequired(State.ParliamentContract, SmartContractConstants.ParliamentContractSystemName);
     Assert(
         input.ContractAddress == State.ParliamentContract.Value &&
         ValidateParliamentOrganization(input.OwnerAddress, true), "Invalid authority input.");
     State.CrossChainIndexingController.Value = input;
     return(new Empty());
 }
        private static void VerifyAuthority(
            AuthorityInfo config,
            AuthorityInfo request,
            string accountTid,
            string resultTid)
        {
            var resultAuthority = Authority.CreateAuthorityForRequest(config, request, accountTid);

            Assert.AreEqual(resultTid, resultAuthority.GetTenantId());
        }
        //-------------------------------------------------------
        // 保存 删除
        //-------------------------------------------------------

        #region 函数:Save(XmlDocument doc)
        /// <summary>保存信息</summary>
        /// <param name="doc">Xml 文档对象</param>
        /// <returns>返回操作结果</returns>
        public string Save(XmlDocument doc)
        {
            AuthorityInfo param = new AuthorityInfo();

            param = AjaxUtil.Deserialize <AuthorityInfo>(param, doc);

            service.Save(param);

            return(MessageObject.Stringify("0", I18n.Strings["msg_save_success"]));
        }
Esempio n. 22
0
 public Task <IReadOnlyList <IAccount> > GetAccountsAsync(
     string clientID,
     string redirectUri,
     AuthorityInfo authorityInfo,
     ICacheSessionManager cacheSessionManager,
     IInstanceDiscoveryManager instanceDiscoveryManager)
 {
     _logger.Info("NullBroker - returning empty list on GetAccounts request.");
     return(Task.FromResult(CollectionHelpers.GetEmptyReadOnlyList <IAccount>())); // nop
 }
        /// <summary>
        /// The algorithm here is much more complex in order to workaround a limitation in the AAD plugin's
        /// handling of guest accounts:
        ///
        /// 1. Read the accounts from WAM.AADPlugin
        /// 2. For each account, we need to find its home_account_id as the one from WAM may not be correct
        /// 3. If we can find a cached account with the same LocalAccountId or UPN, use it
        /// 4. If not, make a simple silent token request and use the client info provided
        /// </summary>
        public async Task <IReadOnlyList <IAccount> > GetAccountsAsync(
            string clientId,
            AuthorityInfo authorityInfo,
            Cache.ICacheSessionManager cacheSessionManager,
            Instance.Discovery.IInstanceDiscoveryManager instanceDiscoveryManager)
        {
            var webAccountProvider = await _webAccountProviderFactory.GetAccountProviderAsync("organizations").ConfigureAwait(false);

            var wamAccounts = await _wamProxy.FindAllWebAccountsAsync(webAccountProvider, clientId).ConfigureAwait(false);

            if (wamAccounts.Count > 0)
            {
                var webAccountEnvs = wamAccounts
                                     .Select(w =>
                {
                    _wamProxy.TryGetAccountProperty(w, "Authority", out string accountAuthority);
                    if (accountAuthority != null)
                    {
                        return((new Uri(accountAuthority)).Host);
                    }
                    else
                    {
                        _logger.WarningPii(
                            $"[WAM AAD Provider] Could not convert the WAM account {w.UserName} (id: {w.Id}) to an MSAL account because the Authority could not be found",
                            $"[WAM AAD Provider] Could not convert the WAM account {w.Id} to an MSAL account because the Authority could not be found");

                        return(null);
                    }
                })
                                     .Where(a => a != null);

                var instanceMetadata = await instanceDiscoveryManager.GetMetadataEntryTryAvoidNetworkAsync(authorityInfo, webAccountEnvs, cacheSessionManager.RequestContext)
                                       .ConfigureAwait(false);

                var accountsFromCache = await cacheSessionManager.GetAccountsAsync().ConfigureAwait(false);

                var msalAccountTasks = wamAccounts
                                       .Select(
                    async webAcc =>
                    await ConvertToMsalAccountOrNullAsync(
                        clientId,
                        webAcc,
                        instanceMetadata,
                        cacheSessionManager,
                        accountsFromCache).ConfigureAwait(false));

                var msalAccounts = (await Task.WhenAll(msalAccountTasks).ConfigureAwait(false)).Where(a => a != null).ToList();

                _logger.Info($"[WAM AAD Provider] GetAccountsAsync converted {msalAccounts.Count} accounts from {wamAccounts.Count} WAM accounts");
                return(msalAccounts);
            }

            _logger.Info("[WAM AAD provider] No accounts found.");
            return(Array.Empty <IAccount>());
        }
        protected Authority(AuthorityInfo authorityInfo)
        {
            if (authorityInfo == null)
            {
                throw new ArgumentNullException(nameof(authorityInfo));
            }

            // Don't reuse the same authority info, instead copy it
            // to prevent objects updating each other's details
            AuthorityInfo = new AuthorityInfo(authorityInfo);
        }
Esempio n. 25
0
        public override Empty ChangeMethodFeeController(AuthorityInfo input)
        {
            RequiredMethodFeeControllerSet();
            AssertSenderAddressWith(State.MethodFeeController.Value.OwnerAddress);
            var organizationExist = CheckOrganizationExist(input);

            Assert(organizationExist, "Invalid authority input.");

            State.MethodFeeController.Value = input;
            return(new Empty());
        }
        /// <inheritdoc />
        public Task <string> ValidateAuthorityAndGetOpenIdDiscoveryEndpointAsync(
            AuthorityInfo authorityInfo,
            string userPrincipalName,
            RequestContext requestContext)
        {
            string defaultEndpoint = string.Format(
                CultureInfo.InvariantCulture,
                new Uri(authorityInfo.CanonicalAuthority).AbsoluteUri + Constants.OpenIdConfigurationEndpoint);

            return(Task.FromResult(defaultEndpoint));
        }
Esempio n. 27
0
 public int AddAuthorityInfo(AuthorityInfo model)
 {
     try
     {
         return((int)HibernateTemplate.Save(model));
     }
     catch (Exception ex)
     {
         return(0);
     }
 }
 public override Empty ChangeSideChainLifetimeController(AuthorityInfo input)
 {
     AssertSideChainLifetimeControllerAuthority(Context.Sender);
     Assert(ValidateAuthorityInfoExists(input), "Invalid authority input.");
     State.SideChainLifetimeController.Value = input;
     Context.Fire(new SideChainLifetimeControllerChanged()
     {
         AuthorityInfo = input
     });
     return(new Empty());
 }
        public Task <IReadOnlyList <IAccount> > GetAccountsAsync(
            string clientID,
            string redirectUri,
            AuthorityInfo authorityInfo,
            ICacheSessionManager cacheSessionManager,
            IInstanceDiscoveryManager instanceDiscoveryManager)
        {
            // runtime does not yet support account discovery

            return(Task.FromResult <IReadOnlyList <IAccount> >(Array.Empty <IAccount>()));
        }
Esempio n. 30
0
        /// <summary></summary>
        /// <param name="entity"></param>
        /// <param name="authority"></param>
        /// <param name="authorizationScopes"></param>
        /// <param name="scopeText"></param>
        public static void BindAuthorizationScope(EntityClass entity, AuthorityInfo authority, IList <IAuthorizationScope> authorizationScopes, string scopeText)
        {
            IList <MembershipAuthorizationScopeObject> list = GetAuthorizationScopeObjects(scopeText);

            authorizationScopes.Clear();

            foreach (MembershipAuthorizationScopeObject item in list)
            {
                authorizationScopes.Add(new MembershipAuthorizationScope(entity, authority, item.GetAuthorizationObject()));
            }
        }