将 Azure Active Directory 与 .NET Web API 连接,经过身份验证始终为 false



我正在使用Angular 7开发一个标准的.NET Web Api 2,我需要连接Azure Active Directory。

我添加了以下代码:

public static void ConfigureAuth(IAppBuilder app)
{
       app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Tenant = configurationManager.AadTenant,
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidAudience = configurationManager.AadAudience,
                    },
                });
 }

我的租户和受众都是正确的。一切正常,令牌有效并存在于请求中。

问题是IsAuthentication总是假的,当我查看身份中的声明时,它们是空的

 protected override bool IsAuthorized(HttpActionContext actionContext)
 {
     return base.IsAuthorized(actionContext); // Always false
 }

我不知道问题出在哪里。我尝试了很多链接,但没有一个对我有用。有人知道为什么吗?谢谢

若要保护您的服务,可以使用如下所示的 IsAuthorize 筛选器实现:

private static string trustedCallerClientId = ConfigurationManager.AppSettings["ida:TrustedCallerClientId"];  
protected override bool IsAuthorized(HttpActionContext actionContext)  
        {  
            bool isAuthenticated = false;  
            try  
            {  
                string currentCallerClientId = ClaimsPrincipal.Current.FindFirst("appid").Value;  
                isAuthenticated = currentCallerClientId == trustedCallerClientId;  
            }  
            catch (Exception ex)  
            {  
                new CustomLogger().LogError(ex, "Invalid User");  
                isAuthenticated = false;  
            }  
            return isAuthenticated;  
        }  

主体不是从当前线程中获取的,而是从 actionContext 中获取的。因此,您必须设置的是操作上下文的请求上下文中的主体:

actionContext.RequestContext.Principal = yourPrincipal;

我假设您的操作上下文.requestcontext没有正确的数据,这就是为什么即使您的请求成功但您的属性始终为假。

参考:

https://www.c-sharpcorner.com/article/azure-active-directory-authentication/

希望对您有所帮助。

相关内容

最新更新