Azure 应用服务中的身份验证和授权的高级用法Advanced usage of authentication and authorization in Azure App Service

本文介绍了如何自定义应用服务中的内置身份验证和授权,以及如何从应用程序管理标识。This article shows you how to customize the built-in authentication and authorization in App Service, and to manage identity from your application.

若要快速入门,请参阅以下教程之一:To get started quickly, see one of the following tutorials:

使用多个登录提供程序Use multiple sign-in providers

门户配置不会提供向用户显示多个登录提供程序的统包方式。The portal configuration doesn't offer a turn-key way to present multiple sign-in providers to your users. 但是,将此功能添加到应用并不困难。However, it isn't difficult to add the functionality to your app. 步骤概括如下:The steps are outlined as follows:

首先,在 Azure 门户中的“身份验证/授权”页上,配置想要启用的每个标识提供者。 First, in the Authentication / Authorization page in the Azure portal, configure each of the identity provider you want to enable.

在“请求未经身份验证时需执行的操作”中,选择“允许匿名请求(无操作)”。 In Action to take when request is not authenticated , select Allow Anonymous requests (no action) .

在登录页、导航栏或应用的其他任何位置中,将一个登录链接添加到已启用的每个提供程序 (/.auth/login/<provider>)。In the sign-in page, or the navigation bar, or any other location of your app, add a sign-in link to each of the providers you enabled (/.auth/login/<provider>). 例如:For example:

<a href="/.auth/login/aad">Log in with Azure AD</a>
<a href="/.auth/login/microsoftaccount">Log in with Microsoft Account</a>

当用户单击其中一个链接时,系统会打开相应的登录页让用户登录。When the user clicks on one of the links, the respective sign-in page opens to sign in the user.

若要将登录后用户重定向到自定义 URL,请使用 post_login_redirect_url 查询字符串参数(不要与标识提供者配置中的重定向 URI 混淆)。To redirect the user post-sign-in to a custom URL, use the post_login_redirect_url query string parameter (not to be confused with the Redirect URI in your identity provider configuration). 例如,若要在登录后将用户导航至 /Home/Index,使用以下 HTML 代码:For example, to navigate the user to /Home/Index after sign-in, use the following HTML code:

<a href="/.auth/login/<provider>?post_login_redirect_url=/Home/Index">Log in</a>

验证来自提供程序的令牌Validate tokens from providers

在客户端定向的登录中,应用程序手动将用户登录到提供程序,然后将身份验证令牌提交给应用服务进行验证(请参阅身份验证流)。In a client-directed sign-in, the application signs in the user to the provider manually and then submits the authentication token to App Service for validation (see Authentication flow). 此验证本身不实际向你授予对所需应用资源的访问权限,但成功的验证会向你提供一个会话令牌,可以使用该令牌来访问应用资源。This validation itself doesn't actually grant you access to the desired app resources, but a successful validation will give you a session token that you can use to access app resources.

若要验证提供程序令牌,必须首先为应用服务应用配置所需的提供程序。To validate the provider token, App Service app must first be configured with the desired provider. 在运行时,从你的提供程序检索身份验证令牌后,将令牌发布到 /.auth/login/<provider> 进行验证。At runtime, after you retrieve the authentication token from your provider, post the token to /.auth/login/<provider> for validation. 例如:For example:

POST https://<appname>.chinacloudsites.cn/.auth/login/aad HTTP/1.1
Content-Type: application/json

{"id_token":"<token>","access_token":"<token>"}

令牌格式根据提供程序而略有不同。The token format varies slightly according to the provider. 有关详细信息,请参阅下表:See the following table for details:

提供程序值Provider value 请求正文中必需的Required in request body 注释Comments
aad {"access_token":"<access_token>"}
microsoftaccount {"access_token":"<token>"} expires_in 属性为可选。The expires_in property is optional.
从 Live 服务请求令牌时,将始终请求 wl.basic 作用域。When requesting the token from Live services, always request the wl.basic scope.

如果提供程序令牌成功通过验证,则 API 将在响应正文中返回一个 authenticationToken,这是你的会话令牌。If the provider token is validated successfully, the API returns with an authenticationToken in the response body, which is your session token.

