HTTP authorization in header is basic by default and throws http500 if mentioned

53 Views Asked by At

I have an OData interface with an implemented basic authentication. Somehow the basic auth is set to default by its class. When I deliver the credentials in the request header without the key word "Basic", it works fine, but when I do, I get a HTTP 500 Internal Server Error. How can I remove the default basic auth setting?

works: picture of auth checkbox

does not work, like it should: auth checkbox with basic setting

This is my auth class:

public class HttpBasicAuthorizeAttribute:AuthorizeAttribute {

    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) {
        Debug.WriteLine(actionContext.Request.Headers);
        if (actionContext.Request.Headers.Authorization != null) {
            // get the Authorization header value from the request and base64 decode it
                            
            string userInfo = Encoding.Default.GetString(Convert.FromBase64String(actionContext.Request.Headers.Authorization.ToString()));
            // custom authentication logic
            if (string.Equals(userInfo,string.Format("{0}:{1}","name","=password"))) {
                IsAuthorized(actionContext);
            }
            else {
                HandleUnauthorizedRequest(actionContext);
            }
        }
        else {
            HandleUnauthorizedRequest(actionContext);
        }
    }

    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext) {
        actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized) {
            ReasonPhrase = "Unauthorized"
        };
    }
}
1

There are 1 best solutions below

4
akg179 On

The right way to pass an Authorization header value is 'Basic {base64string}' and based on the image you shared in the question, the right way is causing an Internal Server Error for you. That's because the output of actionContext.Request.Headers.Authorization.ToString() is not a valid Base64 string as it contains the 'Basic ' string literal in it. Before you apply Convert.FromBase64String() on it, you will need to remove the 'Basic ' literal from it.

Applying an additional .Replace("Basic ", string.Empty) at the end of ToString() would do it. Should look like this-

string userInfo = Encoding.Default.GetString(Convert.FromBase64String(actionContext.Request.Headers.Authorization.ToString().Replace("Basic ", string.Empty)));