Mar*_*ark 2 c# graph azure azure-active-directory blazor
我从 Blazor 服务器应用程序调用图形 API 时遇到一些问题。我按照https://learn.microsoft.com/en-us/azure/app-service/scenario-secure-app-access-microsoft-graph-as-user?tabs=azure-resource-explorer上的示例进行操作但我在尝试登录时收到以下错误:
MsalClientException:需要一种客户端凭据类型:创建机密客户端时必须定义 ClientSecret、Certificate、ClientAssertion 或 AppTokenProvider
我的代码如下:
appsettings.json
{
/*
The following identity settings need to be configured
before the project can be successfully executed.
For more info see https://aka.ms/dotnet-template-ms-identity-platform
*/
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "XXXXXXXXXXXXXXXXXXXXXXXXXX",
"TenantId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"ClientId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"CallbackPath": "/signin-oidc"
},
"Graph": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.read"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
}
program.cs
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { "user.read" })
.AddMicrosoftGraph(builder.Configuration.GetSection("Graph"))
.AddInMemoryTokenCaches();
SearchBase.cs
[AuthorizeForScopes(Scopes = new[] { "user.read" })]
public class SearchBase : ComponentBase
{
...
protected async override Task OnInitializedAsync()
{
try
{
_user = await _graphServiceClient.Me.Request().GetAsync();
}
catch (Exception ex)
{
_logger.LogDebug(ex.Message);
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
首次登录应用程序时会引发该错误。它看起来是由 program.cs 文件中的最后三行触发的:
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { "user.read" })
.AddMicrosoftGraph(builder.Configuration.GetSection("Graph"))
.AddInMemoryTokenCaches();
Run Code Online (Sandbox Code Playgroud)
如果我将它们注释掉,它会按预期通过 Azure AD 使我登录。然而,这会导致 SearchBase.cs 中的 Graph API 调用无法正常工作。
我对使用 Graph API 很陌生,希望有人以前遇到过这个。我通过谷歌找到的示例返回代码与我自己的非常相似,所以我不知道出了什么问题。
感谢您提供的任何帮助。
标记
MsalClientException:需要一种客户端凭据类型:创建机密客户端时必须定义 ClientSecret、Certificate、ClientAssertion 或 AppTokenProvider
如果调用 Microsoft Graph API 时缺少ClientSecret参数,通常会发生此错误。
要解决该错误,您需要在文件中包含应用服务生成的ClientSecret。appsettings.json
您可以获取ClientSecret值,如下所示:
转到 Azure 门户 -> 应用程序服务 -> 您的应用程序服务 -> 身份验证 -> 身份提供程序设置 -> 编辑

选择“单击以编辑秘密值”,如下所示:

复制您的客户端密钥的值,如下所示:

现在,appsettings.json通过包含复制的客户端密钥来更新您的客户端密钥,如下所示:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "XXXXXXXXXXXXXXXXXXXXXXXXXX",
"TenantId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"ClientId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"ClientSecret": "XXXXXXXXXXXXXXX",
"CallbackPath": "/signin-oidc"
},
"Graph": {
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.read"
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1525 次 |
| 最近记录: |