Getting 401 unauthorized error, while using access_token


#1

Hi Sir, Mam,

Please help, I am getting 401 unauthorized error, and not able to fix it :-(

please check my code -

public string validateLogin()  //first function, 
{
    string oauth_signature_method = "HMAC-SHA1";
    string oauth_token = "";
    string oauth_token_Secret = "";
    string oauth_timestamp = GenerateTimeStamp();
    string oauth_nonce = GenerateNonce();
    string oauth_version = oAuthVersion.ToString();
    string x_auth_username = HttpUtility.UrlEncode("XXX");
    string x_auth_password = HttpUtility.UrlEncode("XXXX");
    string x_auth_mode = "client_auth";

    string outUrl = "";
    string queryString = "";
    string ret = "";

    Uri xAuthUrl = new Uri(ACCESS_TOKEN);

    string sig = GenerateSignature(xAuthUrl, oauth_consumer_key, oauth_consumer_Secret, oauth_token, oauth_token_Secret, x_auth_username, x_auth_password, oauth_timestamp, oauth_nonce, out outUrl, out queryString);

      queryString += "&oauth_signature=" + HttpUtility.UrlEncode(sig);
    //ret = WebRequest(Method.GET, outUrl, queryString);

    string header = CreateHeader(oauth_consumer_key, oauth_nonce, sig, oauth_signature_method, oauth_timestamp, oauth_token, oauth_version);

    outUrl += "?";
    
    ret = WebRequest(Method.POST, outUrl, queryString, header);
    return ret;
}

public string GenerateNonce()
{
    return random.Next(123400, 9999999).ToString();
}

public string GenerateTimeStamp()
{
    TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return Convert.ToInt64(ts.TotalSeconds).ToString();
}

public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string username, string password, string timestamp, string nonce, out string normalizedUrl, out string normalizedRequestParameters)
{
    normalizedUrl = null;
    normalizedRequestParameters = null;

    string signatureBase = GenerateSignatureBase(url, consumerKey, consumerSecret, token, tokenSecret, username, password, timestamp, nonce, out normalizedUrl, out normalizedRequestParameters);
    HMACSHA1 hmacsha1 = new HMACSHA1();
    hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), string.IsNullOrEmpty(token) ? "" : UrlEncode(tokenSecret)));
    return GenerateSignatureUsingHash(signatureBase, hmacsha1);
}

public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash)
{
    return ComputeHash(hash, signatureBase);
}

public string ComputeHash(HashAlgorithm hash, string signatureBase)
{
    byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(signatureBase);
    byte[] hashBytes = hash.ComputeHash(dataBuffer);
    return Convert.ToBase64String(hashBytes);
}

public class QueryParameter
{
    private string name = null;
    private string value = null;
    public QueryParameter(string name, string value)
    {
        this.name = name;
        this.value = value;
    }
    public string Name
    {
        get { return name; }
    }
    public string Value
    {
        get { return value; }
    }
}

public class QueryParameterCompare : IComparer<QueryParameter>
{
    #region IComparer<QueryParameter> members
    public int Compare(QueryParameter x, QueryParameter y)
    {
        if (x.Name == y.Name)
        {
            return string.Compare(x.Value, y.Value);
        }
        else
        {
            return string.Compare(x.Name, y.Name);
        }
    #endregion
    }
}


public string NormalizedRequestParametrs(IList<QueryParameter> parameters)
{
    StringBuilder sb = new StringBuilder();
    QueryParameter p = null;

    for (int i = 0; i < parameters.Count; i++)
    {
        p = parameters[i];
        sb.AppendFormat("{0}={1}", p.Name, p.Value);
        if (i < parameters.Count - 1)
        {
            sb.Append("&");
        }
    }
    return sb.ToString();
}

private List<QueryParameter> GetQueryParameters(string parameters)
{
    if (parameters.StartsWith("?"))
    {
        parameters = parameters.Remove(0, 1);
    }
    List<QueryParameter> result = new List<QueryParameter>();
    if (!string.IsNullOrEmpty(parameters))
    {
        string[] p = parameters.Split('&');
        foreach (string s in p)
        {
            if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix))
            {
                if (s.IndexOf('=') > -1)
                {
                    string[] temp = s.Split('=');
                    result.Add(new QueryParameter(temp[0], temp[1]));
                }
                else
                {
                    result.Add(new QueryParameter(s, string.Empty));
                }
            }
        }
    }
    return result;
}


