Monaca Docs
Search…
Twitter Single Sign-on App
Here, we will explain the method of single sign-on (SSO) using OAuth on Twitter.
For single sign-on, use the InAppBrowser plug-in and a third-party advanced-http plug-in, and the signature required for OAuth uses the oauth-signature library.
After successful authentication, you can display the user's basic information on the app and post tweets.
If you want to use third-party Cordova plugins, you need to create a custom build debugger (Android or iOS).

Demo

Tested Environment
  • Android 11.0
  • iOS 14.3

Prerequisite

Getting Twitter Consumer Key and Consumer Secret

To use the Twitter API, you need to register a developer account. Register a developer account from Twitter Developer Account.
Next, on the Twitter Developer Portal page, register your app and issue a Consumer Key (API key), Consumer Secret (API secret key), and Bearer token.
  1. 2.
    Create Standalone Apps from the Create App button at the bottom of the screen. (Instead of creating Standalone Apps, you can create Apps under Projects)
  2. 3.
    Enter the Name (app name), Description (app description), and Website (URL from which the app will be downloaded). (* You cannot use a name that has already been used. There is a limit to the number of apps that can be created per day.)
  3. 4.
    Enter the Callback URL (optional: the page that will be displayed after successful authentication). In this sample app, set mymonacaapp://. Please change to the one for your app later. This Callback URL is also required when implementing the app.
  4. 5.
    Select the Settings tab and from App permissions, grant Read and Write permissions. If you do not tweet from the app, only allow Read permission.
  5. 6.
    Select the Settings tab and from Authentication, enable 3-legged OAuth.

Import plugin

We will use the InAppBrowser plugin and a third-party advanced-http plugin for single sign-on and use the oauth-signature library to create the signatures needed for OAuth.
  1. 1.
    From the Monaca Cloud IDE, select Settings → Manage Cordova Plugins.
  2. 2.
    Enable the InAppBrowser plugin.
3. Click the button "Import Cordova Plugin", check "Specify URL or package name", enter cordova-plugin-advanced-http for the package name, and click the OK button.

Import JS components

  1. 1.
    From Monaca Cloud IDE, select Settings → Add / Remove JS / CSS Components.
  2. 2.
    Search by typing oauth-signature-js in the component search form. Install oauth-signature-js from the search results. After that, select components/oauth-signature-js/dist/oauth-signature.js in the selection of the load target and save it. Please note that the oauth-signature.js library is BSD-3-Clause, so please be careful when distributing the source code and binary code of the application.

App description

File organization

File
Description
index.html
App screen page
css/style.css
App stylesheet
js/app.js
JavaScript file that performs various processing when the application is executed

HTML description

index.html

1
<!DOCTYPE HTML>
2
<html>
3
<head>
4
<meta charset="utf-8">
5
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
6
<meta http-equiv="Content-Security-Policy" content="default-src * data: gap: content: https://ssl.gstatic.com; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
7
<script src="components/loader.js"></script>
8
<link rel="stylesheet" href="components/loader.css">
9
<link rel="stylesheet" href="css/style.css">
10
<script src="js/app.js"></script>
11
12
</head>
13
<body>
14
<h2>Twitter Sample</h2>
15
<div>
16
<button onclick="connect()">Connect !</button>
17
<p>Your Id:
18
<span id="tw-id"></span>
19
</p>
20
<p>Your Name:
21
<span id="tw-name"></span>
22
</p>
23
<hr>
24
<button id="showMe" onclick="showMe()">Show Me</button>
25
<p>Your Info:
26
<span id="tw-profile"></span>
27
</p>
28
<img id="tw-profile-image" class="profile">
29
<hr>
30
<p>
31
<textarea id="tweetText" rows=5 cols=40>Hello</textarea>
32
</p>
33
<button id="tweetBtn" onclick="sendTweet()">Send Tweet</button>
34
</div>
35
</body>
36
</html>
Copied!
This page is the application screen.
This page is roughly divided into 3 blocks. Each block is separated by <hr> tags
  1. 1.
    Login block:
    There is a button to move to the Twitter login screen and a component that displays the user ID and user name (screen name) after login.
  2. 2.
    Profile block:
    There is a button to get the profile of the logged-in user and a component to display it after a successful acquisition.
  3. 3.
    Tweet block:
    There is a text area and a button to tweet.

JavaScript description

app.js

