如何从startup.cs

问题描述

我正在尝试升级正在使用Microsoft.Identity.Web nuget包的项目之一。到目前为止,确实工作得很好,但是我很难确定如何添加以前通过以下方式进行的其他声明:

        services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme,options =>
        {
            options.Events.OnAuthorizationCodeReceived = async ctx =>
            {
                var serviceProvider = services.BuildServiceProvider();
                var distributedCache = serviceProvider.GetrequiredService<IdistributedCache>();

                var identifier = ctx.Principal.FindFirst(ObjectIdentifierType)?.Value;

                var cca = ConfidentialClientApplicationBuilder.CreateWithApplicationoptions(new ConfidentialClientApplicationoptions()
                {
                    ClientId = "ClientId",RedirectUri = "RedirectUri",ClientSecret = "ClientSecret"
                })
                .WithAuthority(ctx.Options.Authority)
                .Build();

                var tokenCache = new SessionTokenCache(identifier,distributedCache);
                tokenCache.Initialize(cca.UserTokenCache);
                var token = await cca.AcquiretokenByAuthorizationCode(scopes,ctx.TokenEndpointRequest.Code).ExecuteAsync();

                ctx.HandleCodeRedemption(token.Accesstoken,token.IdToken);

                // get the claims
                var claimservice = serviceProvider.GetrequiredService<Claimservice>();
                var response = await apiclient.GetUserAdditionalClaimsAsync(token.Accesstoken);
                
                // add the claims
            };

现在,当我尝试使用ITokenAcquisition.GetAccesstokenForUserAsync()方法而不是使用ConfidentialClientApplicationBuilder

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftWebApp(options =>
    {
        Configuration.Bind("AzureAD",options);
        options.Events.OnAuthorizationCodeReceived = async ctx =>
        {
            var serviceProvider = services.BuildServiceProvider();
            var tokenAcquisition = serviceProvider.GetrequiredService<ITokenAcquisition>();


            var token = await tokenAcquisition.GetAccesstokenForUserAsync("scopes");

            // get the claims
            var claimservice = serviceProvider.GetrequiredService<Claimservice>();
            var response = await apiclient.GetUserAdditionalClaimsAsync(token);

            // add the claims
        };
    })
    .AddMicrosoftWebAppCallsWebApi(Configuration,new[] { "scopes" })
    .AdddistributedTokenCaches();

对于如何最好地解决此问题,我们将不胜感激。 谢谢!

我收到以下错误

enter image description here

解决方法

使用ConfidentialClientApplicationBuilder时使用client credentials flow。我不知道您为什么使用ITokenAcquisition.GetAccessTokenForUserAsync()代替。

您可以使用下面的code sample进行客户端凭据流程:

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

app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
        .WithTenantId("{tenantID}")
        .WithClientSecret(config.ClientSecret)
        .Build();

// 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
}