2

嗨,我从这里的示例开始

https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi

并设法让 TaskWebApp 与 TaskService 对话。

我现在想扩展解决方案以提供第 3 项服务

我不确定问题是否在 ConfidentialClientApplication 中,因为当它无法获取我的令牌时,我也没有例外。

我认为问题是我的 TaskWebApp 中的 CConfigureApp 方法只期望管理来自单个 TokenService 的令牌。

这是我的 web App Starttup.Auth ConfigureAuth 方法,这与示例应用程序没有变化

 public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                // Generate the metadata address using the tenant and policy information
                MetadataAddress = String.Format(AadInstance, Tenant, DefaultPolicy),

                // These are standard OpenID Connect parameters, with values pulled from web.config
                ClientId = ClientId,
                RedirectUri = RedirectUri,
                PostLogoutRedirectUri = RedirectUri,

                // Specify the callbacks for each type of notifications
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                    AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    AuthenticationFailed = OnAuthenticationFailed,
                },

                // Specify the claims to validate
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name"
                },

                // Specify the scope by appending all of the scopes requested into one string (seperated by a blank space)
                Scope = $"{OpenIdConnectScopes.OpenId} {ReadTasksScope} {WriteTasksScope}"
            }
        );
    }

这是我的 OnAuthorizationCodeReceived 方法,再次保持不变

 private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
    {
        // Extract the code from the response notification
        var code = notification.Code;

        var userObjectId = notification.AuthenticationTicket.Identity.FindFirst(ObjectIdElement).Value;
        var authority = String.Format(
                            AadInstance, 
                            Tenant, 
                            DefaultPolicy);
        var httpContext = notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase;

        // Exchange the code for a token. Make sure to specify the necessary scopes
        ClientCredential cred = new ClientCredential(ClientSecret);
        ConfidentialClientApplication app = new ConfidentialClientApplication(
                                            authority, 
                                            Startup.ClientId,
                                            RedirectUri, 
                                            cred, 
                                            new NaiveSessionCache(userObjectId, httpContext));

        var authResult = await app.AcquireTokenByAuthorizationCodeAsync(new string[]
        {
            ReadTasksScope,
            WriteTasksScope
        }, 
        code, 
        DefaultPolicy);



    }

问题似乎是我的读写范围直接引用了TaskService,当我尝试从其他应用程序请求适当的范围时它会抱怨。

在我的控制器中

    private async Task<String> acquireToken(String[] scope)
    {

        try
        {
            string userObjectID = ClaimsPrincipal.Current.FindFirst(Startup.ObjectIdElement).Value;
            string authority = String.Format(Startup.AadInstance, Startup.Tenant, Startup.DefaultPolicy);

            ClientCredential credential = new ClientCredential(Startup.ClientSecret);

            // Retrieve the token using the provided scopes
            ConfidentialClientApplication app = new ConfidentialClientApplication(authority, Startup.ClientId,
                Startup.RedirectUri, credential,
                new NaiveSessionCache(userObjectID, this.HttpContext));

            AuthenticationResult result = await app.AcquireTokenSilentAsync(scope);

            return result.Token;
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.Message);
            throw e;
        }

使用了此方法,但我的 AuthorisationResult 失败,消息无法静默获取令牌,没有内部异常。

到目前为止,我已尝试将 NaiveSessionCache 作为其可选内容删除,但仍然失败

为了克服这个问题,我注册了第 4 个服务,然后让我的 webapis 使用该单个客户端 ID 和密码来控制对其资源的访问,但这感觉这不是正确的前进方式。

任何帮助都会非常感谢

4

0 回答 0