如何使用 Azure AD 授权代码流?

发布于 2025-01-12 22:39:52 字数 3644 浏览 1 评论 0原文

我正在构建一个 ASP.NET (v4.8) Web 应用程序,该应用程序将作为 Azure 应用服务托管,但目前我们位于本地主机上。

我已成功配置 Azure AD,并且收到授权代码,因为我将应用服务配置为发送访问令牌。应用程序注册仅具有User.Read(委派)权限。

应用程序注册设置 - 访问令牌

在我的 Startup.cs 文件中,我配置了 OpenIdConnectAuthenticationNotifications,以便接收访问代码已收到授权代码。这是代码:

public void ConfigureAuth(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType( CookieAuthenticationDefaults.AuthenticationType );
    app.UseCookieAuthentication(new CookieAuthenticationOptions());
        authority = aadInstance + tenantId;
        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions  {
            ClientId = clientId, Authority = authority,
            PostLogoutRedirectUri = postLogoutRedirectUri,
            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                TokenResponseReceived = (tr) => { return Task.FromResult(0); }, 
                AuthorizationCodeReceived = (code) => {
                    // you are here! what's next?
                    access_code = code.Code;
                    return Task.FromResult(0);
                },
                SecurityTokenReceived = (token) => 
                {
                    return Task.FromResult(0);
                },
                AuthenticationFailed = (context) => { return System.Threading.Tasks.Task.FromResult(0); }
            }
        });
        app.UseStageMarker(PipelineStage.Authenticate);
    }

我的目标是作为当前用户调用此图形端点来获取他们的 JobTitle 和 >来自 Azure AD 的部门。这是资源:https://graph.microsoft.com/v1.0/me

我正在关注这个文档,但尚不清楚如何处理提供的 access_code。请帮助我理解。

  1. 这是 access_code 不记名令牌吗?我可以直接使用它来调用图形API吗?
  2. 我是否必须使用它来调用 /token 端点才能获取不记名令牌?
  3. 我是否必须使用它来调用 /authorize 端点才能获取不记名令牌?
  4. 我现在正在发出直接 HTTP 请求,我应该使用 MSAL 还是 Graph SDK?

我想我正在尝试完成这一步:

在此处输入图像描述

这是我当前正在处理的代码,它返回 HTTP CODE 400(错误请求):

private void GetOtherProfileData()
{
    var cId = Startup.clientId;
    var tenantId = Startup.tenantId;
    var scope = Startup.scope;
    // scope: https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
    var code = Startup.access_code;
    var redir = HttpUtility.UrlEncode(Startup.redirectUri);
    var req_url = $@"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token?client_id={cId}&scope={scope}
                        &code={code}&redirect_uri={redir}&grant_type=authorization_code
                        &code_verifier=ThisIsntRandomButItNeedsToBe43CharactersLong";
    var req = WebRequest.CreateHttp(req_url);
    req.Method = "POST";
    req.ContentLength = 0;
    req.ContentType = "application/x-www-form-urlencoded";
    var resp = req.GetResponse();
    var str = resp.GetResponseStream();
    var json = new StreamReader(str).ReadToEnd();
    Trace.TraceInformation(json);
    /// this should return bearer token and then we go call the /me endpoint... 
///right?
}

任何代码示例或指向最近的文档会有所帮助。

I am building an ASP.NET (v4.8) Web application that will be hosted as an Azure App Service, but for now we are on localhost.

I am configured for Azure AD successfully and I am receiving an authorization code because I configured my app service to send the access token. The app registration has ONLY User.Read (delegated) permissions.

App Registration Settings - Access Tokens

In my Startup.cs file, I've configured OpenIdConnectAuthenticationNotifications so that I am receiving the access code in AuthorizationCodeReceived. Here is the code:

public void ConfigureAuth(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType( CookieAuthenticationDefaults.AuthenticationType );
    app.UseCookieAuthentication(new CookieAuthenticationOptions());
        authority = aadInstance + tenantId;
        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions  {
            ClientId = clientId, Authority = authority,
            PostLogoutRedirectUri = postLogoutRedirectUri,
            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                TokenResponseReceived = (tr) => { return Task.FromResult(0); }, 
                AuthorizationCodeReceived = (code) => {
                    // you are here! what's next?
                    access_code = code.Code;
                    return Task.FromResult(0);
                },
                SecurityTokenReceived = (token) => 
                {
                    return Task.FromResult(0);
                },
                AuthenticationFailed = (context) => { return System.Threading.Tasks.Task.FromResult(0); }
            }
        });
        app.UseStageMarker(PipelineStage.Authenticate);
    }

My objective is to call this graph endpoint as the current user to get their JobTitle and > Department from Azure AD. Here is the resource: https://graph.microsoft.com/v1.0/me