1
const apiKey = '[Consumer Key(API key)]';
2
const secretKey = '[Consumer Secret (API key secret)]';
3
const callbackURL = '[Registered callback URL (scheme)]';
4
5
const signatureMethod = "HMAC-SHA1";
6
const version = "1.0";
7
8
const requestTokenURL = "https://api.twitter.com/oauth/request_token";
9
const loginURL = "https://api.twitter.com/oauth/authorize"
10
const accessTokenURL = "https://api.twitter.com/oauth/access_token";
11
const updateURL = "https://api.twitter.com/1.1/statuses/update.json";
12
const usersShowURL = "https://api.twitter.com/1.1/users/show.json";
13
14
let model = {};
15
16
function percentEncode(str) {
17
return encodeURIComponent(str).replace(/[!'()*]/g, char => '%' + char.charCodeAt().toString(16));
18
}
19
20
function getNonce() {
21
const array = new Uint8Array(32);
22
window.crypto.getRandomValues(array);
23
return Array.from(array).map(uint => uint.toString(16).padStart(2, '0')).join('');
24
}
25
26
function oauthSend(url, method, accessTokenSecret, data, oauth_params, cb) {
27
const timestamp = (Math.floor(Date.now() / 1000)).toString(10);
28
const parameters = Object.assign(
29
{},
30
oauth_params,
31
{
32
oauth_nonce: getNonce(),
33
oauth_signature_method: signatureMethod,
34
oauth_timestamp: timestamp,
35
oauth_version: version
36
},
37
data
38
);
39
const signature = oauthSignature.generate(method.toUpperCase(),
40
url,
41
parameters,
42
secretKey,
43
accessTokenSecret
44
);
45
const authorizationHeader = "OAuth " + Object.keys(parameters).map((key) => {
46
return percentEncode(key) + '="' + percentEncode(parameters[key]) + '", '
47
}).join('') + 'oauth_signature=\"' + signature + '\"';
48
49
const urlWithParams = method.toUpperCase() === "GET" ?
50
url + "?" + Object.keys(data).map(function(k) {
51
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
52
}).join('&') : url;
53
54
cordova.plugin.http.sendRequest(urlWithParams, {
55
method: method,
56
headers: {'Authorization': authorizationHeader},
57
data: data,
58
serializer: null
59
}, (res) => {
60
cb(res);
61
}, (error) => {
62
alert(error.error);
63
});
64
}
65
66
function connect() {
67
oauthSend(requestTokenURL, 'post', "", {}, {
68
oauth_callback: callbackURL,
69
oauth_consumer_key: apiKey,
70
}, function (res) {
71
openLoginDialog(res.data);
72
});
73
}
74
75
function openLoginDialog(res) {
76
const oauth = res.split('&')[0];
77
const url = loginURL + "?" + oauth;
78
const ref = cordova.InAppBrowser.open(url, "_blank", 'location=yes,beforeload=get');
79
ref.addEventListener('beforeload', beforeLoad(ref));
80
}
81
82
function beforeLoad(ref) {
83
return function (event, cb) {
84
if (event.url && event.url.startsWith(callbackURL) ) {
85
const url = new URL(event.url);
86
const params = Array.from(url.searchParams.entries()).reduce(
87
function (acc, cur) {
88
acc[cur[0]] = cur[1];
89
return acc;
90
} , {}
91
);
92
ref.close();
93
getAccessToken(params);
94
} else {
95
cb(event.url);
96
}
97
};
98
}
99
100
function getAccessToken(params) {
101
oauthSend(accessTokenURL, 'post', "", {}, {
102
oauth_verifier: params.oauth_verifier,
103
oauth_token: params.oauth_token,
104
oauth_consumer_key: apiKey,
105
}, function (res) {
106
const params = Array.from(new URLSearchParams(res.data).entries()).reduce(
107
function (acc, cur) {
108
acc[cur[0]] = cur[1];
109
return acc;
110
} , {}
111
);
112
document.getElementById('tw-id').innerHTML = params.user_id;
113
document.getElementById('tw-name').innerHTML = params.screen_name;
114
model.oauth_token = params.oauth_token;
115
model.oauth_token_secret = params.oauth_token_secret;
116
model.user_id = params.user_id;
117
});
118
}
119
120
function sendTweet() {
121
const text = document.querySelector("#tweetText").value;
122
oauthSend(updateURL, 'post', model.oauth_token_secret, { "status": text }, {
123
oauth_token: model.oauth_token,
124
oauth_consumer_key: apiKey
125
}, function (res) {
126
alert("Tweet しました");
127
});
128
}
129
130
function showMe() {
131
oauthSend(usersShowURL, 'get', model.oauth_token_secret, { "user_id": model.user_id }, {
132
oauth_token: model.oauth_token,
133
oauth_consumer_key: apiKey
134
}, function (res) {
135
const profile = JSON.parse(res.data);
136
document.querySelector("#tw-profile").innerHTML =
137
"name: " + profile["name"] + "<br>" +
138
"screen_name: " + profile["screen_name"] + "<br>" +
139
"location: " + profile["location"] + "<br>" +
140
"description: " + profile["description"] + "<br>";
141
document.querySelector("#tw-profile-image").src = profile["profile_image_url_https"].replace("_normal", "");
142
});
143
}
Copied!
In the first three lines of the file, set the API key (consumer key), API key secret (consumer secret), and callback URL you obtained from the Twitter Developer account.
1
const apiKey = '[Consumer Key(API key)]';
2
const secretKey = '[Consumer Secret (API key secret)]';
3
const callbackURL = '[Registered callback URL (scheme)]';
Copied!
Tap the Connect button to display the authentication screen.
After a successful login, the access token and user ID are stored in the variable model. In this sample app, there is no log-out function, so you need to kill the app from the task to cancel the login status.
Then tap the Show Me button to see the logged-in user information and the icon. Furthermore, when you tap the Send Tweet button, the message entered in the text form will be posted to Twitter.
If you check "Remember me" on the Twitter login screen, the authorization screen will be displayed in the logged-in state without entering the account and password from the next time. If you want to log out from Twitter, please sign out from the icon on the upper right of the authorization screen.
In this app, the login information (access token) is temporarily stored in the variable model, so the login information will be lost when the app is restarted. If you want to stay logged in, save your access token and user ID in a persistent location such as localstorage.
Last modified 4mo ago