使用OAuth2对Azure AD进行身份验证以调用WebAPI [英] Use OAuth2 for authentication against Azure AD to call WebAPI

查看:134
本文介绍了使用OAuth2对Azure AD进行身份验证以调用WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个将在AWS中托管的新Web应用程序.此应用程序需要通过OAuth2从我们的Azure Active Directory中对用户进行身份验证.到目前为止,这是我一直在努力的工作,以及我到达那里所采取的步骤:

I am trying to create a new web application that will be hosted in AWS. This application needs to authenticate users from our Azure Active Directory via OAuth2. Here's what I have working so far and steps I used to get me there:

1)用户从"login.microsoftonline.com"登录后,我可以生成一个代码".为此,我在Azure AD中设置了一个新应用程序,该Web应用程序将用户引导至该应用程序以进行登录.我还在Azure AD中设置了API应用程序,该应用程序用作查询字符串中的"resource"参数.当我将用户定向到login.microsoftonline.com端点

1) I can generate a "code" after user logs in from "login.microsoftonline.com". To accomplish this, I set up a new application in Azure AD that my web application directs users to for logging in. I have also set up the API application in Azure AD which I'm using as the "resource" parameter in the query string when I direct users to the login.microsoftonline.com endpoint

2)使用上面#1生成的代码",我可以通过调用应用程序的/token端点来生成授权令牌.我可以通过传递相同的资源值(我最终要使用的API的URL),代码,我的客户ID和我的客户秘密来做到这一点

2) using the "code" generated from #1 above, I can generate my authorization token by calling the /token endpoint of my application. I'm able to do this by passing the same resource value (the url to my API that I ultimately want to use), the code, my client id, and my client secret

3)来自上面#2的令牌响应向下发送token_type,expires_in,scope,access_token,refresh_token和id_token属性,所有这些属性都具有值.我能够将id_token解码为JWT,并且可以在Claims对象中显示已登录用户的正确用户信息

3) the token response from #2 above sends down token_type, expires_in, scope, access_token, refresh_token, and id_token properties all of which have values. I'm able to decode the id_token into a JWT and it is showing the correct user information for the logged in user in the claims object

4)我在哪里卡住,然后我尝试使用我在上述#3中获得的access_token调用也已在Azure AD中注册的API应用程序,并将该值传递给该值是"Bearer xyz123 ......"的"Authorization"标头,如果我不对API应用程序进行任何授权,则可以得到期望的结果,但是,如果我放置了[Authorize]属性在类甚至是Get()方法上,我总是得到401(未经授权).我确定还有其他需要连接的东西,但不确定是什么.我找到了以下资源: https://docs.microsoft.com/zh-CN/azure/api-management/api-management-howto-protect-backend-with-aad ,但它谈到了使用api管理和我注册我的API认为我不需要这样做(如果不需要,我绝对不希望这样做).

4) HERE'S WHERE I'M STUCK I then try to make a call to my API application that is also registered in Azure AD using the access_token I obtain in #3 above passing that value in an "Authorization" header with that value being "Bearer xyz123......" If I don't put any authorization on the API application, I get results as I'd expect, if however, I put an [Authorize] attribute on the class or even the Get() method, I always get a 401 (unauthorized). I'm certain there's something else I need to wire up I'm just not sure what. I found this resource: https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-protect-backend-with-aad but it talks of registering my API with api management and I don't think I need to do that (I definitely don't want to if I don't have to).

我正在创建的api将取决于能否获得登录用户的身份,我假设我可以从承载令牌中提取身份,我只是不知道如何...

The api I'm creating will rely on being able to get the logged in user's identity which I'm assuming I can extract from the bearer token, I just don't know how...

任何帮助和指导将不胜感激.

any help and guidance will be greatly appreciated.

编辑以包含有效的解决方案: 这是我在启动课程中根据以下接受的答案使用的内容.请注意,受众群体"值是我要访问的API端点的URL.承租人是我们在组织中绑定的自定义URL,如果您不提供有效的承租人值,则可能会收到一个异常,指出响应状态代码不表示成功:404(未找到)".您需要可以从Nuget获得的Azure Active Directory程序集:Install-Package Microsoft.Owin.Security.ActiveDirectory

Edit to include working solution: Here is what i used in my startup class per the accepted answer below. Note the "audience" value is the URL of the API end point that I'm calling that I need access to. The Tenant is a custom url that we have bound in our organization, if you don't supply a valid tenant value, you might get an exception that says "Response status code does not indicate success: 404 (Not Found)." You'll need the Azure Active Directory assembly which you can get from Nuget: 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
                }
            });
    }
}

这是我用来从需要访问权限以接收我的令牌的应用程序发出请求的发布参数.

here are the post parameters I'm using to make the request from the application that needs access to receive my token.

        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:

It depends on how you protect the web API. Normally, we can protect the web API using Azure AD using the code below:

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 .在这种情况下,我们将此应用程序既用作客户端又用作资源.然后,我们可以像下面的请求一样请求访问令牌:

The Audience is the ClientId of app you register on the Azure portal. In this scenario, we use this app as both the client and resource. Then we canrequest the access token like request below:

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的更多详细信息,可以在此处参考.

This token should works for the authorization of web API which protect by the code above. More detail about protecting the web API, you can refer here.

这篇关于使用OAuth2对Azure AD进行身份验证以调用WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