使用 OpenID Connect 对 Azure AD 进行身份验证

Authentication to Azure AD using OpenID Connect

我有一个 MVC 应用程序可以对用户进行身份验证并获取 Graph API 的访问令牌。该应用程序运行没有问题。现在,当应用程序部署到 Azure 网站时,应用程序的设置与代码中配置的设置不同。在本地 运行ning 时,它继续 运行 没有问题,反映了预期的配置。

我的配置如下:

private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
        private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
        private static string authority = aadInstance + tenantId +"/v2.0";
        private static string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
        private static string scopes = "openid profile offline_access";
        string graphResourceId = "https://graph.windows.net";

        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = authority,
                    Scope = scopes,
                    ResponseType = OpenIdConnectResponseTypes.CodeIdToken,
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        // we inject our own multitenant validation logic
                        ValidateIssuer = true,
                        // map the claimsPrincipal's roles to the roles claim
                        RoleClaimType = "roles"
                    },
                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        AuthorizationCodeReceived = OnAuthorizationCodeReceivedAsync,
                        RedirectToIdentityProvider = (context) =>
                        {
                            // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                            // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
                            // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                            string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                            context.ProtocolMessage.RedirectUri = appBaseUrl;
                            context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                            return Task.FromResult(0);
                        }
                    }
                });
        }

当导航到托管在 Azure 网站上的网站时,我得到以下信息 URL:

https://login.microsoftonline.com/{mytenantid}/oauth2/authorize?
response_type=id_token
&redirect_uri={mywebsite}%2F.auth%2Flogin%2Faad%2Fcallback
&client_id={myclientid}
&scope=openid+profile+email
&response_mode=form_post
&nonce=8e30e3673b7743cfb0d3bbcfc09071fe_20210506154851
&state=redir%3D%252F&sso_reload=true

请注意 response_type(第二行)和 scope(第五行)与配置的不同。

然而,在本地 运行ning 时,我得到了正确的设置:

https://login.microsoftonline.com/{mytenantid}/oauth2/v2.0/authorize?
client_id={myclientid}
&response_mode=form_post
&response_type=code+id_token
&scope=openid+profile+offline_access
&state=OpenIdConnect.AuthenticationProperties%3dAEBM2yvxZTbQSs_KkD_NYaV2UG0NOUz26xyvse0tCqlrBt19AEdzRRtvB8XOyHyLnP5JNg3XsYChXxzYjXOp783oLQ27Cq6Ex2MbgMsI_Fz-hGlI7T0pOGKfCZmd9tsE
&nonce=637558966120041797.ZWJlMmUxZTktZDkzNi00NjUyLTk4ZTctZDNhYzliNjkyMDExZjEyNWExNDYtMjNlZi00OTJiLWEyY2MtNzE2YTExNmIxNmJh
&redirect_uri=http%3a%2f%2flocalhost%3a49480%2f
&post_logout_redirect_uri=http%3a%2f%2flocalhost%3a49480%2f
&sso_reload=true

谁能帮我看看为什么会这样?我需要 response_typecode id_token 以便我可以使用授权码获取访问令牌。

看来您的旧网络服务已损坏,因此无法很好地部署代码。如果你想要原因,最好联系azure supporter。

使用 ASP.NET 的 OpenID Connect 示例:https://github.com/AzureADQuickStarts/AppModelv2-WebApp-OpenIDConnect-DotNet/

Startup.cs:

    // The Client ID is used by the application to uniquely identify itself to Azure AD.
    string clientId = "ClientId";

    // RedirectUri is the URL where the user will be redirected to after they sign in.
    string redirectUri = "RedirectUri";

    // Tenant is the tenant ID (e.g. tenant-id, or 'common' for multi-tenant)
    static string tenant = "Tenant";

    // Authority is the URL for authority, composed by Microsoft identity platform endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
    string authority = "https://login.microsoftonline.com/" + tenant +"/v2.0");

    ......
    app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
    {
        ClientId = clientId,
        Authority = authority,
        RedirectUri = redirectUri,
        PostLogoutRedirectUri = redirectUri,
        Scope = OpenIdConnectScope.OpenIdProfile, // "openid profile"
        ResponseType = OpenIdConnectResponseType.CodeIdToken, // "code id_token"
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            AuthenticationFailed = OnAuthenticationFailed
        }
    });