/// <inheritdoc />
        internal override void Validate()
        {
            base.Validate();

            Config.ClientCredential = new ClientCredentialWrapper(Config);

            if (string.IsNullOrWhiteSpace(Config.RedirectUri))
            {
                Config.RedirectUri = Constants.DefaultConfidentialClientRedirectUri;
            }

            if (!Uri.TryCreate(Config.RedirectUri, UriKind.Absolute, out Uri uriResult))
            {
                throw new InvalidOperationException(MsalErrorMessage.InvalidRedirectUriReceived(Config.RedirectUri));
            }

            if (!string.IsNullOrEmpty(Config.AzureRegion) && Config.AuthorityInfo.ValidateAuthority == true)
            {
                throw new MsalClientException(
                          MsalError.RegionalAuthorityValidation,
                          "You configured both Regional Authority and Authority Validation. Authority validation is not currently supported for regional Azure authorities." +
                          "You can set the validateAuthority flag to false to use Azure Regional authority. Do not disable authority validation if you read the authority from an untrusted source, " +
                          "for example from the WWWAuthenticate header of an HTTP request that resulted in a 401 response. See https://aka.ms/msal-net-regional for details.");
            }
        }
Ejemplo n.º 2
0
        /// <inheritdoc />
        internal override void Validate()
        {
            base.Validate();

            //ADFS does not require client id to be in the form of a GUID.
            if (Config.Authority.AuthorityInfo?.AuthorityType != AuthorityType.Adfs && !Guid.TryParse(Config.ClientId, out _))
            {
                throw new MsalClientException(MsalError.ClientIdMustBeAGuid, MsalErrorMessage.ClientIdMustBeAGuid);
            }

            if (Config.IsBrokerEnabled && Config.MultiCloudSupportEnabled)
            {
                // TODO: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/3139
                throw new NotSupportedException(MsalErrorMessage.MultiCloudSupportUnavailable);
            }

            if (string.IsNullOrWhiteSpace(Config.RedirectUri))
            {
                Config.RedirectUri = PlatformProxyFactory.CreatePlatformProxy(null)
                                     .GetDefaultRedirectUri(Config.ClientId, Config.UseRecommendedDefaultRedirectUri);
            }

            if (!Uri.TryCreate(Config.RedirectUri, UriKind.Absolute, out Uri uriResult))
            {
                throw new InvalidOperationException(MsalErrorMessage.InvalidRedirectUriReceived(Config.RedirectUri));
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Brokers enable Single-Sign-On, device identification,
        /// and application identification verification. To enable one of these features,
        /// you need to set the WithBroker() parameters to true. See https://aka.ms/msal-net-brokers
        /// for more information on platform specific settings required to enable the broker.
        ///
        /// On iOS and Android, Authenticator and Company Portal serve as brokers.
        /// On Windows, WAM (Windows Account Manager) serves as broker. See https://aka.ms/msal-net-wam
        /// </summary>
        /// <param name="enableBroker">Determines whether or not to use broker with the default set to true.</param>
        /// <returns>A <see cref="PublicClientApplicationBuilder"/> from which to set more
        /// parameters, and to create a public client application instance</returns>
        /// <remarks>If your app uses .NET classic or .NET Core 3.x, and you wish to use the Windows broker,
        /// please install the nuget package Microsoft.Identity.Client.Desktop and call .WithWindowsBroker(true)</remarks>
        public PublicClientApplicationBuilder WithBroker(bool enableBroker = true)
        {
#if NET45
            throw new PlatformNotSupportedException("The Windows broker is not available on .NET Framework 4.5, please use at least .NET Framework 4.6.2");
#endif

#if NET461 || NET_CORE
            if (Config.BrokerCreatorFunc == null)
            {
                throw new PlatformNotSupportedException(
                          "The Windows broker is not directly available on MSAL for .NET Framework or .NET Core 3.x" +
                          " To use it, please install the nuget package named Microsoft.Identity.Client.Desktop " +
                          "and call the extension method .WithWindowsBroker(true)");
            }
#endif
#if NET461 || WINDOWS_APP || NET5_WIN
            if (!Config.ExperimentalFeaturesEnabled)
            {
                throw new MsalClientException(
                          MsalError.ExperimentalFeature,
                          MsalErrorMessage.ExperimentalFeature(nameof(WithBroker)));
            }
#endif

#pragma warning disable CS0162 // Unreachable code detected
            Config.IsBrokerEnabled = enableBroker;
            return(this);

#pragma warning restore CS0162 // Unreachable code detected
        }
Ejemplo n.º 4
0
 internal void ValidateUseOfExperimentalFeature([System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
 {
     if (!ServiceBundle.Config.ExperimentalFeaturesEnabled)
     {
         throw new MsalClientException(
                   MsalError.ExperimentalFeature,
                   MsalErrorMessage.ExperimentalFeature(memberName));
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Specifies if the token request should be sent to regional ESTS.
        /// If set, MSAL tries to auto-detect and use a regional Azure authority. This helps keep the authentication traffic inside the Azure region.
        /// If the region cannot be determined (e.g. not running on Azure), MSALClientException is thrown with error code region_discovery_failed.
        /// This feature requires configuration at tenant level.
        /// By default the value for this variable is false.
        /// </summary>
        /// <param name="autoDetectRegion"><c>true</c> if the token request should be sent to regional ESTS. Otherwise <c>false</c>.
        /// The default is <c>false</c></param>
        /// <returns>The builder to chain the .With methods</returns>
        public AcquireTokenForClientParameterBuilder WithAzureRegion(bool autoDetectRegion)
        {
            if (!ServiceBundle.Config.ExperimentalFeaturesEnabled)
            {
                throw new MsalClientException(
                          MsalError.ExperimentalFeature,
                          MsalErrorMessage.ExperimentalFeature(nameof(WithAzureRegion)));
            }

            CommonParameters.AddApiTelemetryFeature(ApiTelemetryFeature.WithAzureRegion, autoDetectRegion);
            Parameters.AutoDetectRegion = autoDetectRegion;
            return(this);
        }
 private static void ValidateTypeMismatch(AuthorityInfo configAuthorityInfo, AuthorityInfo requestAuthorityInfo)
 {
     if (!configAuthorityInfo.IsDefaultAuthority &&
         requestAuthorityInfo != null &&
         configAuthorityInfo.AuthorityType != requestAuthorityInfo.AuthorityType)
     {
         throw new MsalClientException(
                   MsalError.AuthorityTypeMismatch,
                   MsalErrorMessage.AuthorityTypeMismatch(
                       configAuthorityInfo.AuthorityType,
                       requestAuthorityInfo.AuthorityType));
     }
 }
        [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]  // hide confidential client on mobile
#endif
        public PublicClientApplicationBuilder WithBroker(bool enableBroker = true)
        {
#if DESKTOP || WINDOWS_APP
            if (!Config.ExperimentalFeaturesEnabled)
            {
                throw new MsalClientException(
                          MsalError.ExperimentalFeature,
                          MsalErrorMessage.ExperimentalFeature(nameof(WithBroker)));
            }
#endif

            Config.IsBrokerEnabled = enableBroker;
            return(this);
        }
        /// <inheritdoc />
        internal override void Validate()
        {
            base.Validate();

            if (string.IsNullOrWhiteSpace(Config.RedirectUri))
            {
                Config.RedirectUri = PlatformProxyFactory.CreatePlatformProxy(null)
                                     .GetDefaultRedirectUri(Config.ClientId, Config.UseRecommendedDefaultRedirectUri);
            }

            if (!Uri.TryCreate(Config.RedirectUri, UriKind.Absolute, out Uri uriResult))
            {
                throw new InvalidOperationException(MsalErrorMessage.InvalidRedirectUriReceived(Config.RedirectUri));
            }
        }
        /// <inheritdoc />
        internal override void Validate()
        {
            base.Validate();

            Config.ClientCredential = new ClientCredentialWrapper(Config);

            if (string.IsNullOrWhiteSpace(Config.RedirectUri))
            {
                Config.RedirectUri = Constants.DefaultConfidentialClientRedirectUri;
            }

            if (!Uri.TryCreate(Config.RedirectUri, UriKind.Absolute, out Uri uriResult))
            {
                throw new InvalidOperationException(MsalErrorMessage.InvalidRedirectUriReceived(Config.RedirectUri));
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Sets the certificate associated with the application.
        /// Applicable to first-party applications only, this method also allows to specify
        /// if the <see href="https://datatracker.ietf.org/doc/html/rfc7517#section-4.7">x5c claim</see> should be sent to Azure AD.
        /// Sending the x5c enables application developers to achieve easy certificate roll-over in Azure AD:
        /// this method will send the certificate chain to Azure AD along with the token request,
        /// so that Azure AD can use it to validate the subject name based on a trusted issuer policy.
        /// This saves the application admin from the need to explicitly manage the certificate rollover
        /// (either via portal or PowerShell/CLI operation). For details see https://aka.ms/msal-net-sni
        /// </summary>
        /// <param name="certificate">The X509 certificate used as credentials to prove the identity of the application to Azure AD.</param>
        /// <param name="sendX5C">To send X5C with every request or not. The default is <c>false</c></param>
        /// <remarks>You should use certificates with a private key size of at least 2048 bytes. Future versions of this library might reject certificates with smaller keys. </remarks>
        public ConfidentialClientApplicationBuilder WithCertificate(X509Certificate2 certificate, bool sendX5C)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }

            if (!certificate.HasPrivateKey)
            {
                throw new MsalClientException(MsalError.CertWithoutPrivateKey, MsalErrorMessage.CertMustHavePrivateKey(nameof(certificate)));
            }

            Config.ClientCredential = new CertificateClientCredential(certificate);
            Config.SendX5C          = sendX5C;
            return(this);
        }
Ejemplo n.º 11
0
        /// <summary>
        ///  Modifies the token acquisition request so that the acquired token is a Proof of Possession token (PoP), rather than a Bearer token.
        ///  PoP tokens are similar to Bearer tokens, but are bound to the HTTP request and to a cryptographic key, which MSAL can manage on Windows.
        ///  See https://aka.ms/msal-net-pop
        /// </summary>
        /// <param name="popAuthenticationConfiguration">Configuration properties used to construct a proof of possession request.</param>
        /// <remarks>
        /// <list type="bullet">
        /// <item> An Authentication header is automatically added to the request</item>
        /// <item> The PoP token is bound to the HTTP request, more specifically to the HTTP method (GET, POST, etc.) and to the Uri (path and query, but not query parameters). </item>
        /// <item> MSAL creates, reads and stores a key in memory that will be cycled every 8 hours.</item>
        /// <item>This is an experimental API. The method signature may change in the future without involving a major version upgrade.</item>
        /// </list>
        /// </remarks>
        public T WithProofOfPossession(PoPAuthenticationConfiguration popAuthenticationConfiguration)
        {
            if (!ServiceBundle.Config.ExperimentalFeaturesEnabled)
            {
                throw new MsalClientException(
                          MsalError.ExperimentalFeature,
                          MsalErrorMessage.ExperimentalFeature(nameof(WithProofOfPossession)));
            }

            CommonParameters.PopAuthenticationConfiguration = popAuthenticationConfiguration ?? throw new ArgumentNullException(nameof(popAuthenticationConfiguration));

            CommonParameters.AddApiTelemetryFeature(ApiTelemetryFeature.WithPoPScheme);
            CommonParameters.AuthenticationScheme = new PoPAuthenticationScheme(CommonParameters.PopAuthenticationConfiguration, ServiceBundle);

            return(this as T);
        }
        /// <inheritdoc />
        internal override void Validate()
        {
            base.Validate();

            int countOfCredentialTypesSpecified = 0;

            if (!string.IsNullOrWhiteSpace(Config.ClientSecret))
            {
                countOfCredentialTypesSpecified++;
            }

            if (Config.ClientCredentialCertificate != null)
            {
                countOfCredentialTypesSpecified++;
            }

            if (Config.ClientCredential != null)
            {
                countOfCredentialTypesSpecified++;
            }

            if (countOfCredentialTypesSpecified > 1)
            {
                throw new InvalidOperationException(MsalErrorMessage.ClientSecretAndCertificateAreMutuallyExclusive);
            }

            if (!string.IsNullOrWhiteSpace(Config.ClientSecret))
            {
                Config.ClientCredential = new ClientCredentialWrapper(Config.ClientSecret);
            }

            if (Config.ClientCredentialCertificate != null)
            {
                Config.ClientCredential = new ClientCredentialWrapper(new ClientAssertionCertificateWrapper(Config.ClientCredentialCertificate));
            }

            if (string.IsNullOrWhiteSpace(Config.RedirectUri))
            {
                Config.RedirectUri = Constants.DefaultConfidentialClientRedirectUri;
            }

            if (!Uri.TryCreate(Config.RedirectUri, UriKind.Absolute, out Uri uriResult))
            {
                throw new InvalidOperationException(MsalErrorMessage.InvalidRedirectUriReceived(Config.RedirectUri));
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Brokers enable Single-Sign-On, device identification,
        /// and application identification verification. To enable one of these features,
        /// you need to set the WithBroker() parameters to true. See https://aka.ms/msal-net-brokers
        /// for more information on platform specific settings required to enable the broker.
        ///
        /// On iOS and Android, Authenticator and Company Portal serve as brokers.
        /// On Windows, WAM (Windows Account Manager) serves as broker. See https://aka.ms/msal-net-wam
        /// </summary>
        /// <param name="enableBroker">Determines whether or not to use broker with the default set to true.</param>
        /// <returns>A <see cref="PublicClientApplicationBuilder"/> from which to set more
        /// parameters, and to create a public client application instance</returns>
        /// <remarks>If your app uses .NET classic or .NET Core 3.x, and you wish to use the Windows broker,
        /// please install the nuget package Microsoft.Identity.Client.Desktop and call .WithDesktopFeatures()</remarks>
        public PublicClientApplicationBuilder WithBroker(bool enableBroker = true)
        {
#pragma warning disable CS0162 // Unreachable code detected

#if NET45
            throw new PlatformNotSupportedException(
                      "The Windows broker is not available on .NET Framework 4.5, please use at least .NET Framework 4.6.2");
#endif

#if NET461
            if (Config.BrokerCreatorFunc == null)
            {
                throw new PlatformNotSupportedException(
                          "The Windows broker is not directly available on MSAL for .NET Framework" +
                          " To use it, please install the nuget package named Microsoft.Identity.Client.Desktop " +
                          "and call the extension method .WithWindowsBroker() first.");
            }
#endif

#if NET_CORE
            if (Config.BrokerCreatorFunc == null && DesktopOsHelper.IsWindows())
            {
                throw new PlatformNotSupportedException(
                          "If you have a Windows application which targets net5 or net5-windows, please change the target to net5-windows10.0.17763.0. \nYour app can still run on earlier versions of Windows such as Win7 if you add <SupportedOSPlatformVersion>7</SupportedOSPlatformVersion> in the csproj.\n The broker (WAM) is available only on Win10 and this library will fallback to a browser on older systems. " +

                          "\n\r\n\rIf you have a NET5 cross-platform (Windows, Mac, Linux) application, please dual target net5 and net5-windows10.0.17763.0. Your installer should deploy the net5 version on Mac and Linux and the net5-window10.0.17763.0 on Windows." +
                          "\n\r\n\rIf you have a .NET Core 3.1 application, please install the nuget package named Microsoft.Identity.Client.Desktop and call the extension method .WithWindowsBroker() first. " +
                          "\n\rFor details see https://aka.ms/msal-net-wam and https://github.com/dotnet/designs/blob/main/accepted/2020/platform-checks/platform-checks.md ");
            }
#endif

#if NET461 || WINDOWS_APP || NET5_WIN
            if (!Config.ExperimentalFeaturesEnabled)
            {
                throw new MsalClientException(
                          MsalError.ExperimentalFeature,
                          MsalErrorMessage.ExperimentalFeature(nameof(WithBroker)));
            }
#endif

            Config.IsBrokerEnabled = enableBroker;
            return(this);

#pragma warning restore CS0162 // Unreachable code detected
        }
        [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]  // hide confidential client on mobile
#endif
        public AcquireTokenSilentParameterBuilder WithProofOfPossession(PoPAuthenticationConfiguration popAuthenticationConfiguration)
        {
            ConfidentialClientApplication.GuardMobileFrameworks();

            if (!ServiceBundle.Config.ExperimentalFeaturesEnabled)
            {
                throw new MsalClientException(
                          MsalError.ExperimentalFeature,
                          MsalErrorMessage.ExperimentalFeature(nameof(WithProofOfPossession)));
            }

            CommonParameters.PopAuthenticationConfiguration = popAuthenticationConfiguration ?? throw new ArgumentNullException(nameof(popAuthenticationConfiguration));

            CommonParameters.AddApiTelemetryFeature(ApiTelemetryFeature.WithPoPScheme);
            CommonParameters.AuthenticationScheme = new PoPAuthenticationScheme(CommonParameters.PopAuthenticationConfiguration, ServiceBundle);

            return(this);
        }
Ejemplo n.º 15
0
        /// <inheritdoc />
        internal override void Validate()
        {
            base.Validate();

            if (string.IsNullOrWhiteSpace(Config.RedirectUri))
            {
                Config.RedirectUri = Constants.DefaultConfidentialClientRedirectUri;
            }

            if (!Uri.TryCreate(Config.RedirectUri, UriKind.Absolute, out Uri uriResult))
            {
                throw new InvalidOperationException(MsalErrorMessage.InvalidRedirectUriReceived(Config.RedirectUri));
            }

            if (!string.IsNullOrEmpty(Config.AzureRegion) && (Config.CustomInstanceDiscoveryMetadata != null || Config.CustomInstanceDiscoveryMetadataUri != null))
            {
                throw new MsalClientException(MsalError.RegionDiscoveryWithCustomInstanceMetadata, MsalErrorMessage.RegionDiscoveryWithCustomInstanceMetadata);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Brokers enable Single-Sign-On, device identification,
        /// and application identification verification. To enable one of these features,
        /// you need to set the WithBroker() parameters to true. See https://aka.ms/msal-net-brokers
        /// for more information on platform specific settings required to enable the broker.
        ///
        /// On iOS and Android, Authenticator and Company Portal serve as brokers.
        /// On Windows, WAM (Windows Account Manager) serves as broker. See https://aka.ms/msal-net-wam
        /// </summary>
        /// <param name="enableBroker">Determines whether or not to use broker with the default set to true.</param>
        /// <returns>A <see cref="PublicClientApplicationBuilder"/> from which to set more
        /// parameters, and to create a public client application instance</returns>
        /// <remarks>If your app uses .NET classic or .NET Core 3.x, and you wish to use the Windows broker,
        /// please install the nuget package Microsoft.Identity.Client.Desktop and call .WithDesktopFeatures()</remarks>
        public PublicClientApplicationBuilder WithBroker(bool enableBroker = true)
        {
#pragma warning disable CS0162 // Unreachable code detected

#if NET45
            throw new PlatformNotSupportedException(
                      "The Windows broker is not available on .NET Framework 4.5, please use at least .NET Framework 4.6.2");
#endif

#if NET461
            if (Config.BrokerCreatorFunc == null)
            {
                throw new PlatformNotSupportedException(
                          "The Windows broker is not directly available on MSAL for .NET Framework" +
                          " To use it, please install the nuget package named Microsoft.Identity.Client.Desktop " +
                          "and call the extension method .WithDesktopFeatures() first.");
            }
#endif

#if NET_CORE
            if (Config.BrokerCreatorFunc == null && Platforms.Features.DesktopOs.DesktopOsHelper.IsWindows())
            {
                throw new PlatformNotSupportedException(
                          "If you have a Windows application which targets net5 or net5-windows, please change the target to net5-windows10.0.17763.0, which provides support from Win7 to Win10. For details see https://github.com/dotnet/designs/blob/main/accepted/2020/platform-checks/platform-checks.md" +
                          "If you have a cross-platform (Windows, Mac, Linux) application which targets net5, please dual target net5 and net5-windows10.0.17763.0. Your installer should deploy the net5 version on Mac and Linux and the net5-window10.0.17763.0 on Win7-Win10. For details see https://github.com/dotnet/designs/blob/main/accepted/2020/platform-checks/platform-checks.md" +
                          "If you have a .NET Core 3.1 application, please install the nuget package named Microsoft.Identity.Client.Desktop and call the extension method .WithDesktopFeatures() first.");
            }
#endif

#if NET461 || WINDOWS_APP || NET5_WIN
            if (!Config.ExperimentalFeaturesEnabled)
            {
                throw new MsalClientException(
                          MsalError.ExperimentalFeature,
                          MsalErrorMessage.ExperimentalFeature(nameof(WithBroker)));
            }
#endif

            Config.IsBrokerEnabled = enableBroker;
            return(this);

#pragma warning restore CS0162 // Unreachable code detected
        }
        // Allows testing the PoP flow with any crypto. Consider making this public.
        internal T WithProofOfPosession(HttpRequestMessage httpRequestMessage, IPoPCryptoProvider popCryptoProvider)
        {
            if (!ServiceBundle.Config.ExperimentalFeaturesEnabled)
            {
                throw new MsalClientException(
                          MsalError.ExperimentalFeature,
                          MsalErrorMessage.ExperimentalFeature(nameof(WithProofOfPosession)));
            }

            if (httpRequestMessage is null)
            {
                throw new ArgumentNullException(nameof(httpRequestMessage));
            }

            if (popCryptoProvider == null)
            {
                throw new ArgumentNullException(nameof(popCryptoProvider));
            }

            CommonParameters.AddApiTelemetryFeature(ApiTelemetryFeature.WithPoPScheme);
            CommonParameters.AuthenticationScheme = new PoPAuthenticationScheme(httpRequestMessage, popCryptoProvider);

            return(this as T);
        }