> For the complete documentation index, see [llms.txt](https://backbench.gitbook.io/backbench-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://backbench.gitbook.io/backbench-docs/3rd-party-integrations/login-with-twitter.md).

# Login with Twitter

## What You'll Need

1. Backbench account - [Sign Up](https://bench.backbench.io/signup), the personal account will always remain free to use.
2. Twitter Developer account- Apply for a [Developer account](https://apps.twitter.com/).

## Prerequisites for the app

1. Sign In to backbench, and create or use a bench.
2. Start by creating a new app on twitter, enter a valid callback url in below format,\
   `https://USERID-BENCHID.backbench.io/cb` ( found in Endpoints section of Backbench. )
3. Select Enable Sign In with Twitter at `Allow this application to be used to Sign in with Twitter` and hit save.&#x20;
4. Keep a note of following parameter's from twitter app's dashboard.

   ```
   consumer_key, consumer_secret, callback_url
   ```

## Demo

{% embed url="<https://mybench-samples.backbench.io/twitter.html>" %}
Node.js Sample
{% endembed %}

<https://mybench-bbsamples.backbench.io/twitter.html>

## Frontend

1. Create a html for Twitter's login in File manager section. (**note:** Do not forget to enable File manager from endpoint's section)

{% code title="twitter.html" %}

```markup
<!doctype html>
<html lang="en">
<head>
</head>
<body>
  <h1> login using Google</h1><br><br>
  <a href="/login">Login with witter</a>
</body>
</html>
```

{% endcode %}

## Backend

Create a module `login.js` for Node, `login` for BBLANG. Replace consumer\_key, consumer\_secret, and callback\_url.

{% tabs %}
{% tab title="Node.js" %}
{% code title="login.js" %}

```javascript
var request = require("request");

exports.endpoint = function(req, cb){
    var ckey = "************************"; 
    request({
        url: 'https://api.twitter.com/oauth/request_token',
        oauth: {
            callback: "https://mybench-samples.backbench.io/cb",
            consumer_key: ckey,
            consumer_secret: "*************************************************"
        }
    }, function(err, resp, body){
        var temp = body.split("&")
        var oauth_token = temp[0].split("=")[1]
        var oauth_token_secret = temp[1].split("=")[1]
        bb.memSet(ckey, oauth_token_secret, function(err2, res2){
            if (oauth_token) {
                let redirect_uri = "https://api.twitter.com/oauth/authenticate?oauth_token="+oauth_token
                cb(undefined, {"Location": redirect_uri })
            } else {
                cb(undefined, {"msg": 'Permission denied'})
            }
        })
    })
}
```

{% endcode %}
{% endtab %}

{% tab title="BBLANG" %}
{% code title="login" %}

```javascript
twitter:login(req)->{
    res = bb:http:post({
        url: 'https://api.twitter.com/oauth/request_token',
        oauth: {
            callback: "https://mybench-bbsamples.backbench.io/cb",
            consumer_key: "I5urvH55D1bTWqWzOXfnhVcTk",
            consumer_secret: "miVOFYODoZ4xxtKQTWuE7VpSA8IWRAkZ6zf1HCwZrdH3swYWva"
        }
    })
    oauth_token = std:split(std:split(res.body, "&")[0], "=")[1]
    oauth_token_secret = std:split(std:split(res.body, "&")[1], "=")[1]
    bb:log(oauth_token, oauth_token_secret)
    bb:mem:set(oauth_token_secret, oauth_token_secret)
    if oauth_token {
        bb:http:get({
            url: 'https://api.twitter.com/oauth/authenticate',
            qs: {
                oauth_token: oauth_token
            },
            followAllRedirects: true
        })
    } else {
        'Permission denied'
    }
}

```

{% endcode %}
{% endtab %}
{% endtabs %}

For Node, map `login.js` module to `/login` and for BBLANG, map `twitter:login` to `/login` in Endpoints section.

Now we'll create a function which responds after twitter redirects to /cb. Make `cb.js` for node and `cb` for bblang (`twitter:callback`) and map it to `/cb`.

{% tabs %}
{% tab title="Node.js" %}
{% code title="cb.js" %}

```javascript
var request = require("request");

exports.endpoint = function(req, cb){
    var ckey = "*********************";
    bb.memGet(ckey, function(err, token_secret){
        request({
            method: "post",
            url: "https://api.twitter.com/oauth/access_token",
            oauth: {
                consumer_key: ckey,
                consumer_secret: "********************************************",
                token: req.query.oauth_token,
                token_secret: token_secret, 
                verifier: req.query.oauth_verifier
            }
        }, function(err, resp, body){
            if (err){
                cb(err)
            }
            cb(null, {data: body})
        })
    })
}  
```

{% endcode %}
{% endtab %}

{% tab title="BBLANG" %}
{% code title="cb" %}

```javascript
twitter:callback(req)->{
    res = bb:http:post({
        url: "https://api.twitter.com/oauth/access_token",
        oauth: {
            consumer_key: "*********************************",
            consumer_secret: "********************************************************************************************",
            token: req.query.oauth_token,
            token_secret: bb:mem:get(oauth_token_secret), 
            verifier: req.query.oauth_verifier
        }
    })
    body = std:split(res.body, "&")
    res = bb:http:get({
        url : 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=peeyu5h&count=2',
        qs : {
            screen_name: std:split(body[3], "=")[1],
            user_id: std:split(body[2], "=")[1] 
        },
        oauth : {
            consumer_key: "***************",
            consumer_secret: "**************************",
            token: std:split(body[0], "=")[1] ,
            token_secret: std:split(body[1], "=")[1] 
        },
        json : true
    })
    "<h1>My Latest Tweet</h1>"+res.body[0].text
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

**For Node.js App:**

1. Select +, in the upper right corner to create a Module. For example, say "package.json" and select CREATE or hit Enter.
2. Copy and paste the code module from below.

```javascript
{
    "dependencies": { 
        "request": "^2.88.0"
    }
}
```

A **package.json** file lists the packages that your project depends on. allows you to specify the versions of a package that your project can use using semantic versioning rules.

## Logging in

**Obtaining a request token** \
by sending a `POST` request to `/oauth/request_token` with following as headers. (if you are using nodejs request library then you can send these params in oauth param of[ request](https://github.com/request/request))

```
Authorization:
        OAuth oauth_callback="https://USERNAME-BENCHID.backbench.io/cb",
              oauth_consumer_key="xxxxxxxxxxxxxxxxxxxxxx",
              oauth_consumer_secret="xxxxxxxxxxxxxxxxxxxxx",
```

&#x20;**Redirect to Twitter**

You'll get `oauth_token` in response of above. Next step is to redirect to Twitter's authentication.

`https://api.twitter.com/oauth/authenticate?oauth_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`

**Exchange request\_token with access\_token**&#x20;

Convert your `request_token` to `token`, by sending a POST request to `/oauth/access_token`, with following headers:&#x20;

```
Authorization: OAuth oauth_consumer_key="XXXXXXXXXXXXXXXXXX",
					 oauth_consumer_secret="XXXXXXXXXXXXXXXXXX",
                     oauth_token="NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0",
                     oauth_token_secret="NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0",
					 oauth_verifier="uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY"
```

where `oauth_token` and `oauth_verifier` you'll get as query parameter. (after twitter's redirection)

For a comprehensive guide, refer official doc <https://dev.twitter.com/web/sign-in/implementing>.

## User Permission:

Can be changed on Twitter's app setting page.&#x20;

## Confirming Identity:&#x20;

Once you've obtained an `Token`, you can start making authenticated API requests on behalf of the user by sending request.

`https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=peeyu5h&count=2`

with header containing `consumer_key, consumer_secret, token and token_secret.`