{
    "authenticationToken": "...",
    "user": {
        "userId": "sid:..."
    }
}

获得此会话令牌后,你可以通过向 HTTP 请求中添加 X-ZUMO-AUTH 标头来访问受保护的应用资源。Once you have this session token, you can access protected app resources by adding the X-ZUMO-AUTH header to your HTTP requests. 例如:For example:

GET https://<appname>.chinacloudsites.cn/api/products/1
X-ZUMO-AUTH: <authenticationToken_value>

注销会话Sign out of a session

用户可通过向应用的 /.auth/logout 终结点发送 GET 请求来启动注销。Users can initiate a sign-out by sending a GET request to the app's /.auth/logout endpoint. GET 请求可执行以下操作:The GET request does the following:

  • 清除当前会话中的身份验证 Cookie。Clears authentication cookies from the current session.
  • 从令牌存储中删除当前用户的令牌。Deletes the current user's tokens from the token store.
  • 对于 Azure Active Directory,请对标识提供者执行服务器端注销。For Azure Active Directory, performs a server-side sign-out on the identity provider.

以下是网页中一个简单的注销链接:Here's a simple sign-out link in a webpage:

<a href="/.auth/logout">Sign out</a>

默认情况下,成功注销后,客户端会重定向到 URL /.auth/logout/doneBy default, a successful sign-out redirects the client to the URL /.auth/logout/done. 通过添加 post_logout_redirect_uri 查询参数可更改注销后的重定向页面。You can change the post-sign-out redirect page by adding the post_logout_redirect_uri query parameter. 例如:For example:

GET /.auth/logout?post_logout_redirect_uri=/index.html

建议对 post_logout_redirect_uri 的值进行编码。It's recommended that you encode the value of post_logout_redirect_uri.

使用完全限定的 URL 时,URL 必须托管在同一域中,或配置为允许应用访问的外部重定向 URL。When using fully qualified URLs, the URL must be either hosted in the same domain or configured as an allowed external redirect URL for your app. 在以下示例中,若要重定向到未托管在同一域中的 https://myexternalurl.comIn the following example, to redirect to https://myexternalurl.com that's not hosted in the same domain:

GET /.auth/logout?post_logout_redirect_uri=https%3A%2F%2Fmyexternalurl.com

在 Azure CLI 中运行以下命令:Run the following command in the Azure CLI :

az webapp auth update --name <app_name> --resource-group <group_name> --allowed-external-redirect-urls "https://myexternalurl.com"

保留 URL 片段Preserve URL fragments

用户登录应用后,通常希望会重定向到同一页面的同一部分,例如 /wiki/Main_Page#SectionZAfter users sign in to your app, they usually want to be redirected to the same section of the same page, such as /wiki/Main_Page#SectionZ. 但是,由于从不向服务器发送 URL 片段(例如,#SectionZ),因此默认情况下,OAuth 登录完成并重定向回应用后,会保留这些片段。However, because URL fragments (for example, #SectionZ) are never sent to the server, they are not preserved by default after the OAuth sign-in completes and redirects back to your app. 然后,当用户需再次导航到所需定位点时,他们无法获得最佳体验。Users then get a suboptimal experience when they need to navigate to the desired anchor again. 此限制存在于所有服务器端身份验证解决方案中。This limitation applies to all server-side authentication solutions.

在应用服务身份验证中,可跨 OAuth 登录保留 URL 片段。In App Service authentication, you can preserve URL fragments across the OAuth sign-in. 为此,请将名为 WEBSITE_AUTH_PRESERVE_URL_FRAGMENT 的应用设置设为 trueTo do this, set an app setting called WEBSITE_AUTH_PRESERVE_URL_FRAGMENT to true. 可在 Azure 门户 中执行此操作,或只需在 Azure CLI 中运行以下命令:You can do it in the Azure portal, or simply run the following command in the Azure CLI:

az webapp config appsettings set --name <app_name> --resource-group <group_name> --settings WEBSITE_AUTH_PRESERVE_URL_FRAGMENT="true"

访问用户声明Access user claims

应用服务使用特殊的标头将用户声明传递给应用程序。App Service passes user claims to your application by using special headers. 不允许外部请求设置这些标头,因此,只会提供应用服务设置的标头。External requests aren't allowed to set these headers, so they are present only if set by App Service. 部分标头示例如下:Some example headers include:

  • X-MS-CLIENT-PRINCIPAL-NAMEX-MS-CLIENT-PRINCIPAL-NAME
  • X-MS-CLIENT-PRINCIPAL-IDX-MS-CLIENT-PRINCIPAL-ID

使用任何语言或框架编写的代码均可从这些标头获取所需信息。Code that is written in any language or framework can get the information that it needs from these headers. 对于 ASP.NET 4.6 应用, ClaimsPrincipal 会自动设置为相应的值。For ASP.NET 4.6 apps, the ClaimsPrincipal is automatically set with the appropriate values. 但是,ASP.NET Core 不提供与应用服务用户声明集成的身份验证中间件。ASP.NET Core, however, doesn't provide an authentication middleware that integrates with App Service user claims. 有关解决方法,请参阅 MaximeRouiller.Azure.AppService.EasyAuthFor a workaround, see MaximeRouiller.Azure.AppService.EasyAuth.

应用程序也可以通过调用 /.auth/me 来获取有关经过身份验证的用户的其他详细信息。Your application can also obtain additional details on the authenticated user by calling /.auth/me. 移动应用服务器 SDK 提供处理该数据的帮助器方法。The Mobile Apps server SDKs provide helper methods to work with this data. 有关详细信息,请参阅如何使用 Azure 移动应用 Node.js SDK使用适用于 Azure 移动应用的 .NET 后端服务器 SDKFor more information, see How to use the Azure Mobile Apps Node.js SDK, and Work with the .NET backend server SDK for Azure Mobile Apps.

检索应用代码中的令牌Retrieve tokens in app code

在服务器代码中,提供程序特定的令牌将注入到请求标头中,使你可以轻松访问这些令牌。From your server code, the provider-specific tokens are injected into the request header, so you can easily access them. 下表显示了可能的令牌标头名称:The following table shows possible token header names:

提供程序Provider 标头名称Header names
Azure Active DirectoryAzure Active Directory X-MS-TOKEN-AAD-ID-TOKEN
X-MS-TOKEN-AAD-ACCESS-TOKEN
X-MS-TOKEN-AAD-EXPIRES-ON
X-MS-TOKEN-AAD-REFRESH-TOKEN
Microsoft 帐户Microsoft Account X-MS-TOKEN-MICROSOFTACCOUNT-ACCESS-TOKEN
X-MS-TOKEN-MICROSOFTACCOUNT-EXPIRES-ON
X-MS-TOKEN-MICROSOFTACCOUNT-AUTHENTICATION-TOKEN
X-MS-TOKEN-MICROSOFTACCOUNT-REFRESH-TOKEN

在客户端代码(例如移动应用或浏览器中 JavaScript)中,将 HTTP GET 请求发送到 /.auth/meFrom your client code (such as a mobile app or in-browser JavaScript), send an HTTP GET request to /.auth/me. 返回的 JSON 包含提供程序特定的令牌。The returned JSON has the provider-specific tokens.

备注

访问令牌用于访问提供程序资源,因此,仅当使用客户端机密配置了提供程序时,才提供这些令牌。Access tokens are for accessing provider resources, so they are present only if you configure your provider with a client secret. 若要了解如何获取刷新令牌,请参阅“刷新访问令牌”。To see how to get refresh tokens, see Refresh access tokens.

刷新标识提供程序令牌Refresh identity provider tokens

