Asp.net mvc Azure Active Directory-身份验证单个租户

Asp.net mvc Azure Active Directory-身份验证单个租户,asp.net-mvc,azure,azure-active-directory,openid,Asp.net Mvc,Azure,Azure Active Directory,Openid,我正在尝试为我的web应用程序配置Azure AD单租户身份验证。我遵循了.NET的快速入门指南,但是我注意到我实际上可以使用任何Microsoft Office 365帐户登录到我的应用程序,而不是只使用租户中的帐户 有人能指出我的错误吗?我希望它拒绝不在我的租户(@mydomain.com电子邮件地址)中的登录 Startup.cs public class Startup { // The Client ID (a.k.a. Application ID) is u

我正在尝试为我的web应用程序配置Azure AD单租户身份验证。我遵循了.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);            
        }
 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);
        }
公共类启动
{
//应用程序使用客户端ID(又称应用程序ID)向Azure AD唯一标识自己
字符串clientId=System.Configuration.ConfigurationManager.AppSettings[“clientId”];
//RedirectUri是用户登录后将重定向到的URL
字符串redirectUrl=System.Configuration.ConfigurationManager.AppSettings[“redirectUrl”];
//租户是租户ID(例如contoso.onmicrosoft.com,或多租户的“通用”)
静态只读字符串tenant=System.Configuration.ConfigurationManager.AppSettings[“tenant”];
//Authority是授权的URL,由Azure Active Directory端点和租户名称(例如。https://login.microsoftonline.com/contoso.onmicrosoft.com)
string authority=string.Format(System.Globalization.CultureInfo.InvariantCulture,System.Configuration.ConfigurationManager.AppSettings[“authority”],租户);
/// 
///配置OWIN以使用OpenIdConnect
/// 
/// 
/// 
公共无效配置(IAppBuilder应用程序)
{
app.usekentorovicookiesaver();
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(新的CookieAuthenticationOptions{
CookieName=“我的工作区”,
AuthenticationType=CookieAuthenticationDefaults.AuthenticationType,
AuthenticationMode=AuthenticationMode.Active,
CookieSecure=CookieSecureOption。始终,
CookieManager=新系统WebChunkingCookieManager(),
CookieDomain=“mydomain.com”,
ExpireTimeSpan=新的时间跨度(4,0,0),
slidengexpiration=true
});            
app.UseOpenIdConnectAuthentication(
新的OpenIdConnectAuthenticationOptions
{
//设置从web.config获得的ClientId、authority、RedirectUri以及UseTokenLifetime
ClientId=ClientId,
权威=权威,
RedirectUri=redirectUrl,
UseTokenLifetime=false,
//PostLogoutRedirectUri是用户注销后将重定向到的页面。在本例中,它使用的是主页
PostLogoutRedirectUri=重定向URL,
//作用域是请求的作用域:OpenIdConnectScopes.openidprofiles相当于字符串“openid profile”:在同意屏幕中,这将导致“登录并读取您的配置文件”
Scope=OpenIdConnectScope.OpenIdProfile,
//ResponseType设置为请求id_令牌,该令牌包含有关登录用户的基本信息
ResponseType=OpenIdConnectResponseType.IdToken,
//ValidateIssuer设置为false以允许任何组织的工作帐户登录到您的应用程序
//要仅允许来自单个组织的用户,请将validateisuer设置为true,并将web.config中的“租户”设置设置为租户名称或Id(例如:contoso.onmicrosoft.com)
//若要仅允许来自特定组织列表的用户,请将ValidateIssuer设置为true并使用ValidIssuers参数
TokenValidationParameters=新的TokenValidationParameters()
{
validateisuer=true,
ValidIssuers=新列表(){
"https://login.microsoftonline.com/my-client(应用程序)-id在此“
}
},
//OpenIdConnectAuthenticationNotifications将OWIN配置为向OnAuthenticationFailed方法发送身份验证失败的通知
通知=新的OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed=OnAuthenticationFailed
}
}
);            
}
/// 
///通过将用户重定向到主页并在查询字符串中显示错误来处理失败的身份验证请求
/// 
/// 
/// 
身份验证的专用任务失败(AuthenticationFailedNotification上下文)
{
if(context.Exception.Message.Contains(“IDE21323”)){
context.HandleResponse();
context.OwinContext.Authentication.Challenge();
}否则{
context.HandleResponse();
context.Response.Redirect(“/?errormessage=“+context.Exception.Message”);
}
返回Task.FromResult(0);
}
HomeController.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);            
        }
 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);
        }
公共无效登录()
{
如果(!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(
新的AuthenticationProperties{RedirectUri=“/”},
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}            
}
/// 
///发送OpenID连接注销请求。
/// 
公共无效签出()
{