public string GenerateSignatureBase(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string username, string password, string timestamp, string nonce, out string normalizedUrl, out string normalizedRequestParameters)
{
    normalizedUrl = null;
    normalizedRequestParameters = null;

    List<QueryParameter> parameters = GetQueryParameters(url.Query);
    parameters.Add(new QueryParameter(OAuthVersionKey, oAuthVersion.ToString()));
    parameters.Add(new QueryParameter(OAuthNonceKey, nonce));
    parameters.Add(new QueryParameter(OAuthTimeStampKey, timestamp));
    parameters.Add(new QueryParameter(OAuthSgnatureMethodKey, "HMAC-SHA1"));
    parameters.Add(new QueryParameter(OAuthConsumerKey, consumerKey));
    parameters.Add(new QueryParameter(OAuthTokenKey, token));
    parameters.Add(new QueryParameter(OAuthVerifier, ""));
    parameters.Add(new QueryParameter(XAuthUserName, username));
    parameters.Add(new QueryParameter(XAuthPassword, password));
    parameters.Add(new QueryParameter(XAuthMode, "client_auth"));

    parameters.Sort(new QueryParameterCompare());

    normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host);
    if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
    {
        normalizedUrl += ":" + url.Port;
    }
    normalizedUrl += url.AbsolutePath;

    normalizedRequestParameters = NormalizedRequestParametrs(parameters);

    StringBuilder signatureBase = new StringBuilder();
    signatureBase.AppendFormat("{0}&", Method.POST);
    signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
    signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));
    return signatureBase.ToString();
}

public string WebRequest(Method method, string url, string postData, string headerData)
{
    HttpWebRequest webrequest = null;
    Stream requestWriter = null;
    string responseData = "";

    System.Net.ServicePointManager.Expect100Continue = false;
    webrequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
    webrequest.Method = method.ToString();
    webrequest.UserAgent = ".NET";
    
    webrequest.Credentials = CredentialCache.DefaultCredentials;
    webrequest.AllowWriteStreamBuffering = true;

    webrequest.PreAuthenticate = true;
    webrequest.ServicePoint.Expect100Continue = false;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

    webrequest.Headers.Add("Authorization", headerData.ToString());

    if (method == Method.POST)
    {
        webrequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
        webrequest.Accept = "*/*";
        byte[] btArr = UTF8Encoding.UTF8.GetBytes(postData);
        webrequest.ContentLength = btArr.Length;
        requestWriter = webrequest.GetRequestStream();
        requestWriter.Write(btArr, 0, btArr.Length);
        requestWriter.Close();
    }
    responseData = WebResponseGet(webrequest);
    webrequest = null;
    return responseData;
}

public string WebResponseGet(HttpWebRequest webrequest)
{
    StreamReader responseReader = null;
    string responseData = "";
    try
    {
        responseReader = new StreamReader(webrequest.GetResponse().GetResponseStream());
        responseData = responseReader.ReadToEnd();
    }
    catch (Exception e)
    {
        throw;
    }
    finally
    {
        webrequest.GetResponse().GetResponseStream().Close();
        responseReader.Close();
        responseReader = null;
    }
    return responseData;
}

public string CreateHeader(string oauth_consumer_key, string oauth_nonce, string oauth_signature, string oauth_signature_method, string oauth_timestamp, string oauth_token, string oauth_version)
{
    string authorizationHeaderParams = String.Empty;
    authorizationHeaderParams += "OAuth ";
    authorizationHeaderParams += "oauth_nonce=" + "\"" +
                                 Uri.EscapeDataString(oauth_nonce) + "\",";

    authorizationHeaderParams +=
        "oauth_signature_method=" + "\"" +
        Uri.EscapeDataString(oauth_signature_method) +
        "\",";

    authorizationHeaderParams += "oauth_timestamp=" + "\"" +
                                 Uri.EscapeDataString(oauth_timestamp) + "\",";

    authorizationHeaderParams += "oauth_consumer_key="
                                 + "\"" + Uri.EscapeDataString(oauth_consumer_key) + "\",";

    //authorizationHeaderParams += "oauth_token=" + "\"" +
    //                             Uri.EscapeDataString(oauth_token) + "\",";

    authorizationHeaderParams += "oauth_signature=" + "\""
                                 + Uri.EscapeDataString(oauth_signature) + "\",";

    authorizationHeaderParams += "oauth_version=" + "\"" +
                                 Uri.EscapeDataString(oauth_version) + "\"";
    return authorizationHeaderParams;
}

public string UrlEncode(string value)
{
    StringBuilder result = new StringBuilder();

    foreach (char symbol in value)
    {
        if (unreservedChars.IndexOf(symbol) != -1)
        {
            result.Append(symbol);
        }
        else
        {
            result.Append('%' + String.Format("{0:X2}", (int)symbol));
        }
    }

    return result.ToString();
}

Please help.

Thanks
Prasansha


#2

Hi All