Search code examples
javawebtwittertwitter-login

Guide about twitter login in web without using any third party library


I find a way to implement twitter login with github twitter4j but I want to implement it without using any third party library. With the twitter document, I am not able to understand what should I do for it. From where I can get oauth_nonce, oauth_timestamp & oauth_signature's value? Please suggest me a good way to implement twitter login in web.


Solution

  • I am myself the developer of a ThirdParty library and I will definitely advise to use them. Twitter authentication has multiple problems to consider.

    Anyway here is an answer for you.

    // oauth_nonce
    var oauth_nonce = new Random().Next(123400, 9999999).ToString(CultureInfo.InvariantCulture);
    
    // oauth_timestamp
    TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    var oauthTimestamp = Convert.ToInt64(ts.TotalSeconds).ToString(CultureInfo.InvariantCulture);
    

    Signature is a bit more complicated. You need to extract all the params of your query. Order them by name, Append all of them into a string separated with '&' (lets call it URL_PARAMETERS). Then create a string as followed {HTTP_METHOD}&{BASE_URL}&{URL_PARAMETERS}

    Now you simply have to compute the Hash of the previous value with the oauth_secret_key (from Twitter app).

    And not you can simply do oauth_signature = Http.UrlEncode(Convert.ToBase64(<HASH>)).

    Also don't forget

    var oauth_signature_method = "HMAC-SHA1";