当提供程序的访问令牌(而不是会话令牌)到期时,需要在再次使用该令牌之前重新验证用户。When your provider's access token (not the session token) expires, you need to reauthenticate the user before you use that token again. 向应用程序的 /.auth/refresh 终结点发出 GET 调用可以避免令牌过期。You can avoid token expiration by making a GET call to the /.auth/refresh endpoint of your application. 调用应用服务时,应用服务会自动刷新已身份验证用户的令牌存储中的访问令牌。When called, App Service automatically refreshes the access tokens in the token store for the authenticated user. 应用代码发出的后续令牌请求将获取刷新的令牌。Subsequent requests for tokens by your app code get the refreshed tokens. 但是,若要正常刷新令牌,令牌存储必须包含提供程序的刷新令牌However, for token refresh to work, the token store must contain refresh tokens for your provider. 每个提供程序会阐述获取刷新令牌的方式。以下列表提供了简短摘要:The way to get refresh tokens are documented by each provider, but the following list is a brief summary:

配置提供程序以后,即可在令牌存储中找到访问令牌的刷新令牌和过期时间Once your provider is configured, you can find the refresh token and the expiration time for the access token in the token store.

若要随时刷新访问令牌,只需以任何语言调用 /.auth/refreshTo refresh your access token at any time, just call /.auth/refresh in any language. 以下代码片段从 JavaScript 客户端使用 jQuery 刷新访问令牌。The following snippet uses jQuery to refresh your access tokens from a JavaScript client.

function refreshTokens() {
  let refreshUrl = "/.auth/refresh";
  $.ajax(refreshUrl) .done(function() {
    console.log("Token refresh completed successfully.");
  }) .fail(function() {
    console.log("Token refresh failed. See application logs for details.");
  });
}

如果用户撤销了授予应用的权限,对 /.auth/me 的调用可能会失败并返回 403 Forbidden 响应。If a user revokes the permissions granted to your app, your call to /.auth/me may fail with a 403 Forbidden response. 若要诊断错误,请查看应用程序日志了解详细信息。To diagnose errors, check your application logs for details.

延长会话令牌过期宽限期Extend session token expiration grace period

经过身份验证的会话会在 8 小时后过期。The authenticated session expires after 8 hours. 经过身份验证的会话过期后,默认会提供 72 小时的宽限期。After an authenticated session expires, there is a 72-hour grace period by default. 在此宽限期内,可以使用应用服务刷新会话令牌,而无需重新对用户进行身份验证。Within this grace period, you're allowed to refresh the session token with App Service without reauthenticating the user. 会话令牌失效后,只需调用 /.auth/refresh,而不需要自行跟踪令牌过期时间。You can just call /.auth/refresh when your session token becomes invalid, and you don't need to track token expiration yourself. 72 小时的宽限期过后,用户必须重新登录才能获取有效的会话令牌。Once the 72-hour grace period is lapses, the user must sign in again to get a valid session token.

如果 72 小时的时间不够,可以延长此过期期限。If 72 hours isn't enough time for you, you can extend this expiration window. 大大延长过期时间可能会造成严重的安全风险(例如身份验证令牌泄密或被盗)。Extending the expiration over a long period could have significant security implications (such as when an authentication token is leaked or stolen). 因此,应将宽限期保留为默认 72 小时,或者将延期设为最小值。So you should leave it at the default 72 hours or set the extension period to the smallest value.

若要延长默认的过期期限,请在 Azure CLI 中运行以下命令。To extend the default expiration window, run the following command in the Azure CLI.

az webapp auth update --resource-group <group_name> --name <app_name> --token-refresh-extension-hours <hours>

备注

宽限期仅适用于应用服务的已经身份验证的会话,而不适用于来自标识提供者的令牌。The grace period only applies to the App Service authenticated session, not the tokens from the identity providers. 已过期的提供程序令牌没有宽限期。There is no grace period for the expired provider tokens.

限制登录帐户的域Limit the domain of sign-in accounts

Microsoft 帐户和 Azure Active Directory 都允许从多个域登录。Both Microsoft Account and Azure Active Directory lets you sign in from multiple domains. Azure AD 允许对登录帐户使用任意数量的自定义域。Azure AD allows any number of custom domains for the sign-in accounts. 但是,建议将用户直接转到自己品牌的 Azure AD 登录页面(如 contoso.com)。However, you may want to accelerate your users straight to your own branded Azure AD sign-in page (such as contoso.com). 若要推荐登录帐户的域名,请执行以下步骤。To suggest the domain name of the sign-in accounts, follow these steps.

