使用Owin在Asp.Net Web Api中同时使用OAuth和Basic Auth

时间:2015-02-05 20:02:19

标签: asp.net-web-api oauth owin

我在基于on these blog posts

的Web Api项目中实施了OAuth身份验证

效果很好,包括刷新令牌逻辑。

我想为基本身份验证添加一个选项,以及为预定作业调用几个。

我尝试添加Basic Auth解决方案作为中间件,但我仍然要求401要求持有者令牌。

我可以通过从那些api调用中删除[Authorize]属性并在代码中手动检查(如果用户已经过身份验证但似乎是错误的解决方法)来实现它。

有没有办法使用OWin支持Basic Auth和OAuth身份验证?

1 个答案:

答案 0 :(得分:7)

如何将您的操作或控制器归属于您希望使用属性[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()
{
}

请注意我们如何创建声明身份并将身份验证方案设置为Basic,您可以在此处提出所需的任何声明。