我曾经在类似的情况下工作,并实现了一个身份验证过滤器 (IAuthenticationFilter
) 和一个继承自 OAuthAuthorizationServerProvider
的自定义类。在我的情况下,我需要使用 OAuth 和旧令牌对请求进行身份验证。我相信在你的情况下,你需要自定义 AuthenticationFilter
。以下是 AuthenticationFilter
的示例:
public class MyAuthenticationFilter : IAuthenticationFilter
{
private readonly string _authenticationType;
public MyAuthenticationFilter(string authenticationType)
{
if (authenticationType == null)
{
throw new ArgumentNullException("authenticationType");
}
_authenticationType = authenticationType;
}
public string AuthenticationType
{
get { return _authenticationType; }
}
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpRequestMessage request = context.Request;
if (request == null)
{
throw new InvalidOperationException("Request mut not be null");
}
IAuthenticationManager authenticationManager = GetAuthenticationManagerOrThrow(request);
cancellationToken.ThrowIfCancellationRequested();
AuthenticateResult result = await authenticationManager.AuthenticateAsync(_authenticationType);
ClaimsIdentity identity = null;
if (result != null)
{
identity = result.Identity;
if (identity != null)
{
context.Principal = new ClaimsPrincipal(identity);
}
}
else
{
if (!request.Headers.Contains("legacy-token-header"))
context.ErrorResult = new AuthenticationFailureResult(Resources.SAUTH_ERROR_LEGACYTOKENNOTFOUND, request);
else
{
try
{
var queryString = request.GetQueryNameValuePairs();
if (!queryString.Any(x => x.Key == "l"))
context.ErrorResult = new AuthenticationFailureResult(Resources.SAUTH_ERROR_USERTYPENOTFOUND, request);
else
{
var userType = queryString.First(x => x.Key == "l").Value;
String token = HttpUtility.UrlDecode(request.Headers.GetValues("tk").First());
identity = TokenLegacy.ValidateToken(token, userType);
identity.AddClaims(userType, (OwinRequest) ((OwinContext)context.Request.Properties["MS_OwinContext"]).Request);
if (identity != null)
{
context.Principal = new ClaimsPrincipal(identity);
}
}
}
catch (Exception e)
{
context.ErrorResult = new AuthenticationFailureResult(e.Message, request);
}
}
}
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpRequestMessage request = context.Request;
if (request == null)
{
throw new InvalidOperationException("Request mut not be null");
}
IAuthenticationManager authenticationManager = GetAuthenticationManagerOrThrow(request);
authenticationManager.AuthenticationResponseChallenge = AddChallengeAuthenticationType(
authenticationManager.AuthenticationResponseChallenge, _authenticationType);
return TaskHelpers.Completed();
}
public bool AllowMultiple
{
get { return true; }
}
private static AuthenticationResponseChallenge AddChallengeAuthenticationType(
AuthenticationResponseChallenge challenge, string authenticationType)
{
Contract.Assert(authenticationType != null);
List<string> authenticationTypes = new List<string>();
AuthenticationProperties properties;
if (challenge != null)
{
string[] currentAuthenticationTypes = challenge.AuthenticationTypes;
if (currentAuthenticationTypes != null)
{
authenticationTypes.AddRange(currentAuthenticationTypes);
}
properties = challenge.Properties;
}
else
{
properties = new AuthenticationProperties();
}
authenticationTypes.Add(authenticationType);
return new AuthenticationResponseChallenge(authenticationTypes.ToArray(), properties);
}
private static IAuthenticationManager GetAuthenticationManagerOrThrow(HttpRequestMessage request)
{
Contract.Assert(request != null);
var owinCtx = request.GetOwinContext();
IAuthenticationManager authenticationManager = owinCtx != null ? owinCtx.Authentication : null;
if (authenticationManager == null)
{
throw new InvalidOperationException("IAuthenticationManagerNotAvailable");
}
return authenticationManager;
}
}
在
WebApiConfig.cs
中,您需要添加以下身份验证过滤器:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new MyAuthenticationFilter(OAuthDefaults.AuthenticationType));
}
}
我建议阅读官方WEB API海报:
https://www.asp.net/media/4071077/aspnet-web-api-poster.pdf