I was following this documentation, but it was not clear what to do with the provided access_code. Please help me understand.

  1. Is this access_code a bearer token? can I use it directly to call the graph API?
  2. Do I have to use it to call the /token endpoint to get a bearer token?
  3. Do I have to use it to call the /authorize endpoint to get a bearer token?
  4. I am making direct HTTP requests now, should I use MSAL or Graph SDK?

I think I am trying to accomplish this step:

enter image description here

This is the code I am currently working on, and it returns HTTP CODE 400 (Bad Request):

private void GetOtherProfileData()
{
    var cId = Startup.clientId;
    var tenantId = Startup.tenantId;
    var scope = Startup.scope;
    // scope: https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
    var code = Startup.access_code;
    var redir = HttpUtility.UrlEncode(Startup.redirectUri);
    var req_url = $@"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token?client_id={cId}&scope={scope}
                        &code={code}&redirect_uri={redir}&grant_type=authorization_code
                        &code_verifier=ThisIsntRandomButItNeedsToBe43CharactersLong";
    var req = WebRequest.CreateHttp(req_url);
    req.Method = "POST";
    req.ContentLength = 0;
    req.ContentType = "application/x-www-form-urlencoded";
    var resp = req.GetResponse();
    var str = resp.GetResponseStream();
    var json = new StreamReader(str).ReadToEnd();
    Trace.TraceInformation(json);
    /// this should return bearer token and then we go call the /me endpoint... 
///right?
}

Any code samples or pointers to recent documentation would be helpful.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝海似她心 2025-01-19 22:39:52

这个 access_code 是不记名令牌吗?我可以直接使用它来调用图形API吗?

<块引用>

不,code 和 Access_token 不同。您将需要一个access_token来调用Graph API。

我是否必须使用它来调用 /token 端点才能获取不记名令牌?

<块引用>

是的,您需要代码来调用令牌端点以获取不记名令牌。

我是否必须使用它来调用 /authorize 端点才能获取不记名令牌?

<块引用>

调用授权端点后您将获得代码。您需要传递 grant_type=code 才能获取响应代码。

我现在正在发出直接 HTTP 请求,我应该使用 MSAL 还是 Graph SDK?

<块引用>

获得access_token后,您需要调用Graph API。除了令牌之外,它还需要来自 Azure 端的适当的专用和应用程序用户权限。

Is this access_code a bearer token? can I use it directly to call the graph API?

No, code and Access_token are different. You will need a access_token to call Graph API.

Do I have to use it to call the /token endpoint to get a bearer token?

Yes, you'll need code to call token endpoint to get the bearer token.

Do I have to use it to call the /authorize endpoint to get a bearer token?

You will get the code after calling authorize endpoint. You need to pass grant_type=code to get the code in response.

I am making direct HTTP requests now, should I use MSAL or Graph SDK?

You'll need to call Graph API after you get the access_token. Along with the token it also needs proper dedicated and application User permissions from Azure side.

太阳公公是暖光 2025-01-19 22:39:52

我在这里找到了一个很好的示例: https://github.com/Azure -Samples/ms-identity-aspnet-webapp-openidconnect

我试图在没有客户端密码的情况下执行此操作,这是一个错误。

这就是我实现它的方式=>

AuthorizationCodeReceived = async (context) => {
    // you are here!
    IConfidentialClientApplication clientApp = MsalAppBuilder.BuildConfidentialClientApplication();
    AuthenticationResult result = await clientApp.AcquireTokenByAuthorizationCode(new[] { "User.Read" }, context.Code)
                        .WithSpaAuthorizationCode() //Request an authcode for the front end
                        .ExecuteAsync();
                    access_code = result.AccessToken;
                    // this is the bearer token.
                },

这是 BuildConfidentialClientApplication 的实现内部的内容:

clientapp = ConfidentialClientApplicationBuilder.Create(Startup.clientId)
            .WithClientSecret(Startup.secret)
            .WithRedirectUri(Startup.redirectUri)
            .WithAuthority(new Uri(Startup.authority))
            .Build();

I found a good sample here: https://github.com/Azure-Samples/ms-identity-aspnet-webapp-openidconnect

I was trying to do this without a client secret, that was a mistake.

This is how I implemented it =>

AuthorizationCodeReceived = async (context) => {
    // you are here!
    IConfidentialClientApplication clientApp = MsalAppBuilder.BuildConfidentialClientApplication();
    AuthenticationResult result = await clientApp.AcquireTokenByAuthorizationCode(new[] { "User.Read" }, context.Code)
                        .WithSpaAuthorizationCode() //Request an authcode for the front end
                        .ExecuteAsync();
                    access_code = result.AccessToken;
                    // this is the bearer token.
                },

This is what is inside the implementation of BuildConfidentialClientApplication:

clientapp = ConfidentialClientApplicationBuilder.Create(Startup.clientId)
            .WithClientSecret(Startup.secret)
            .WithRedirectUri(Startup.redirectUri)
            .WithAuthority(new Uri(Startup.authority))
            .Build();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文