【问题标题】:Is it possible to secure an ASP.NET Web API 2 application against more than one authentication provider?是否可以针对多个身份验证提供程序保护 ASP.NET Web API 2 应用程序?
【发布时间】:2016-11-18 11:26:21
【问题描述】:

我刚刚完成了this excellent article 关于使用 OAuth2 保护 ASP.NET Web API 2 应用程序对使用 ADAL 和 OWIN 中间件组件的 ADFS/Windows Azure AD 实例的保护。

但是,本文中描述的整个身份验证工作流程似乎非常“硬连线”到 HTTP 请求管道中,并且没有为针对其他身份验证提供程序实施身份验证工作流程留下任何空间。

为什么需要这个?

我有一个移动网络客户端,其中允许“内部”和“外部”用户进行身份验证,以便针对 API 端点发出对用户相关数据的请求。

虽然“内部”用户从 Azure AD/ADFS 获取他们的身份验证令牌,但“外部”用户必须针对另一个发布另一种身份验证令牌的系统进行身份验证。

因此,我必须能够在 API 端点级别区分来自“内部”和“外部”用户的请求,以便针对他们的不同身份验证令牌启动正确的评估工作流程。

任何关于如何实现这一目标的指示将不胜感激。

问候,马蒂亚斯

【问题讨论】:

标签: c# azure authentication asp.net-web-api2 adal


【解决方案1】:

经过一番挖掘,我找到了following answer,它描述了如何使用JwtSecurityTokenHandler class 以编程方式验证由 ADFS OAuth 2.0 身份验证流程颁发的基于 JWT 的身份验证令牌。代码示例可以在链接的答案中找到。

这将允许我创建一个自定义授权过滤器,然后我可以将其用作控制器或控制器方法的属性。此过滤器将分析客户端请求中的授权标头,检测其中包含的身份验证令牌的类型,然后启动相应的程序逻辑以验证/验证身份验证令牌。

可能是这样的:

public enum AuthTokenType
{
    OAuth2Bearer,
    Custom
}

public class CustomAuthenticationAttribute : IAuthenticationFilter
{
    public bool AllowMultiple
    {
        get
        {
            throw new NotImplementedException();
        }
    }

    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
            HttpRequestMessage incommingRequest = context.Request;
            HttpHeaders headers = incommingRequest.Headers;
            string authHeader = GetHeader(headers, "Authorization");
            AuthTokenType authTokenType = DetecteAuthTokenType(authHeader);

            if (authTokenType == AuthTokenType.OAuth2Bearer) 
            {
               // Validate auth token using the JwtSecurityTokenHandler class
            }
            else if (authTokenType == AuthTokenType.Custom)
            {
               // Validate auth token using whatever is necessary
            }
            else
            {
               // auth token doesn't correspond to a recognized type or hasn't been part of the client request - reject request
            }  
    }

    public AuthTokenType DetectAuthTokenType(string authHeader)
    {
       // Analyze the authorization header string and return its proper type
    }

    private string GetHeader(HttpHeaders headers, string key)
    {
        IEnumerable<string> keys = null;
        if (!headers.TryGetValues(key, out keys))
            return null;

        return keys.First();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    相关资源
    最近更新 更多