How do I Implement twitter Oauth into my Google chrome extension - twitter

I figured out how to get the sign in button and redirect through php code. BUT, Chrome Dev only allows client side code. How do I get the log in with twitter with client side code for my Chrome app?
is there a way to run php code for a chrome app?

Here is another alternative to CodeBird for authenticating a twitter user in a Chrome extension.
The key with this approach is to provide Twitter with a legitimate domain for the callback URL for your app. Then, use content scripts to inject a script onto that same domain. That script will parse the query string of the URL to get the tokens and send those tokens in a message to your extension's background script. Your background script will take the tokens and then perform the third leg of the oauth process, which will finally get you the oauth token and oauth token secret.
Here is a brief example:
in your manifest.json, make sure your content script matches the same domain that you put in your twitter app settings callback URL:
"content_scripts": [{
"matches": ["https://andyjiang.com/*"],
"js": ["js/session.js"]
}]
Then, in your js/session.js file, have this sort of logic:
chrome.runtime.sendMessage({type: 'auth', session:
window.location.search.substr(1)}, function(response) {
window.open('', '_self', '');
window.close();
});
In your background script, have some logic that listens for the message, gets the token, and uses Twitter's API for the third leg of the oauth process to finally get the oauth token and oauth token secret, which you can then save in localStorage or chrome.storage.
Here is sample code of the logic:
https://github.com/lambtron/chrome-extension-twitter-oauth-example
Hope that helps!

You can use the Chrome Identity API for this. Check out Non-Google account authentication for simple instructions on making a request using the launchWebAuthFlow API function.
Previously, there were client side libraries for implementing the OAuth flow, such as oauth2-extensions described here, but thankfully this is not required anymore .
Update
I've been playing around trying to get an example working for Twitter, but haven't quite got there. It appears that Twitter doesn't have an API endpoint that matches the OAuth2 URL that is expected. I think in the case of Twitter, you may have to use OAuth 1.0a instead, which would require a library after all. I found one called CodeBird. I will try and investigate further though.
Example using Chrome Identity API to Authorise Instagram
You need to register the client to your provider with https://abcdefghijklmnopqrstuvwxyzabcdef.chromiumapp.org/intagram_cb, where 'abcdefghijklmnopqrstuvwxyzabcdef' is replaced with your extension ID and intagram_cb is name for a path to be able to distinguish between other providers you wish to authenticate with within the extension. If you only have one, then you can omit it.
Add provider to the permissions property in the manifest.json file:
"permissions": [
"*://*.instagram.com/*"
]
Get access token. You obtain the client_id token from your provider account:
var redirect_uri = chrome.identity.getRedirectURL("intagram_cb");
var client_id = "123456789012345";
var auth_url = "https://instagram.com/oauth/authorize/?" +
"client_id=" + client_id + "&" +
"response_type=token&" +
"redirect_uri=" + encodeURIComponent(redirect_uri);
chrome.identity.launchWebAuthFlow({'url':auth_url, 'interactive': true},
function(redirect_url) {
// extract the token from this url and use it for future requests
var accessToken = redirect_url.substring(redirect_url.indexOf("=") + 1);
}
});

Related

Google Identity Services SDK - authorization code model in popup mode - how to request refresh/access tokens?