此设置将 domain_hint 查询字符串参数追加到登录重定向 URL。This setting appends the domain_hint query string parameter to the login redirect URL.

重要

接收重定向 URL 之后,客户端可能删除 domain_hint 参数,然后使用其他域登录。It's possible for the client to remove the domain_hint parameter after receiving the redirect URL, and then login with a different domain. 所以虽然此功能非常方便,但它不是一项安全功能。So while this function is convenient, it's not a security feature.

授权或拒绝用户Authorize or deny users

尽管应用服务会处理最简单的授权问题(例如,拒绝未经身份验证的请求),但应用可能需要更精细的授权行为,例如,仅将访问权限限制给特定的一组用户。While App Service takes care of the simplest authorization case (i.e. reject unauthenticated requests), your app may require more fine-grained authorization behavior, such as limiting access to only a specific group of users. 在某些情况下,需要编写自定义应用程序代码以允许或拒绝已登录用户的访问。In certain cases, you need to write custom application code to allow or deny access to the signed-in user. 在其他情况下,应用服务或标识提供者可能无需进行代码更改即可提供帮助。In other cases, App Service or your identity provider may be able to help without requiring code changes.

服务器级别(仅限 Windows 应用)Server level (Windows apps only)

对于任何 Windows 应用,可以通过编辑 Web.config 文件来定义 IIS Web 服务器的授权行为。For any Windows app, you can define authorization behavior of the IIS web server, by editing the Web.config file. Linux 应用不使用 IIS,无法通过 Web.config 进行配置。Linux apps don't use IIS and can't be configured through Web.config .

  1. 导航到 https://<app-name>.scm.chinacloudsites.cn/DebugConsoleNavigate to https://<app-name>.scm.chinacloudsites.cn/DebugConsole

  2. 在打开应用服务文件的浏览器资源管理器中,导航到“site/wwwroot”。 In the browser explorer of your App Service files, navigate to site/wwwroot . 如果 Web.config 不存在,请选择“+” > “新建文件”来创建该文件。 If a Web.config doesn't exist, create it by selecting + > New File .

  3. 选择“Web.config”旁边的铅笔图标对其进行编辑。 Select the pencil for Web.config to edit it. 添加以下配置代码,然后单击“保存”。 Add the following configuration code and click Save . 如果 Web.config 已存在,则只需在其中添加包含任何内容的 <authorization> 元素即可。If Web.config already exists, just add the <authorization> element with everything in it. <allow> 元素中添加要允许的帐户。Add the accounts you want to allow in the <allow> element.

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
       <system.web>
          <authorization>
            <allow users="user1@contoso.com,user2@contoso.com"/>
            <deny users="*"/>
          </authorization>
       </system.web>
    </configuration>
    

应用程序级别Application level

如果其他任何级别不提供所需的授权,或者平台或标识提供者不受支持,则必须编写自定义代码,以基于用户声明为用户授权。If either of the other levels don't provide the authorization you need, or if your platform or identity provider isn't supported, you must write custom code to authorize users based on the user claims.

使用文件进行配置(预览) Configure using a file (preview)

可以选择通过部署提供的文件来配置身份验证设置。Your auth settings can optionally be configured via a file that is provided by your deployment. 应用服务身份验证/授权的某些预览功能可能要求此操作。This may be required by certain preview capabilities of App Service Authentication / Authorization.

重要

请记住,应用的有效负载(并由此该文件)可能随在环境之间移动。Remember that your app payload, and therefore this file, may move between environments, as with slots. 可能需要将不同的应用注册固定到每个槽,在这些情况下,应继续使用标准配置方法,而非配置文件。It is likely you would want a different app registration pinned to each slot, and in these cases, you should continue to use the standard configuration method instead of using the configuration file.

启用基于文件的配置Enabling file-based configuration

注意

