Search code examples
c#deserializationhttpresponse

Deserialize string (AuthenticationHeaderValue.Parameter)


I'm currently writing an error handling for some http requests. For example, if the token is expired, I receive the following string in response.Headers.WwwAuthenticate:

"error=\"invalid_token\", error_description=\"The token is expired\""

The string is the Paremeter property of a AuthenticationHeaderValue object. I tried deserializing the string with JObject.Parse() and JsonConvert.DeserializeObject() but it doesn't work. I guess it's because the JSON is invalid since the property names are unquoted and it uses "=" instead of ":".

Is there simple way to parse that string?


Solution

  • Had the exact same problem today. My solution will be to check if the parameter string is enclosed by braces and if not put them around and then deserialize it. So it would be something like this:

    var header = response.Headers.WwwAuthenticate.FirstOrDefault();
    
    if (header == null)
        return false;
    
    if (header.Scheme != JwtBearerScheme)
        throw new Exception($"Fatal Error: Authentication scheme is { header.Scheme } instead of { JwtBearerScheme }.");
    
    string parameter = header.Parameter;
    
    if (!parameter.StartsWith("{") || !parameter.EndsWith("}"))
        parameter = "{ " + parameter + " }";
    
    var error = JsonConvert.DeserializeObject<MyErrorObject>(parameter);