c# – WebAPI和授权基础

我创建了一个WebAPI,但现在我想通过基本授权来保护它.

// POST the data to the API
using (var client = new WebClient())
{
    client.Headers.Add("Content-Type", "application/json");
    client.Headers.Add(HttpRequestHeader.Authorization, "Basic" + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials)));
    string json = JsonConvert.SerializeObject(ex);
    string content = client.UploadString("http://myURL/v1/endpoint", json);
}

下面,我如何发布数据.现在,我想创建一个可以添加到我的控制器或我的Application_Start()的函数.它将检查:

>如果request.Headers.Authorization是!= null
>如果request.Headers.Authorization.Scheme是!=“基本”
>如果有一些参数
>获取参数并对其进行解码以创建一对(SecretId / SecretKey)
>调用服务以检查数据库中是否存在具有此对的客户端
>使用IPrincipal创建身份

问题是我不知道最好的方法是创建customAttribute或过滤器或其他东西.有很多不同的方法可以做到这一点,但我想了解其中的差异.

最佳答案 在项目中创建下面提到的过滤器,并在Web API方法的顶部使用它:

**[BasicAuth]**

    /// <summary>
/// Basic Authentication Filter Class
/// </summary>
public class BasicAuthAttribute : ActionFilterAttribute
{
    /// <summary>
    /// Called when [action executing].
    /// </summary>
    /// <param name="filterContext">The filter context.</param>
    public override void OnActionExecuting(HttpActionContext filterContext)
    {
        try
        {
            if (filterContext.Request.Headers.Authorization == null)
            {
                // Client authentication failed due to invalid request.

                filterContext.Response = new System.Net.Http.HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.Unauthorized,
                    Content = new StringContent("{\"error\":\"invalid_client\"}", Encoding.UTF8, "application/json")
                };
                filterContext.Response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", "realm=xxxx"));
            }
            else if (filterContext.Request.Headers.Authorization.Scheme != "Basic" ||
                string.IsNullOrEmpty(filterContext.Request.Headers.Authorization.Parameter))
            {
                // Client authentication failed due to invalid request.
                filterContext.Response = new System.Net.Http.HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.BadRequest,
                    Content = new StringContent("{\"error\":\"invalid_request\"}", Encoding.UTF8, "application/json")
                };
            }
            else
            {
                var authToken = filterContext.Request.Headers.Authorization.Parameter;
                Encoding encoding = Encoding.GetEncoding("iso-8859-1");
                string usernamePassword = encoding.GetString(Convert.FromBase64String(authToken));

                int seperatorIndex = usernamePassword.IndexOf(':');
                string clientId = usernamePassword.Substring(0, seperatorIndex);
                string clientSecret = usernamePassword.Substring(seperatorIndex + 1);
                if (!ValidateApiKey(clientId, clientSecret))
                {
                    // Client authentication failed due to invalid credentials
                    filterContext.Response = new System.Net.Http.HttpResponseMessage()
                    {
                        StatusCode = HttpStatusCode.Unauthorized,
                        Content = new StringContent("{\"error\":\"invalid_client\"}", Encoding.UTF8, "application/json")
                    };
                }
                // Successfully finished HTTP basic authentication
            }
        }
        catch (Exception ex)
        {
            // Client authentication failed due to internal server error
            filterContext.Response = new System.Net.Http.HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.BadRequest,
                Content = new StringContent("{\"error\":\"invalid_request\"}", Encoding.UTF8, "application/json")
            };
        }
    }





    /// <summary>
    /// Validates the API key.
    /// </summary>
    /// <param name="recievedKey">The recieved key.</param>
    /// <returns></returns>
    private bool ValidateApiKey(string clientId, string clientSecret)
    {
        if (your condition satisfies)
        {
            return true;
        }
        return false;
    }
}
点赞