预览期间,启用基于文件的配置会禁止通过某些客户端(例如 Azure 门户、Azure CLI 和 Azure PowerShell)管理应用程序的应用服务身份验证/授权功能。During preview, enabling file-based configuration will disable management of the App Service Authentication / Authorization feature for your application through some clients, such as the Azure portal, Azure CLI, and Azure PowerShell.

  1. 在项目根目录(部署到 Web/函数应用中的 D:\home\site\wwwroot)为配置创建新的 JSON 文件。Create a new JSON file for your configuration at the root of your project (deployed to D:\home\site\wwwroot in your web / function app). 根据基于文件的配置引用填写所需的配置。Fill in your desired configuration according to the file-based configuration reference. 如果修改现有 Azure 资源管理器配置,确保将 authsettings 集合中捕获的属性转换为配置文件。If modifying an existing Azure Resource Manager configuration, make sure to translate the properties captured in the authsettings collection into your configuration file.

  2. 修改现有配置,它在 Microsoft.Web/sites/<siteName>/config/authsettings 下的 Azure 资源管理器 API 中捕获。Modify the existing configuration, which is captured in the Azure Resource Manager APIs under Microsoft.Web/sites/<siteName>/config/authsettings. 若要修改它,可以使用 Azure 资源管理器模板To modify this, you can use an Azure Resource Manager template. 在 authsettings 集合中,需要设置三个属性(并可能删除其他属性):Within the authsettings collection, you will need to set three properties (and may remove others):

    1. enabled 设为 trueSet enabled to "true"
    2. isAuthFromFile 设为 trueSet isAuthFromFile to "true"
    3. authFilePath 设为文件的名称(例如 auth.json)Set authFilePath to the name of the file (for example, "auth.json")

备注

authFilePath 的格式在平台之间有所不同。The format for authFilePath varies between platforms. 在 Windows 上,支持相对路径和绝对路径。On Windows, both relative and absolute paths are supported. 建议使用相对路径。Relative is recommended. 对于 Linux,当前仅支持绝对路径,因此设置的值应为“/home/site/wwwroot/auth.json”或类似。For Linux, only absolute paths are supported currently, so the value of the setting should be "/home/site/wwwroot/auth.json" or similar.

完成此配置更新后,该文件的内容将用于定义该站点的应用服务身份验证/授权行为。Once you have made this configuration update, the contents of the file will be used to define the behavior of App Service Authentication / Authorization for that site. 如果希望回到 Azure 资源管理器配置,可以将 isAuthFromFile 设置回 false。If you ever wish to return to Azure Resource Manager configuration, you can do so by setting isAuthFromFile back to "false".

配置文件引用Configuration file reference

从配置文件引用的任何机密都必须存储为应用程序设置Any secrets that will be referenced from your configuration file must be stored as application settings. 可以将设置命名为任何所需名称。You may name the settings anything you wish. 只需确保配置文件中的引用使用相同的键。Just make sure that the references from the configuration file uses the same keys.

以下详尽无遗地介绍文件中的可能配置选项:The following exhausts possible configuration options within the file:

