在Asp.Net Web API中使用OAuth和Basic Auth与Owin
我基于这些博客文章在我的Web Api项目中实现了OAuth身份验证
它运行良好,包括刷新令牌逻辑。
我想为基本身份验证添加一个选项,以及针对预定作业的几个调用。
我尝试添加一个基本身份验证解决方案作为中间件,但我仍然得到401要求持票人令牌。
我可以通过从这些api调用中除去[Authorize]属性并在代码中手动检查用户是否已通过验证,但似乎是解决此问题的错误方法。
有没有办法同时支持使用OWin的基本身份验证和OAuth身份验证?
你如何将你的动作或控制器属性设置为你希望通过属性[OverrideAuthentication]
来实现基本验证然后,创建自定义验证过滤器属性,该属性继承自Attribute, IAuthenticationFilter
如下面的代码
public class BasicAuthenticationAttribute : Attribute, IAuthenticationFilter
{
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
var req = context.Request;
// Get credential from the Authorization header
//(if present) and authenticate
if (req.Headers.Authorization != null && "basic".Equals(req.Headers.Authorization.Scheme, StringComparison.OrdinalIgnoreCase))
{
var rawCreds = req.Headers.Authorization.Parameter;
var credArray = GetCredentials(rawCreds);
var clientId = credArray[0];
var secret = credArray[1];
if (ValidCredentials(clientId, secret))
{
var claims = new List<Claim>()
{
new Claim(ClaimTypes.Name, clientId)
};
var identity = new ClaimsIdentity(claims, "Basic");
var principal = new ClaimsPrincipal(new[] { identity });
// The request message contains valid credential
context.Principal = principal;
}
else
{
context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
}
}
else
{
context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
}
return Task.FromResult(0);
}
private string[] GetCredentials(string rawCred)
{
var encoding = Encoding.GetEncoding("UTF-8");
var cred = encoding.GetString(Convert.FromBase64String(rawCred));
var credArray = cred.Split(':');
if (credArray.Length == 2)
{
return credArray;
}
else
{
return credArray = ":".Split(':');
}
}
private bool ValidCredentials(string clientId, string secret)
{
//compare the values from web.config
if (clientId == secret)
{
return true;
}
return false;
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context,CancellationToken cancellationToken)
{
context.Result = new ResultWithChallenge(context.Result);
return Task.FromResult(0);
}
public class ResultWithChallenge : IHttpActionResult
{
private readonly IHttpActionResult next;
public ResultWithChallenge(IHttpActionResult next)
{
this.next = next;
}
public async Task<HttpResponseMessage> ExecuteAsync( CancellationToken cancellationToken)
{
var response = await next.ExecuteAsync(cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic"));
}
return response;
}
}
public bool AllowMultiple
{
get { return false; }
}
}
现在,您可以使用它来将控制器或操作归类为以下代码:
[OverrideAuthentication]
[BasicAuthentication]
[Route("")]
public async Task<IHttpActionResult> Get()
{
}
请注意,我们如何创建声明标识并将身份验证方案设置为基本,您可以在此输入任何声明。
链接地址: http://www.djcxy.com/p/22339.html上一篇: Using both OAuth and Basic Auth in Asp.Net Web Api with Owin