Azure Active Directory - аутентификация с одним владельцем - PullRequest
1 голос
/ 07 мая 2019

Я пытаюсь настроить аутентификацию Azure AD Single Tenant для своего веб-приложения. Я следовал краткому руководству по началу работы с .NET, однако заметил, что на самом деле я могу войти в свое приложение, используя ЛЮБУЮ учетную запись Microsoft Office 365, а не только те, которые принадлежат моему арендатору, как я хочу.

Может кто-нибудь указать на мою ошибку? Я хочу, чтобы это отклоняло входы, которых нет у моего клиента (адрес электронной почты @ mydomain.com)

Startup.cs

public class Startup
    {
        // The Client ID (a.k.a. Application ID) is used by the application to uniquely identify itself to Azure AD
        string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

        // RedirectUri is the URL where the user will be redirected to after they sign in
        string redirectUrl = System.Configuration.ConfigurationManager.AppSettings["redirectUrl"];

        // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
        static readonly string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];

        // Authority is the URL for authority, composed by Azure Active Directory endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com)
        string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

        /// <summary>
        /// Configure OWIN to use OpenIdConnect 
        /// </summary>
        /// <param name="app"></param>
        /// 


        public void Configuration(IAppBuilder app)
        {
            app.UseKentorOwinCookieSaver();
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                CookieName = "My Workspace",
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                AuthenticationMode = AuthenticationMode.Active,
                CookieSecure = CookieSecureOption.Always,
                CookieManager = new SystemWebChunkingCookieManager(),
                CookieDomain = "mydomain.com",
                ExpireTimeSpan = new TimeSpan(4, 0, 0),
                SlidingExpiration = true
            });            
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    // Sets the ClientId, authority, RedirectUri as obtained from web.config - as well as UseTokenLifetime
                    ClientId = clientId,
                    Authority = authority,
                    RedirectUri = redirectUrl,
                    UseTokenLifetime = false,                    

                    // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                    PostLogoutRedirectUri = redirectUrl,

                    //Scope is the requested scope: OpenIdConnectScopes.OpenIdProfileis equivalent to the string 'openid profile': in the consent screen, this will result in 'Sign you in and read your profile'
                    Scope = OpenIdConnectScope.OpenIdProfile,

                    // ResponseType is set to request the id_token - which contains basic information about the signed-in user
                    ResponseType = OpenIdConnectResponseType.IdToken,                               

                    // ValidateIssuer set to false to allow work accounts from any organization to sign in to your application
                    // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name or Id (example: contoso.onmicrosoft.com)
                    // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
                    TokenValidationParameters = new TokenValidationParameters()
                        {

                            ValidateIssuer = true,
                            ValidIssuers = new List<string>() {
                                "https://login.microsoftonline.com/my-client(application)-id-is-here"
                            }
                        },

                    // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                    Notifications = new OpenIdConnectAuthenticationNotifications
                        {
                            AuthenticationFailed = OnAuthenticationFailed
                        }
                }
             );            
        }

        /// <summary>
        /// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            if (context.Exception.Message.Contains("IDE21323")) {
                context.HandleResponse();
                context.OwinContext.Authentication.Challenge();
            } else {
                context.HandleResponse();
                context.Response.Redirect("/?errormessage=" + context.Exception.Message);
            }
            return Task.FromResult(0);            
        }

Мои методы входа / выхода в HomeController.cs

 public void SignIn()
        {
            if (!Request.IsAuthenticated)
            {
                HttpContext.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties { RedirectUri = "/" },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }            
        }

        /// <summary>
        /// Send an OpenID Connect sign-out request.
        /// </summary>
        public void SignOut()
        {
            HttpContext.GetOwinContext().Authentication.SignOut(
                OpenIdConnectAuthenticationDefaults.AuthenticationType,
                CookieAuthenticationDefaults.AuthenticationType);
        }

Я бы хотел, чтобы мое приложение разрешало вход только из моей активной директории, а не из любой учетной записи office365. Я также хотел бы, чтобы он обнаружил, если у пользователя уже есть файл cookie на компьютере, предназначенном для другой учетной записи, и он делает то же самое, что делает Microsoft, когда они показывают сообщение ... «У учетной записи, с которой вы вошли в систему, нет доступа к это приложение. "

Кроме того, на портале Azure в моем приложении в приложениях Active Directory я выбрал «Учетные записи только в этом каталоге организации (mydomain.com)» для параметра «Кто может использовать это приложение или API».

Web.config

У меня есть следующие ключи в моем web.config

<add key="ClientId" value="MY CLIENT ID FROM AZURE AD APP" />
<add key="Tenant" value="MY TENANT ID FROM AZURE AD APP" />    
<add key="Authority" value="https://login.microsoftonline.com/{0}/v2.0" />

Что я делаю не так?

UPDATE

Хотя приложение все еще разрешает вход в систему из ЛЮБОЙ учетной записи Office 365, я смог добавить дополнительный код в свойство IssuerValidator TokenValidationParameters. Я не проверяю JWT на правильные значения TID и IDP, которые я ожидаю. Странно, даже когда я вхожу, используя учетную запись NOT в моем Active Directory, TID остается тем же - однако значение IDP отображается там, где его нет при аутентификации с «действительной» учетной записью.

...