{
    "platform": {
        "enabled": <true|false>
    },
    "globalValidation": {
        "requireAuthentication": <true|false>,
        "unauthenticatedClientAction": "RedirectToLoginPage|AllowAnonymous|Return401|Return403",
        "redirectToProvider": "<default provider alias>",
        "excludedPaths": [
            "/path1",
            "/path2"
        ]
    },
    "httpSettings": {
        "requireHttps": <true|false>,
        "routes": {
            "apiPrefix": "<api prefix>"
        },
        "forwardProxy": {
            "convention": "NoProxy|Standard|Custom",
            "customHostHeaderName": "<host header value>",
            "customProtoHeaderName": "<proto header value>"
        }
    },
    "login": {
        "routes": {
            "logoutEndpoint": "<logout endpoint>"
        },
        "tokenStore": {
            "enabled": <true|false>,
            "tokenRefreshExtensionHours": "<double>",
            "fileSystem": {
                "directory": "<directory to store the tokens in if using a file system token store (default)>"
            },
            "azureBlobStorage": {
                "sasUrlSettingName": "<app setting name containing the sas url for the Azure Blob Storage if opting to use that for a token store>"
            }
        },
        "preserveUrlFragmentsForLogins": <true|false>,
        "allowedExternalRedirectUri": [
            "https://uri1.chinacloudsites.cn/",
            "https://uri2.chinacloudsites.cn/",
            "url_scheme_of_your_app://easyauth.callback"
        ],
        "cookieExpiration": {
            "convention": "FixedTime|IdentityProviderDerived",
            "timeToExpiration": "<timespan>"
        },
        "nonce": {
            "validateNonce": <true|false>,
            "nonceExpirationInterval": "<timespan>"
        }
    },
    "identityProviders": {
        "azureActiveDirectory": {
            "enabled": <true|false>,
            "registration": {
                "openIdIssuer": "<issuer url>",
                "clientId": "<app id>",
                "clientSecretSettingName": "APP_SETTING_CONTAINING_AAD_SECRET",
            },
            "login": {
                "loginParameters": [
                    "paramName1=value1",
                    "paramName2=value2"
                ]
            },
            "validation": {
                "allowedAudiences": [
                    "audience1",
                    "audience2"
                ]
            }
        },
        "facebook": {
            "enabled": <true|false>,
            "registration": {
                "appId": "<app id>",
                "appSecretSettingName": "APP_SETTING_CONTAINING_FACEBOOK_SECRET"
            },
            "graphApiVersion": "v3.3",
            "login": {
                "scopes": [
                    "profile",
                    "email"
                ]
            },
        },
        "gitHub": {
            "enabled": <true|false>,
            "registration": {
                "clientId": "<client id>",
                "clientSecretSettingName": "APP_SETTING_CONTAINING_GITHUB_SECRET"
            },
            "login": {
                "scopes": [
                    "profile",
                    "email"
                ]
            }
        },
        "google": {
            "enabled": true,
            "registration": {
                "clientId": "<client id>",
                "clientSecretSettingName": "APP_SETTING_CONTAINING_GOOGLE_SECRET"
            },
            "login": {
                "scopes": [
                    "profile",
                    "email"
                ]
            },
            "validation": {
                "allowedAudiences": [
                    "audience1",
                    "audience2"
                ]
            }
        },
        "twitter": {
            "enabled": <true|false>,
            "registration": {
                "consumerKey": "<consumer key>",
                "consumerSecretSettingName": "APP_SETTING_CONTAINING TWITTER_CONSUMER_SECRET"
            }
        },
        "openIdConnectProviders": {
            "<providerName>": {
                "enabled": <true|false>,
                "registration": {
                    "clientId": "<client id>",
                    "clientCredential": {
                        "secretSettingName": "<name of app setting containing client secret>"
                    },
                    "openIdConnectConfiguration": {
                        "authorizationEndpoint": "<url specifying authorization endpoint>",
                        "tokenEndpoint": "<url specifying token endpoint>",
                        "issuer": "<url specifying issuer>",
                        "certificationUri": "<url specifying jwks endpoint>",
                        "wellKnownOpenIdConfiguration": "<url specifying .well-known/open-id-configuration endpoint - if this property is set, the other properties of this object are ignored, and authorizationEndpoint, tokenEndpoint, issuer, and certificationUri are set to the corresponding values listed at this endpoint>"
                    }
                },
                "login": {
                    "nameClaimType": "<name of claim containing name>",
                    "scope": [
                        "openid",
                        "profile",
                        "email"
                    ],
                    "loginParameterNames": [
                        "paramName1=value1",
                        "paramName2=value2"
                    ],
                }
            },
            //...
        }
    }
}

将应用固定到特定身份验证运行时版本Pin your app to a specific authentication runtime version

启用身份验证/授权时,会将平台中间件注入 HTTP 请求管道,如功能概述中所述。When you enable Authentication / Authorization, platform middleware is injected into your HTTP request pipeline as described in the feature overview. 作为平台例常更新的一部分,此平台中间件定期更新新功能和改进。This platform middleware is periodically updated with new features and improvements as part of routine platform updates. 默认情况下,Web 或函数应用在此平台中间件的最新版本上运行。By default, your web or function app will run on the latest version of this platform middleware. 这些自动更新始终向后兼容。These automatic updates are always backwards compatible. 但在极少情况下此自动更新引入 Web 或函数应用的运行时问题,此时可以暂时回滚到以前的中间件版本。However, in the rare event that this automatic update introduces a runtime issue for your web or function app, you can temporarily roll back to the previous middleware version. 本文介绍如何将应用临时固定到特定版本的身份验证中间件。This article explains how to temporarily pin an app to a specific version of the authentication middleware.

