user2227904
user2227904

Reputation: 679

Error 500 with authorization while consuming OAuth2 RESTful service through C#

My current job is to consume a RESTful API with OAuth2. Currently I worked out how to get the access token and it is working ok while I use the chrome extension Rest Console, but when I try to do it from my application I always get the error that I am sending an invalid OAuth request. Below you can see three of the ways I tried to consume the API, but to no success. The page always returns error 500. Any help will be appreciated, if I had missed something crucial.

    var auth = "Bearer " + item.access_token;


    /* First Attempt */
    var client = new RestClient("http://<link>");
    var request = new RestRequest("sample", Method.GET);
    request.AddHeader("Authorization", auth);
    request.AddHeader("Content-Type", "application/json;charset=UTF-8");
    request.AddHeader("Pragma", "no-cache");
    request.AddHeader("User-Agent", "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
    request.AddHeader("Accept", "application/json");
    request.RequestFormat = DataFormat.Json;
    var response = client.Execute(request);
    var content = response.Content;





    /* Second Attempt */
    string sURL = "http://<link>/sample";

    string result = "";

    using (WebClient client = new WebClient())
    {
        client.Headers["Authorization"] = auth;
        client.Headers["Content-Type"] = "application/json;charset=UTF-8";
        client.Headers["Pragma"] = "no-cache";
        client.Headers["User-Agent"] = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
        client.Headers["Accept"] = "application/json";

        byte[] byteArray = Encoding.UTF8.GetBytes(parameters);

        var result1 = client.DownloadString(sURL);
    }


    /* Third Attempt */
    var request = (HttpWebRequest)WebRequest.Create(sURL);
    request.Method = "GET";
    request.ContentType = "application/json;charset=UTF-8";
    request.Accept = "application/json";
    request.Headers["Authorization"] = auth;
    request.UserAgent = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
    string content;
    HttpStatusCode statusCode;
    using (var response = request.GetResponse())
    using (var stream = response.GetResponseStream())
    {
        var contentType = response.ContentType;
        Encoding encoding = null;
        if (contentType != null)
        {
            var match = Regex.Match(contentType, @"(?<=charset\=).*");
            if (match.Success)
                encoding = Encoding.GetEncoding(match.ToString());
        }

        encoding = encoding ?? Encoding.UTF8;

        statusCode = ((HttpWebResponse)response).StatusCode;
        using (var reader = new StreamReader(stream, encoding))
            content = reader.ReadToEnd();
    }

--------EDIT--------

For the first attempt I also tried to add the authentication to the client variable client.Authenticator = Authenticate; where OAuth2AuthorizationRequestHeaderAuthenticator Authenticate = new OAuth2AuthorizationRequestHeaderAuthenticator(item.access_token, item.token_type);

Upvotes: 16

Views: 3337

Answers (1)

Mr Rivero
Mr Rivero

Reputation: 1248

The code seems right. The fail attempts you did suggest that the issue is with the token and not the code. Bearer tokens have expiration time. So semms like your token expired between the first time you got it using chrome REST Console extension and when you wrote your code. But the strange situation here is the 500 error code you got. 401 is standard response when you token expired or not exist. 500 error code always mean server error.

Upvotes: 2

Related Questions