I'm trying to implement the authorization code model using the Google Identity Services SDK, as described in Use Code Model. I would like to use the popup mode.
I managed to initialize the code client and receive an auth code with this Javascript code:
tokenClient = google.accounts.oauth2.initCodeClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '', // defined later
ux_mode: 'popup',
})
...
tokenClient.requestCode({prompt: 'consent'});
When I receive the auth code in my callback, I relay it to an endpoint on my platform, as described in Step 5: Exchange authorization code for refresh and access tokens and I try to exchange the auth code for a refresh and access token in Python:
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secret.json',
scopes=scopes,
state=state
redirect_uri=redirect_uri
)
flow.fetch_token(code=code)
The problem is that I use this code with an empty redirect_uri, I get an error "missing redirect_uri parameter". If I specify a redirect URL defined in Google Cloud Console, I get an error "redirect_uri mismatch". And if I try to use the same redirect_uri as the one sent in the initial popup request (Google seems to use storagerelay://... in this case), I get an error that "it doesn't comply with Google Oauth2 policy".
It appears that in any authorization flow when you get an authorization code on the client side and then pass that to your server for token exchange you have to use the string literal "postmessage" as your setting for redirect_uri.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secret.json',
scopes=scopes,
state=state
redirect_uri="postmessage"
)
flow.fetch_token(code=code)
This very important fact seems to be curiously absent from the documentation from most of the google client libraries, but it works for me. Hope this helps!

What is the redirect_uri in Alexa Skill Activation API?

Background
I'm implementing Alexa's App-to-App Account Linking Flow, and I'm stuck on Step 6 - enabling the skill using Alexa's Skill Activation API.
Concretely, I am not sure what value to supply to the redirect_uri POST field. In the docs, the following description is provided:
The redirect_uri parameter that was included in the authorization request to your OAuth 2.0 server to obtain the user's authorization code. This enables Amazon to retrieve access tokens from your token server. This URL must be opaque to Amazon.
My understanding is that Alexa wants to exchange an existing authorization code for an access token, but I don't know how Alexa is trying to accomplish this "under the hood" and my current approach throws a 400 error.
Error Message
[status] 400
[response] {"message":"Could not contact provider of account linking credentials"}
Notes
My app uses Firebase authentication, and creates accounts for users via federated login with Google and Facebook. Thus, Google and Facebook redirect back to my native app (React Native).
I do not have a universal link; instead in my account-linking flow,
the Alexa app redirects users to an html page that redirects to my app using its custom schema.
When a user signs into my app from Alexa, Alexa redirects them from my login page back to the Alexa app. In this case, the Alexa universal link is the redirect url.
When a user signs into Alexa from my app (app-to-app linking), The Alexa app redirects them to my app. My app is the redirect url.
I have tried using my app's [faux] "universal link" as the redirect url, to no avail. There are no other redirects in my login flows. What is this url supposed to be?
NB: I have a endpoint for exchanging an auth_code for an access_token. The token is returned in the body; there's no redirect with the access_token appended to the redirect_url.
Example Skill Activation (my React Native app):
async enableSkill() {
try {
let response = await fetch(`https://api.amazonalexa.com/v1/users/~current/skills/${this.skillId}/enablement`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.alexaAccessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
stage: 'development', // or live
accountLinkRequest: {
redirectUri: Linking.makeUrl(), // <--- unsure
authCode: this.myAppAuthCode, // <-- auth code from my system, not Alexa's
type: "AUTH_CODE"
}
})
});
return response.json();
} catch (err) {
throw new Error(err);
}
}
I think it is not possible to use different OAuth Server like Google and Facebook together. I am not sure if it is possible to use firebase as OAuth Server.
In the account linking tab of the skill, you have to enter the details of the OAuth server you want to use and in the accountLinkRequest you must enter the redirectUri which you used for the OAuth Login with this server.
When you have your own OAuth server make sure it is running on port 443. It took me hours to find out that it is not working with Port 3000 which my Node.js backend used.
According to the developer documentation The redirect_uri you are asking about is a parameter that was included in the authorization request to your OAuth 2.0 server to obtain the user's authorization code. This enables Amazon to retrieve access tokens from your token server. You must set this URL in the developer console of your skill like that:

Forge Autodesk - 2 legged OAuth

