I am trying to build a Unity application to be deployed with WebGL. I am trying to incorporate Google Sign-In into the application, and so far, this was what I've managed to make work in the Unity WebGL build in Chrome:
User presses on the "Login with Google" button on Unity application, in Tab A.
User is directed to Google Sign In page on another Tab B.
User signs in with Google account, and is redirected to my redirect_uri, which is simply https://localhost, with the auth code parameter.
My question is, is it possible for me to do the following, possible with .jslib files:
Instead of going to redirect_uri on Tab B, instead go back to Tab A without reloading, passing along the auth code.
Building on the line above, have javascript handlers, that:
When auth code is received, initiate request to exchange auth code for the id_token as instructed here.
When id_token is received, call a C# Script function to do further actions with the id_token.
Alternatively, I can set redirect_uri to be an endpoint on my backend server, and perform the auth token -> id_token flow using the Google client SDKs. However, for this approach, I would like to know if i am able to
After the auth token -> id_token flow is completed on the backend server, close the current window, Tab B, and go back to Tab A.
After we’re back on Tab A, redirect Unity to a specific scene (not the login scene anymore, but a home page that users are directed to after they are authenticated).
Would very much appreciate any help i can get :')
EDIT: For better clarity, what I want to achieve is something that FacebookSDK for Unity has done in their FB.LogInWithReadPermissions(). The whole auth code -> access_token flow is seamless, and i get redirected back to the Unity application in Tab A at the end with the access_token.
I managed to find a Javascript solution to achieve my first method. The differences are that because
My application will never be in production
Consistency with my Facebook OAuth implementation,
I used the implicit flow instead of the authorization code flow, despite it being not the recommended way due to security concerns. However, I think you can easily use the authorization code flow, retrieving the authorization code and passing it on to your backend to exchange for an id token. (as far as I know, you cannot use Javascript/XHR requests to do this exchange)
So, the flow is that from my C# script, I call a Javascript function from a .jslib file. Basically, the function detects when the OAuth window has redirected back to my redirect_uri, then gets the access_token parameter from the redirected URI, and calls a C# Script function. From there, you should be able to do whatever you need to do (change scene, send to your backend, etc.). Note that there is a try/catch because there will be errors if you attempt to get information from the Google Sign In pages.
The file is as follows:
mergeInto(LibraryManager.library, {
OpenOAuthInExternalTab: function (url, callback) {
var urlString = Pointer_stringify(url);
var callbackString = Pointer_stringify(callback);
var child = window.open(urlString, "_blank");
var interval = setInterval(function() {
try {
// When redirected back to redirect_uri
if (child.location.hostname === location.hostname) {
clearInterval(interval) // Stop Interval
// // Auth Code Flow -- Not used due to relative complexity
// const urlParams = new URLSearchParams(child.location.search);
// const authCode = urlParams.get('code');
// console.log("Auth Code: " + authCode.toString());
// console.log("Callback: " + callbackString);
// window.unityInstance.SendMessage('Auth', callbackString, authCode);
// Implicit Flow
var fragmentString = child.location.hash.substr(1);
var fragment = {};
var fragmentItemStrings = fragmentString.split('&');
for (var i in fragmentItemStrings) {
var fragmentItem = fragmentItemStrings[i].split('=');
if (fragmentItem.length !== 2) {
continue;
}
fragment[fragmentItem[0]] = fragmentItem[1];
}
var accessToken = fragment['access_token'] || '';
console.log("access_token: " + accessToken);
child.close();
// Invoke callback function
window.unityInstance.SendMessage('Auth', callbackString, accessToken);l
}
}
catch(e) {
// Child window in another domain
console.log("Still logging in ...");
}
}, 50);
}
});
Then, in my C# script, I call this function using the following:
public class GoogleHelper : MonoBehaviour
{
[DllImport("__Internal")]
private static extern void OpenOAuthInExternalTab(string url, string callbackFunctionName);
// ...
public void Login(string callbackFunctionName) {
var redirectUri = "https://localhost";
var url = "https://accounts.google.com/o/oauth2/v2/auth"
+ $"?client_id={clientId}"
+ "&response_type=token"
+ "&scope=openid%20email%20profile"
+ $"&redirect_uri={redirectUri}";
OpenOAuthInExternalTab(url, callbackFunctionName);
}
// ...
}
Of course, this is super hacky, and I'm not very familiar with Javascript and so don't really know the implication of the code above, but it works for my use case.
Related
Integrate Salesforce registration page with VanillaJS, getting the error - No matching state found in storage
We are redirecting the user to Salesforce registration page when Create Account button is created.
Once the User registers in Salesforce, the user is redirected to our site but we are getting this error. ('No matching state found in storage').
We tried the below solution but still getting the same error.
As I stated in my answer, the oidc client maintains state information
in the local storage so that it can verify that it got the response
back from the intended server. You can mimic this by generating a
secure random string and saving it in localStorage. Do this before
sending a request to your auth server to register a new user.
Reference- Integrate third party login in from my registration page with IdentityServer4 and Angular 6 - 'No matching state found in storage'
Is there a function related to creating registration? How to fix this issue?
Thanks.
Appreciate your help.
After spending days on this issue. Finally found the workaround as registration is not a feature of OIDC.
To overcome this issue, need to follow the Sign In process same as for Sign Up process, created the startSignupMainWindow method same as startSigninMainWindow and passing the signUpFlag:true as shown below in code.
/* This function is written to mimic the oidc library sign in process flow */
function startSignupMainWindow() {
var someState = {
message: window.location.href,
signUpFlag: true
};
mgr.signinRedirect({
state: someState,
useReplaceToNavigate: true
}).then(function() {
log("signinRedirect done");
}).catch(function(err) {
log(err);
});
}
Reading the signUpFlag:true in UserManager.js and swapping the Salesforce Sign In page Url with Sign Up page url and calling the Register function in Code.
UserManager.js(oidc - client - dev - js / src / UserManager.js)
//UserManager Customised Code :
return this.createSigninRequest(args).then(signinRequest => {
Log.debug("UserManager._signinStart: got signin request");
navigatorParams.url = signinRequest.url;
navigatorParams.id = signinRequest.state.id;
if (signinRequest.state._data.signUpFlag) {
register(signinRequest.state._id, signinRequest.state._code_challenge);
} else {
return handle.navigate(navigatorParams);
}
})
The below code is Register function written in code.
/* This function is written to send the code_challenge to salesforce server so that
salesforce server holds the code challenge and used to verify the further requests(token-request)
against the code_challenge it received initially.*/
//Customised register function written outside the library (Inside our App):
function register(_id, code_challenge) {
var date = new Date();
var baseUrl = "SALESFORCE_URL/login/SelfRegister?expid=id";
var expId = "id";
var userPage = encodeURIComponent(window.location.href);
var appDetails = "response_type=code&" +
"client_id=CLIENT_ID" +
"client_secret=CLIENT_SECRET&" +
"redirect_uri=CALLBACK_URL&" +
"state=" + _id + "&code_challenge=" + code_challenge + "&code_challenge_method=S256&response_mode=query";
var encodedapp = encodeURIComponent(appDetails);
var startUrl = "/services/oauth2/authorize/expid?" + encodedapp;
var signUpUrl = baseUrl + "&startURL=" + startUrl;
window.open(signUpUrl, "_self");
};
I'm writing a Google Hangouts Chat bot with Google Apps Script. The bot authenticates with a third party service with the apps script OAuth2 library. As documented in this How-To, when a message is received by the bot but authentication with the third party service is required, the bot sends a special REQUEST_CONFIG reply to Chat containing the configCompleteRedirectUrl.
var scriptProperties = PropertiesService.getScriptProperties();
function onMessage(event) {
var service = getThirdPartyService();
if (!service.hasAccess()) {
return requestThirdPartyAuth(service, event);
}
Logger.log('execution passed authentication');
return { text: 'Original message ' + event.message.argumentText };
}
function getThirdPartyService() {
var clientId = scriptProperties.getProperty('CLIENT_ID');
var clientSecret = scriptProperties.getProperty('CLIENT_SECRET');
return OAuth2.createService('ThirdPartyApp')
// Set the endpoint URLs.
.setAuthorizationBaseUrl('https://...')
.setTokenUrl('https://.../oauth/token')
// Set the client ID and secret.
.setClientId(clientId)
.setClientSecret(clientSecret)
// Set the name of the callback function that should be invoked to
// complete the OAuth flow.
.setCallbackFunction('authThirdPartyCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
.setLock(LockService.getUserLock())
// Set the scope and other parameters.
.setScope('...')
.setParam('audience', '...')
.setParam('prompt', 'consent');
}
function requestThirdPartyAuth(service, event) {
Logger.log('Authorization requested');
return { "actionResponse": {
"type": "REQUEST_CONFIG",
"url": service.getAuthorizationUrl({
configCompleteRedirectUrl: event.configCompleteRedirectUrl
})
}};
/**
* Handles the OAuth callback.
*/
function authThirdPartyCallback(request) {
var service = getThirdPartyService();
var authorized = service.handleCallback(request);
if (authorized) {
Logger.log("user authorized");
//https://stackoverflow.com/a/48030297/9660
return HtmlService.createHtmlOutput("<script>window.top.location.href='" + request.parameter.configCompleteRedirectUrl + "';</script>");
} else {
Logger.log("user denied access");
return HtmlService.createHtmlOutput('Denied');
}
}
The service defines a callback authentication function, which in turn sends the browser to the configCompleteRedirectUrl. After this URL has been reached, the original message is supposed to be sent or re-dispatched a second time (see How-To step 7.3).
The authentication callback is successful because the last page displayed in the browser OAuth flow is the one specified in event.configCompleteRedirectUrl. Within the Chat window, the configuration prompt is erased, and the original message is changed to public. However, the original message is not dispatched again. The last log displayed in the apps script console is from the authentication callback event.
Is there something I have done incorrectly that prevents the original message from being dispatched again?
After much back and forth with a Google support team member, it turns out that there is a bug in the Hangouts Chat implementation when run against the V8 Apps Script runtime.
My appsscript.json file had "runtimeVersion": "V8" set. The re-dispatch does not work in this scenario. After I reverted to "runtimeVersion": "STABLE" in appsscript.json and re-deployed my scripts, the re-dispatch started working.
I have connected app created in org 2 with OAuth enabled.
I'm using OAuth2.0 User agent workflow in org1 where I have lightning app.
Upon clicking a button (named auth target org) in lightning component page,
window.open(endpturl,'_self');
var currLoc = window.location.href;
alert ('Curr Loc is: ' + currLoc); //prints the URL from where I clicked button (named auth target org). Expected this statement to be executed after step 7. Hence not able to capture the access token.
Redirects to salesforce authorization/login page.
enter user credential --> click allow access.
Redirects to as per connected app configured callback URL
https://business-momentum-162-dev-ed.cs2.my.salesforce.com/services/oauth2/success#access_token=abc&instance_url=https%3A%2F%2Fdream-innovation-4602-dev-ed.cs40.my.salesforce.com&id=https%3A%2F%2Ftest.salesforce.com%2Fid%2F00D540000009LzUEAU%2F00554000000zjC5AAI&issued_at=1531980498349&signature=abc&scope=id+api&token_type=Bearer
BUT i'm not able to capture the access token as step 4 executed before step 7. Hence not able to capture access token. Please do let me know if there is way to get/capture access token.
client side controller code (**using window object**):
({ AuthTargetOrg : function (component, event, helper) {
var endpturl = 'https://test.salesforce.com/services/oauth2/authorize?response_type=token&client_id=abc123&redirect_uri=https%3A%2F%2Fbusiness-momentum-162-dev-ed.lightning.force.com%2Fservices%2Foauth2%2Fsuccess';
window.open(endpturl,'_self');
var currLoc = window.location.href;
alert ('Curr Loc is: ' + currLoc); // prints home page URL from where I clicked "auth target org" button, rather this statement expected to execute after step 7.
)}
Regards,
PJS
I believe you need to use Apex to handle the redirect of the Oauth dance. I've been struggling with this one myself and the problem is that in a lightning component you can't makes API calls directly to salesforce endpoints, it will throw all kinds of errors. I did however find this code example:
https://balkishankachawa.wordpress.com/tag/oauth-with-lightning/
Basically the solution is to use Apex and Lightning Out. Use Apex to receive your redirect from the Salesforce auth which can in turn get the token and pass it back to your lightning component.
I have an app, that links one service with Google Sheets by OAuth 1.0.
I click "login" in addon menu, send signature and callback domain (current sheet). Then in service I click on button, get request token and it returns me to the specified domain with parameters.
function onOpen(e)
{
Logger.log( SpreadsheetApp.getActiveSpreadsheet().getUrl() );
Logger.log( e.source.getUrl() );
}
But .getUrl() doesn't contain them.
According to >this< I can't use doGet(e) in Sheets and, because of OAuth, I can't use Web App, because I still need to pass these parameters to Sheets.
I tried to get it on client-side by window.top.location.href, but had cross-domain errors.
Question: Can I get it? Or is it impossible?
So, a partial answer to my question:
We need 2 different scripts. The first as Sheets web addon, the second as Web App. Next, we need to implement all the steps presented in the screenshot:
1) After steps 0, 1, 2 Service Provider should redirect us to Helper script (Web App) with the following code:
function doGet(e)
{
var token = e.parameter.oauth_token,
code = e.parameter.oauth_verifier,
response;
if(token && code && Root.setVerificationCode(token, code))
response = "Success";
else
response = 'Error';
return HtmlService.createHtmlOutput(response);
}
Here we retrieving GET parameters and send them to Sheets web addon (Root).
Click Resources -> Libraries and add your addon as library. Root is just an identifier.
2) Sheets addon code:
function setVerificationCode(token, code)
{
var oauth = new OAuth();
if(oauth.getAccessToken(code))
{
// change menu here
return true;
}
else
return false;
}
These are full steps you need to implement OAuth 1.0.
P.S. Now I have problems with changing menu, but it'll be my next question.
I am making a web app that pulls the latest posts from our Facebook page and processes them.
This is all working fine with a hard-coded access token generated from this page.
The problem is that this token expires, so i am looking for a solution to generate a new token every time the page loads or a non-expiring token - (i have read somewhere that non expiring tokens don't exist anymore).
So of course i did some research, here, here and here.
But non of these examples seem to be working.
Before any complaints of some code that i have tried so far, this is my working example - with an expiring access token:
var Facebook = function () {
this.token = 'MYTOKEN';
this.lastPost = parseInt((new Date().getTime()) / 1000);
this.posts = [];
};
Facebook.prototype.GetPosts = function () {
var self = this;
var deffered = $q.defer();
var url = 'https://graph.facebook.com/fql?q=SELECT created_time, message, attachment FROM stream WHERE created_time < ' + self.lastPost + ' AND source_id = 437526302958567 ORDER BY created_time desc LIMIT 5&?access_token=' + this.token + '';
$http.get(url)
.success(function (response) {
angular.forEach(response.data, function (post) {
self.posts.push(new Post(post.message, post.attachment.media, post.attachment.media[0].src, post.created_time, 'facebook'));
});
self.lastPost = response.data[response.data.length -1].created_time;
deffered.resolve(self.posts);
self.posts = [];
});
return deffered.promise;
};
return Facebook;
Any help / suggestion will be greatly appreciated.
First off, it is important to remember that Facebook has just launched the Version 2 of the Graph API. From April 2014 on, if you have issues with your app, you need to tell us when you created it on Facebook Developers (new apps use the Version 2 by default).
In order manage pages, your app needs to have manage_pages permission. Make sure that the user you want to manage fan pages for has authorized you. If your app uses the Version 2, make sure that Facebook (the Facebook staff) has authorized you to ask users that kind of permission, otherwise your app won't work.
Once you get your token, exchange it for a permanent token (or a token with long expiry date). Make sure you use the token of the fan page, not the token of the user.
If instead you want to read the stream of public fan pages, you need an access token with read_stream permissions. This permission needs to be approved by Facebook (see above) and this specific type of permission takes time to approve, if you're using the Version 2 of the Graph API. If you're using the old API (Version 1), you can still do that without pre-approval on Facebook's side.
The URL to ask for the permission to read the stream is as follows: https://www.facebook.com/dialog/oauth?client_id=$YOUR_APP_ID&redirect_uri=$YOUR_URL&scope=read_stream,manage_pages (i've added manage_pages in this case, you may not need it).
That url will prompt for authorization. Once the user has authorized the app, you'll be recirected to the URL you chose, with a code= variable.
At that point, call this other url:
https://graph.facebook.com/oauth/access_token?client_id={$app_id}&redirect_uri=$someurl&client_secret={$app_secret}&code={$code}
You'll get a response that has the access_token=variable in it. Grab that access token, exchange it for a long one, with the following URL:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id={$app_id}&client_secret={$app_secret}&fb_exchange_token={$token_you_have_just_grabbed}
The response will give you a token that lasts for some time. Previously, Facebook had decided to have these "long duration tokens" expire after one month. I have found out, though, that they may have changed their mind: if you put a user token in the debugger, you'll see it never expires.
This is the authorization flow for users who visit with a browser. There's the app authorization flow too. If all you need is a stream from your own Fan page, you want to do the following (with Graph API V.1):
make an HTTP GET request using the following URL:
https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={$app_id}&client_secret={$app_secret}
Use the resulting token to make another HTTP GET call, like so:
https://graph.facebook.com/{$your_page_id}/feed?{$authToken}&limit=10
//ten posts
Decode the json object
You're done.