4

I created a WebAPI but now I want to secure 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, how I post the data. Now, I would like to create a function that I can add to my controller or my Application_Start(). It will check:

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

The thing is I don't know the best way is to create a customAttribute or a filter or something else. There is plenty of different way to do this but I would like to understand the difference.

3
  • If you need to intercept request, you can use Application_BeginRequest() in Global.asax file where you can interact with your request Commented Oct 20, 2017 at 2:19
  • 2
    You will need an Authentication Filter. Look it up learn.microsoft.com/en-us/aspnet/web-api/overview/security/… Commented Oct 20, 2017 at 2:21
  • 2
    I think the best way is to use a custom authorize attribute. Then, you may or may not register it in your application_start. Commented Oct 20, 2017 at 2:21

2 Answers 2

1

Create the below-mentioned Filter in your project and use it at top of your web API method as :

**[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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I found few interesting articles about handlers/filter and attribute. I don't want to override [Authorize] so I will probably do an Authentication Filter.

Below some good links:

@Nkosi: Cheers to confirm. I'm going to change the code a little bit because I don't want to use an Attribute but rather an filter that I put in the WebApiConfig

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.