We have an inquiry from our client, to enable Autodesk Model Viewer from within our App. The first step is to implement OAuth2 authentication (2 legged). I followed Forge Autodesk tutorials, but this is completely new to me, and I cannot configure that to work. I do http request (using jQuery) from our App, passing client_id and client_secret, grant_type and a scope. When looking on the developer menu (F12) - I can see that request is hitting their server and returns with the access_token, expire time, authorization "Bearer" with the status 200. So far so good.
I understand that now I need to make a call back to the API and pass this access_token I received. And here is where I lost: console shows me error, Cross origin ... And the success part of http request is not fireing (in http request success part I'm trying to redirect user to the Model Viewer url + access_token we just received). But it is never fires. Was digging forums and tutorials but can't find any good sample or explanation what I'm doing wrong. Below is my code example:
$.post("https://developer.api.autodesk.com/authentication/v1/authenticate",
{
client_id: 'here_is_a_client_id',
client_secret: 'here_is_a_client_secret',
grant_type: 'client_credentials',
scope: 'viewables:read'
},
function(data, status){
console.log("Data: " + data);
window.location.href = 'https://viewer.autodesk.com/id/here_is_a_long_id_number&Authorization=Bearer&' + data;
});
Any help highly appreciated. Also, I was trying to follow Autodesk tutorials using Node.js, but again, after seeing that access_token get back from their server, can't make a callback and attach this access_token to it. New to all these Authorization/Authentication/Tokens so can't figure out the way it works. Thanks in advance.
I could advice you how to avoid this Cross Origin error, but it is critical not to and very dangerous to authorise your application on the client side. Exposing you client secret key will give everyone the right to access your account and spend cloud credits on your behalf. And access all your content. That is the reason you do should not have that approach.
You should never expose the client secret, neither an read/write scoped access token on a client, those should resides on the server, and server only. The only access token you could eventually see on the client should be a viewables:read scoped token only. And even when using a viewables:read token, I prefer to use a proxy instead myself (see here).

Oauth2.0 Google API token issue - Error: redirect_uri_mismatch

I have trouble creating a Google API OAuth2.0 token though following all the steps here: [OAuth2 Authentication](
https://developers.google.com/adwords/api/docs/guides/authentication?authuser=1)
When trying to create the token through the OAuth2.0 playground:
OAUTH 2.0 playground
I end up with this error:
Discussion on similar threads tried to give some guidance but without any luck in my case.
Add google.com in the authorized domain list of your app's OAuth consent screen.
Click on the application for which you want to configure for the next step:
Make sure to also add 'https://developers.google.com' in the Authorized JavaScript origins and 'https://developers.google.com/oauthplayground' in the Authorized redirect URIs[click 'save' below once added]:
You are applying your own client id and client secret to Oauth2 playground you are also using browser credentials.
For browser credentials to work it must be able to return the token to an endpoint that can handle it and that endpoint (Redirect uri) must be registered in the Google Developer console for that project.
if you check your first picture under the check box you clicked
You will need to list the URL https://developers.google.com/oauthplayground as a valid redirect URI in your Google APIs Console's project. Then enter the client ID and secret assigned to a web application on your project below:
Try adding that URL as it says.

invalid_request: The `redirect_uri` parameter does not match a valid url for the application

So I am creating a simple web application using the MEAN stack. I am trying to connect to asana through asana connect using the browser pop-up example. For a simple test I have code that is nearly identical to the example, but I still get the error shown as the title for this question.
I'm not sure what might be going wrong but here is the code.
The authentication is supposed to happen after a button click. The client id, client secret are taken from my account settings on the main website. The redirect uri is also set to http://localhost:3000, so I know for sure that they match.
$scope.signIn = function(){
var client = Asana.Client.create({
clientId: My client id,
clientSecret: my client secret,
redirectUri: 'http://localhost:3000'
});
client.useOauth(
{
flowType: Asana.auth.PopupFlow
});
client.authorize().then(function(){
console.log("log-in success");
}).catch(function(err){
console.log(err);
});
};
For the best user experience and for your application to work properly you want your redirect to accept the incoming HTTP request, parse out the access_token or code (depending on which grant flow) and subsequently render a page for the user.
You can read more about authentication mechanisms on the Asana platform in our documentation

Resources