簡體   English   中英

使用OAuth2對Azure AD進行身份驗證以調用WebAPI

[英]Use OAuth2 for authentication against Azure AD to call WebAPI

我正在嘗試創建一個將在AWS中托管的新Web應用程序。 此應用程序需要通過OAuth2從我們的Azure Active Directory中對用戶進行身份驗證。 到目前為止,這是我一直在努力的工作,以及我到那之前常用的步驟:

1)用戶從“ login.microsoftonline.com”登錄后,我可以生成一個“代碼”。 為此,我在Azure AD中設置了一個新應用程序,該應用程序將我的Web應用程序引導用戶登錄到該應用程序。我還在Azure AD中設置了API應用程序,我將其用作查詢字符串中的“資源”參數當我將用戶定向到login.microsoftonline.com端點時

2)使用上面#1生成的“代碼”,我可以通過調用應用程序的/ token端點來生成授權令牌。 我可以通過傳遞相同的資源值(我最終想要使用的API的URL),代碼,我的客戶端ID和我的客戶端密碼來做到這一點

3)來自上面#2的令牌響應向下發送token_type,expires_in,scope,access_token,refresh_token和id_token屬性,所有這些屬性都具有值。 我能夠將id_token解碼為JWT,並且它在Claims對象中顯示了已登錄用戶的正確用戶信息。

4)在這里,我卡住了 ,然后嘗試使用我在上述#3中獲得的access_token調用也在Azure AD中注冊的API應用程序,並將該值傳遞到“授權”標頭中,並將該值設置為“ Bearer” xyz123 ......“如果不對API應用程序進行任何授權,則會得到預期的結果,但是,如果我在類甚至Get()方法上放置了[Authorize]屬性,我總是得到401(未經授權)。 我確定還有其他需要連接的東西,只是不確定。 我找到了以下資源: https : //docs.microsoft.com/zh-cn/azure/api-management/api-management-howto-protect-backend-with-aad,但是它談到了使用api管理和API注冊我的API認為我不需要這樣做(如果不需要的話,我當然也不想這樣做)。

我正在創建的api將取決於能否獲得登錄用戶的身份,我假設我可以從承載令牌中提取身份,我只是不知道如何...

任何幫助和指導將不勝感激。

編輯以包括有效的解決方案:這是根據下面可接受的答案在啟動類中使用的方法。 請注意,“受眾群體”值是我要訪問的API端點的URL。 承租人是我們在組織中綁定的自定義URL,如果您不提供有效的承租人值,則可能會收到一個異常,內容為“響應狀態代碼未指示成功:404(未找到)”。 您將需要可以從Nuget獲得的Azure Active Directory程序集: Install-Package Microsoft.Owin.Security.ActiveDirectory

public partial class Startup
{
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {

        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Audience = "https://myapi.azurewebsites.net/",
                Tenant = "my.custom.url.com",
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = false
                }
            });
    }
}

這是我用來從需要訪問權限以接收我的令牌的應用程序發出請求的發布參數。

        body.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
        body.Add(new KeyValuePair<string, string>("code", code)); // code from response
        body.Add(new KeyValuePair<string, string>("redirect_uri", "http://localhost:51015/redirect"));
        body.Add(new KeyValuePair<string, string>("client_id", "xxxxxxx-8829-4294-b2c9-xxxxxxxxxx")); // client id of this application making the request
        body.Add(new KeyValuePair<string, string>("client_secret", "PxxxxxxxxxxxxSnTJ4Uh63Voj+tkxxxxxxx="));
        body.Add(new KeyValuePair<string, string>("resource", "https://myapi.azurewebsites.net/")); // same value goes here that is in the audience value of the api, this is also the same value that is passed in the resource parameter of the query string on the redirect to the login to obtain the "code" in the previous step

這取決於您如何保護Web API。 通常,我們可以使用以下代碼使用Azure AD保護Web API:

public partial class Startup
{
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {

        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Audience = ConfigurationManager.AppSettings["ida:Audience"],
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                 TokenValidationParameters= new System.IdentityModel.Tokens.TokenValidationParameters {
                     ValidateIssuer=false
                 }
            });
    }
}

目標對象是您在Azure門戶上注冊的應用程序的ClientId 在這種情況下,我們將此應用程序既用作客戶端又用作資源。 然后,我們可以像下面的請求一樣請求訪問令牌:

POST: https://login.microsoftonline.com/{tenantId}/oauth2/token
resource={clientId}&client_id={clientId}&code={authorizationCode}&grant_type=authorization_code&redirect_uri={redirectUri}&client_secret={clientSecret}

該令牌應可用於受以上代碼保護的Web API的授權。 有關保護Web API的更多詳細信息,您可以在此處參考。

請在Fiddler中檢查與身份驗證失敗有關的任何其他詳細信息,其中可能包含諸如“ Invalid Audience”之類的詳細信息。您需要知道失敗的根本原因(401錯誤)才能解決此問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM