简体   繁体   English

如何在没有用户登录的情况下检索 .NET Core Web API 的 MS Graph 访问令牌

[英]How to retrieve an MS Graph access token for a .NET Core Web API without user sign in

UPDATE (solution): I ended up simply extracting the token from the request that my frontend is sending with:更新(解决方案):我最终只是从我的前端发送的请求中提取了令牌:

private async Task<string> GetApplicationAccessToken()
        {
            var token = this.Request
                            .Headers["Authorization"]
                            .First()
                            .Substring("Bearer ".Length);
            var assertion = new UserAssertion(token, _ASSERTION_TYPE);

            var authResult= await this._app.AcquireTokenOnBehalfOf(new []{""}, assertion)
                                       .ExecuteAsync();

            return authResult.AccessToken;
        }

ORIGINAL:原版的:

I want to funnel data from the MS Graph API (Azure AD endpoint) through my backend (.NET Core Web API) back to my Angular App, that requests the data.我想通过我的后端(.NET Core Web API)将来自 MS Graph API(Azure AD 端点)的数据汇集回请求数据的我的 Angular 应用程序。 I am running into the problem that I am unable to get an Access token in my backend Web API.我遇到了无法在后端 Web API 中获取访问令牌的问题。

I have Implemented a graph service according to this sample where user consent is prompted through a static html page that is being hosted on the web API. But I want to access MS Graph without explicit user consent.我已经根据此示例实施了图形服务,其中通过托管在 web API 上的 static html 页面提示用户同意。但我想在未经用户明确同意的情况下访问 MS Graph。

I have looked for ways to get an access token for my web API without user consent, but not found anything helpful.我一直在寻找未经用户同意为我的 web API 获取访问令牌的方法,但没有找到任何有用的信息。 Only stuff that confuses me.只有让我困惑的东西。 I have also supplied the App registration in Azure AD with application permissions and supplied my web API with sufficient information to the Azure app.我还向 Azure AD 中的应用程序注册提供了应用程序权限,并向我的 web API 提供了足够的信息给 Azure 应用程序。

I am still not sure how to exactly adapt the sample code to work with my scenario where user consent is not required / an token already present in the request that my Angular app makes to my web API.我仍然不确定如何准确调整示例代码以适用于不需要用户同意的场景/我的 Angular 应用程序向我的 web API 发出的请求中已经存在的令牌。

I am getting a userId (objectId.tenantId) in my GraphAuthProvider class when I am trying to call GetAccountAsync() .当我尝试调用GetAccountAsync()时,我在我的GraphAuthProvider class 中得到了一个 userId (objectId.tenantId)。 Yet I still don't receive a token from that call and don't get any error hints, just null.但是我仍然没有从该调用中收到令牌,也没有收到任何错误提示,只有 null。

public async Task<string> GetUserAccessTokenAsync(string userId)
        {
            var account = await _app.GetAccountAsync(userId);

            if (account == null)
            {
                throw new ServiceException(new Error
                {
                    Code    = "TokenNotFound",
                    Message = "User not found in token cache. Maybe the server was restarted."
                });
            }

My appsettings.json我的 appsettings.json

"AzureAd": {
    "CallbackPath": "/signin-oidc",
    "BaseUrl": "https://localhost:63208",
    "ClientId": "[redacted]",
    "TenantId": "[redacted]",
    "ClientSecret": "[redacted]", // This sample uses a password (secret) to authenticate. Production apps should use a certificate.
    "Scopes": "user.read profile",
    "GraphResourceId": "https://graph.microsoft.com/",
    "GraphScopes": "User.Read.All Groups.Read.All"
  }

Can you point me in the right direction as to how to call the MS Graph API from my backend by using the application permissions?关于如何使用应用程序权限从我的后端调用 MS Graph API,你能给我指出正确的方向吗?

Client credential flow using directly http post客户端凭证流直接使用http post

In you web api, you can directly create http request to authenticate using client credential flow and retire Microsoft Graph's access token:在您 web api 中,您可以直接创建 http 请求以使用客户端凭证流进行身份验证并停用 Microsoft Graph 的访问令牌:

POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

client_id=535fb089-9ff3-47b6-9bfb-4f1264799865
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret=qWgdYAmab0YSkuL1qKv5bPX
&grant_type=client_credentials

Before that, you'd better admin consent the app permissions, see the detail steps in this article .在此之前,您最好获得管理员同意应用程序权限,请参阅本文中的详细步骤。

Client credential flow using MSAL.NET使用 MSAL.NET 的客户端凭据流

If using the MSAL.NET, you can use below code sample for client credential flow:如果使用 MSAL.NET,您可以使用以下代码示例进行客户端凭据流:

// Even if this is a console application here, a daemon application is a confidential client application
IConfidentialClientApplication app;

#if !VariationWithCertificateCredentials
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
        .WithTenantId("{tenantID}")
        .WithClientSecret(config.ClientSecret)
        .Build();
#else
// Building the client credentials from a certificate
X509Certificate2 certificate = ReadCertificate(config.CertificateName);
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
    .WithTenantId("{tenantID}")
    .WithCertificate(certificate)
    .Build();
#endif

// With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the
// application permissions need to be set statically (in the portal or by PowerShell), and then granted by
// a tenant administrator
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(scopes)
                .ExecuteAsync();
}
catch(MsalServiceException ex)
{
// Case when ex.Message contains:
// AADSTS70011 Invalid scope. The scope has to be of the form "https://resourceUrl/.default"
// Mitigation: change the scope to be as expected
}

You can refer to this article and code sample on Github.您可以参考Github上的这篇文章代码示例

Client credential flow using Microsoft Graph .NET authentication library使用 Microsoft Graph .NET 身份验证库的客户端凭据流

From document: https://github.com/microsoftgraph/msgraph-sdk-do.net-auth来自文档: https://github.com/microsoftgraph/msgraph-sdk-do.net-auth

You can use Client credential provider:您可以使用客户端凭证提供程序:

// Create a client application.
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithTenantId(tenantID)
                .WithClientSecret(clientSecret)
                .Build();
// Create an authentication provider.
ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);
// Configure GraphServiceClient with provider.
GraphServiceClient graphServiceClient = new GraphServiceClient(authenticationProvider);

Or directly use MSAL.NET to authenticate using client credential flow and build the Microsoft Graph client like reply from @Philippe Signoret shows.或者直接使用 MSAL.NET 使用客户端凭据流进行身份验证并构建 Microsoft Graph 客户端,如@Philippe Signoret 的回复所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从中间件请求 MS Graph 访问令牌 - Request a MS Graph Access token from Middleware 尝试获取 MS Graph API 令牌时缺少用户的 ImmutableID(Windows 身份验证) - ImmutableID of the user missing when trying to acquire a token for MS Graph API (Windows auth) Stocktwits API - 无需用户交互即可从脚本获取访问令牌 - Stocktwits API - get access token from script without user interaction 使用 Java 从 AAD 访问 MS Graph 用户数据 - MS Graph User Data Access from AAD using Java 从 .NET 访问 DB Core Web API 部署为 Azure Web App - Access DB from .NET Core Web API deployed as Azure Web App Chrome 扩展程序如何从 Firebase web 应用程序获取用户凭据而无需用户登录两次? - How does Chrome Extension get user credential from Firebase web app without user having to sign in twice? 从 ASP.Net Core 调用 Microsoft Graph 时缺少必需的范围 Web Api - Missing Scopes Required when calling Microsoft Graph from ASP .Net Core Web Api 如何在没有企业应用程序客户端密钥的情况下刷新 Microsoft Graph API 的令牌? - How to refresh the token of Microsoft Graph API without Client Secret for an Enterprise App? id Token vs access_token google login web 中的 api - id Token vs access_token google login api in web 如何使用 oauth2 令牌在 MS Graph SDK 中进行身份验证? - How to authenticate in MS Graph SDK with oauth2 token?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM