![](/img/trans.png)
[英]Is it possible to decorate ASP.NET WEB API controller method with more than one Http attribute
[英]Is it possible to secure an ASP.NET Web API 2 application against more than one authentication provider?
我刚刚完成了这篇关于使用ADAL和OWIN中间件组件针对ADFS / Windows Azure AD实例使用OAuth2保护ASP.NET Web API 2应用程序的优秀文章 。
但是,似乎本文中描述的整个身份验证工作流程非常“硬连接”到HTTP请求管道中,并且不会为执行与其他身份验证提供程序的身份验证工作流留下任何空间。
为什么需要这个?
我有一个移动Web客户端,允许“内部”和“外部”用户进行身份验证,以便针对API端点发出用户相关数据的请求。
当“内部”用户从Azure AD / ADFS获取其身份验证令牌时,“外部”用户必须对另一个发出另一种身份验证令牌的系统进行身份验证。
因此,我必须能够在API端点级别上区分来自“内部”和“外部”用户的请求,以便为其不同的身份验证令牌启动正确的评估工作流。
关于如何实现这一目标的任何迹象都将受到高度赞赏。
问候,马蒂亚斯
经过一些挖掘后,我找到了以下答案 ,该答案描述了如何使用JwtSecurityTokenHandler类以编程方式验证由ADFS OAuth 2.0身份验证流程发出的基于JWT的身份验证令牌。 代码示例可以在链接的答案中找到。
这将允许我创建一个自定义授权过滤器,然后我可以将其用作控制器或控制器方法的属性。 此过滤器将分析客户端请求中的Authorization标头,检测其中包含的身份验证令牌的类型,然后启动相应的程序逻辑以验证/验证身份验证令牌。
沿着这些方向的东西可能是:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.