WebAPI and Basic Authorization

I created a WebAPI, but now I want to protect it with Basic Authorization.

// 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);
}

Below is how I publish the data. Now I would like to create a function that I can add to the controller or mine Application_Start(). He will check:

  • if request.Headers.Authorization is! = null
  • if request.Headers.Authorization.Scheme is! = "Basic"
  • if there are some parameters
  • get the parameter and decode it to create a pair (SecretId / SecretKey)
  • calling a service to check in the database, if there is a client with this pair
  • create an identifier using IPrincipal

The thing is, I don’t know what the best way is to create a customAttribute or filter or something else. There are many different ways to do this, but I would like to understand the difference.

+4
2

-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;
    }
}
+1

/ . [], , , .

:

@Nkosi: , . , , , WebApiConfig

0

Source: https://habr.com/ru/post/1687843/


All Articles