【问题标题】:How to authenticate web api in WPF app using Azure AD如何使用 Azure AD 在 WPF 应用程序中验证 Web api
【发布时间】:2021-03-21 22:29:44
【问题描述】:

我在我的 WPF 应用程序中使用此代码:

 var app = PublicClientApplicationBuilder.Create(_clientId)                                                
   .WithRedirectUri("http://localhost/")                                                  
   .WithAuthority(AzureCloudInstance.AzurePublic, _tenantId).Build();

 try
        {
            result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();

        }
        catch (MsalUiRequiredException)
        {
            return Result<UserMetadata>.NotAuthorized("There was on error");
        }

而且效果很好。现在我可以调用我的 WEB API 并将“Bearer token”标头发送到所有端点。 (令牌是我从结果中得到的 access_token 属性)

在 web api 中我只是这样做:

 _ = services.AddMicrosoftIdentityWebApiAuthentication(Configuration);

它有效。

但是,我不希望所有端点都受此方法保护(我有其他身份验证机制) 我的想法是在客户端以某种方式获取“代码”变量(在浏览器窗口上设置的那个,但不幸的是没有在我的 C# 代码中返回结果),将它发送到服务器上并在特定控制器内部尝试“登录”用户(获取来自该代码的 access_token)

原因是我已经有了自己的基于数据库中用户表的身份验证机制。

【问题讨论】:

    标签: c# .net azure-active-directory azure-ad-graph-api msal


    【解决方案1】:

    如果我理解正确,您希望使用 AD 仅保护选定的 API 端点。您当然可以通过如下设置Startup.cs 来做到这一点:

    services.AddAuthentication(options =>
                  {
                      options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                  })
                    .AddJwtBearer("AAD", jwtOptions =>
                    {
                        jwtOptions.Authority = $"{appConfiguration.AppSettings.AadInstance}/{appConfiguration.AppSettings.AadDomain}";
                        jwtOptions.Audience = appConfiguration.AppSettings.AadClientId;
                        jwtOptions.Events = new JwtBearerEvents
                        {
                            OnAuthenticationFailed = arg =>
                            {
                                // invoked if authentication fails
                                return Task.FromResult(0);
                            }
                        };
                        
                    });
                
                services.AddAuthorization(options => 
                {
                    options.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().AddAuthenticationSchemes("AAD").Build();
    
                    options.AddPolicy("AAD", new AuthorizationPolicyBuilder().RequireAuthenticatedUser().AddAuthenticationSchemes("AAD").Build());
                });
    

    并且,将属性添加到需要保护的控制器/操作方法,如下所示:

    [Authorize(Policy = "AAD")]
    

    【讨论】:

    • 我做了类似的事情 [Authorize(AuthenticationSchemes="ADSchema")]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 2022-10-25
    • 2017-01-17
    • 2022-09-23
    • 2016-10-19
    相关资源
    最近更新 更多