自动和手动版本更新Automatic and manual version updates

可以通过设置应用的 runtimeVersion 设置,将应用固定到平台中间件的特定版本。You can pin your app to a specific version of the platform middleware by setting a runtimeVersion setting for the app. 应用始终在最新版本上运行,除非选择将其显式固定回特定版本。Your app always runs on the latest version unless you choose to explicitly pin it back to a specific version. 一次支持几个版本。There will be a few versions supported at a time. 如果固定到不再受支持的无效版本,应用将改用最新版本。If you pin to an invalid version that is no longer supported, your app will use the latest version instead. 若要始终运行最新版本,将 runtimeVersion 设为 ~1。To always run the latest version, set runtimeVersion to ~1.

查看和更新当前运行时版本View and update the current runtime version

可以更改应用使用的运行时版本。You can change the runtime version used by your app. 新的运行时版本应在重启应用后生效。The new runtime version should take effect after restarting the app.

查看当前运行时版本View the current runtime version

可以使用 Azure CLI 或应用中其中一个内置版本 HTTP 终结点来查看平台身份验证中间件的当前版本。You can view the current version of the platform authentication middleware either using the Azure CLI or via one of the built0-in version HTTP endpoints in your app.

通过 Azure CLIFrom the Azure CLI

使用 Azure CLI 通过 az webapp auth show 命令查看当前中间件版本。Using the Azure CLI, view the current middleware version with the az webapp auth show command.

az webapp auth show --name <my_app_name> \
--resource-group <my_resource_group>

在此代码中,用应用名称替换 <my_app_name>In this code, replace <my_app_name> with the name of your app. 还使用应用的资源组名称替换 <my_resource_group>Also replace <my_resource_group> with the name of the resource group for your app.

将在 CLI 输出中看到 runtimeVersion 字段。You will see the runtimeVersion field in the CLI output. 它类似于以下示例输出,为了清晰起见,该输出已被截断:It will resemble the following example output, which has been truncated for clarity:

{
  "additionalLoginParams": null,
  "allowedAudiences": null,
    ...
  "runtimeVersion": "1.3.2",
    ...
}
使用版本终结点From the version endpoint

还可点击应用上的 /.auth/version 终结点来查看应用运行所在的当前中间件版本。You can also hit /.auth/version endpoint on an app also to view the current middleware version that the app is running on. 它类似于以下示例输出:It will resemble the following example output:

{
"version": "1.3.2"
}

更新当前运行时版本Update the current runtime version

使用 Azure CLI,可以通过 az webapp auth update 命令更新应用中的 runtimeVersion 设置。Using the Azure CLI, you can update the runtimeVersion setting in the app with the az webapp auth update command.

az webapp auth update --name <my_app_name> \
--resource-group <my_resource_group> \
--runtime-version <version>

<my_app_name> 替换为你的应用的名称。Replace <my_app_name> with the name of your app. 还使用应用的资源组名称替换 <my_resource_group>Also replace <my_resource_group> with the name of the resource group for your app. 另外,将 <version> 替换为 1.x 运行时的有效版本,或替换为 ~1 获取最新版本。Also, replace <version> with a valid version of the 1.x runtime or ~1 for the latest version. 可以在 [此处] (https://github.com/Azure/app-service-announcements) 查找不同运行时版本的发行说明来帮助确定要固定到哪个版本。You can find the release notes on the different runtime versions [here] (https://github.com/Azure/app-service-announcements) to help determine the version to pin to.

可以在执行 az login 登录后从 Azure CLI 在本地运行此命令以执行此命令。You can run this command from the Azure CLI locally to execute this command after executing az login to sign in.