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

问题描述 投票:0回答:1

我正在使用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,
                    },
                });
 }

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

问题是IsAuthenticated总是错误的,当我查看身份中的声明时,它们是空的

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

我不知道问题出在哪里。我尝试过很多链接,但没有一个能为我工作。谁知道为什么?谢谢

azure authentication asp.net-web-api azure-active-directory
1个回答
0
投票

为了保护您的服务,您可以使用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;

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

参考:

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

希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.