繁体   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