How to immediately get id token from google play services Unity Plugin - c#

I'm using https://github.com/playgameservices/play-games-plugin-for-unity plugin to sign in user with his google account , and then i want to get Id Token and send it to my server and register an account for this user in my own database.this is my code to get Id token :
PlayGamesPlatform.Instance.Authenticate(success =>
{
if (success)
{
Debug.Log("Id Token :");
Debug.LogFormat("{0}", PlayGamesPlatform.Instance.GetIdToken());
Debug.Log("End Of Id Token");
}
});
The problem is the first time it prints just empty string , when i call this for the second time (or a moment later) it prints the token. I want to get token immediately or with a callback to make sure that token is recieved .
How to make sure that token is recieved? is there any callback for this?
Thanks

They changed the plugin in new version and now
PlayGamesPlatform.Instance.GetIdToken(Callback)
has a callback function.

If you want to identify a user on your own web service it would be better to use the server auth code. Send this to your server and get the user identity via jwt from google.
GooglePlayGames.OurUtils.PlayGamesHelperObject.RunOnGameThread(() => {
PlayGamesPlatform.Instance.GetServerAuthCode((CommonStatusCodes status, string code) =>
{
Debug.Log("Status: " + status.ToString());
Debug.Log("Code: " + code);
});
});

Related

Can I get Autodesk 3-legged auth without user input

Is it possible to get a 3-legged auth without user input ?
https://aps.autodesk.com/en/docs/oauth/v2/tutorials/get-3-legged-token/
I have the below code which triggers the web browser to ask for login and press "allow"
button.
I can't run autoamted tasks like this, is there a way to call the API in adeffrent way
in order to pass my credentials and get authorised programmatically ??
public async Task<string> GetCode()
{
var requesturl = $"https://developer.api.autodesk.com/authentication/v1/authorize?response_type=code&client_id={client_id}&redirect_uri={redirecturl}&scope=data:create%20data:read%20data:write";
Process.Start(new ProcessStartInfo(requesturl) { UseShellExecute = true });
listener = new HttpListener();
listener.Prefixes.Add(url);
listener.Start();
Console.WriteLine("Listening for connections on {0}", url);
// Handle requests
Task<string> listenTask = HandleIncomingConnections();
this.code = listenTask.Result;
GetToken();
// Close the listener
listener.Close();
return code;
}
In order to access private user data you need the permission of the user to access it. The way you request permission is with the oauth2 consent screen this is standard part of Oauth2.
So no you cant automate that. AutoDesk-forgue does return a refresh token as part of its oauth2 flow.
What you can do is request authorization once store your refresh token and use the refresh token to request a new access token whenever you need to access the api again.
In this way your automation will run just fine without you.

How to add state management in Web Chat BOT created with water fall dialog's using C# MS BOT framework SDK V4?

I have Chat Bot created using C# SDK V4 and it has multiple water fall dialog classes each for performing specific action when a certain option is selected. The BOT has authentication also embedded using Oauth Prompt.
Channel: Web Channel
SDK: SDKV4
Language: C#
Now, I want to have the state management handled or kept in the water fall dialog as the example i see is on top of normal echo bot and if i implement the same lines on my existing bot having water fall dialog it is not working.
Coming to reason why i want state management as After authenticating the user using Oauth Prompt i am displaying the options based upon the logged in User
Now 2 or more users log in simultaneously or one after the other the other login is getting taken and data of second logged in user is getting displayed for the first user when he toggles back and forth with in the options displayed for selection.
When i logged a query on how to maintain the logged in user or refresh the logged in user i was suggested to have state management technique hence this query on how to do it in a water all dialog.
If state management is not the correct option then can you please let me know how to refresh or maintain the logged in user id?
This suspect the issue is tied to the props you are passing to Direct Line when you start up Web Chat. Referenced under Integrate with Javascript, the docs state:
Assigning userID as a static value is not recommended since this will cause all users to share state. Please see the API userID entry for more information.
When you make a call to generate a token, the userID (which should be unique to the user) should be passed along at that point, else you will run into issues of shared state.
Here is a bit of the code I run for accessing a local API that gets and returns a direct line token. As you can see, the userID is passed in the request which is then baked into the token when returned.
// Listen for incoming requests.
server.post('/directline/token', (req, res) => {
// userId must start with `dl_`
const userId = (req.body && req.body.id) ? req.body.id : `dl_${ Date.now() + Math.random().toString(36) }`;
const options = {
method: 'POST',
uri: 'https://directline.botframework.com/v3/directline/tokens/generate',
headers: {
Authorization: `Bearer ${ process.env.directLineSecret }`,
'Access-Control-Allow-Origin': '*'
},
json: {
user: {
ID: userId
}
}
};
request.post(options, (error, response, body) => {
if (!error && response.statusCode < 300) {
res.send(body);
console.log('Someone requested a token...');
} else if (response.statusCode >= 400 && response.statusCode < 500) {
res.send(response.statusCode);
} else if (response.statusCode >= 500) {
res.status(response.statusCode);
res.send('Call to retrieve token from DirectLine failed');
}
});
});
Hope of help!

Facebook API get public profile wall posts

I'm making a small widget in c# to get the posts from a public facebook page/profile.
I believe you have to get a access token each time you make a request to the api?
I'm confused as to which access token I need and what url request string to use.
This is what I'm using currently but it brings back an unexpected looking key.
access_token=112121212121212|NxG_8djeufhfywhduEjaeU4J-lh4
(I've typed in random characters as an example of the structure).
string response = "https://graph.facebook.com/oauth/access_token?client_id=" + facebook_AppID + "&client_secret=" + facebook_AppSecret + "&grant_type=client_credentials";
string accesstoken = RequestResponse(response);
Then when I use that code to get the posts from a wall, using:
string urlGetFeed = "https://graph.facebook.com/thepagename?fields=access_token=" + accesstoken2 + ",posts.fields(message,picture)";
I get a ERROR : The remote server returned an error: (400) Bad Request. Error.
For the feed of a Facebook Page, you only need an App Access Token, which is easy to get:
APP-ID|APP-SECRET
For example:
string urlGetFeed = "https://graph.facebook.com/thepagename/feed?access_token=" + [app-id] + "|" + [app-secret];
Also, the Access Token is not a value of "fields", it´s a separate parameter.
The URL you should use is this:
https://graph.facebook.com/[THE_FACEBOOK_ID]/[WHAT_YOU_WANT]?access_token=[YOUR_ACCESS_TOKEN]&limit=[THE_LIMIT]
The first part access the Facebook graph.
The second part is the Facebook Id that you want.
The third part is the thing that you want from the Facebook Id that you entered (posts, feed, activities, etc). Here you must be sure that the Access Token has the permissions for what you want to get.
The fourth part is the Access Token that you get and the limit (if you don't set the limit the default limit from Facebook will be used).
Beware of the access token that you-re getting with the first line of code that you posted. That line will give you a short live access token. You should interchange the short live access token here:
https://graph.facebook.com/oauth/access_token?client_id=[YUOR_CLIENT_ID]&client_secret=[YOURCLIENT_SECRET]&grant_type=fb_exchange_token&fb_exchange_token=[THE_SHORT_LIVE_ACCESS_TOKEN]
EDIT:
What you should do is to include the FB Connect script:
<script type='text/javascript' src='http://connect.facebook.net/en_US/all.js#xfbml=1'</script>
and then use this function to take the user to the FB login (if it's not logged in) and then to the authorize page:
function createAccessToken()
{
FB.init({appId: '[YOUR APP ID]', status: true, cookie: true});
FB.login(function(response)
{
if (response.status == 'connected')
{
if (response.authResponse.accessToken)
{
var token = response.authResponse.accessToken;
}
else
{
alert('You must grant the permissions for this plugin or will not work.');
}
}
else
{
alert('You must be logged in to Facebook to grant permissions.');
}
}, { scope: 'read_stream' }); }
The token variable inside that function will contain the short lived access token to exchange for the long lived one here:
https://graph.facebook.com/oauth/access_token?client_id=[YOUR_CLIENT_ID]&client_secret=[YOURCLIENT_SECRET]&grant_type=fb_exchange_token&fb_exchange_token=[token]
Once you get that token go here to get what you want:
https://graph.facebook.com/[THE_FACEBOOK_ID]/[WHAT_YOU_WANT]?access_token=[YOUR_ACCESS_TOKEN]&limit=[THE_LIMIT]

Facebook login secure?

I want to let people to log in with "Facebook login".
but, I wonder if it is secure enough, or I'm just doing it wrong.
What I'm getting back after a successful login is the user data, with the facebook_id, which I'm inserting to the DB passed by a JavaScript reuest to the server via handler since I'm using asp.net.
But, what I think that by a malicious use, one can change that data. and insert rubbish to the server, or even insert different facebook_id.
So I wonder if the "Facebook login" is secure enough to use, or that I'm doing it wrong.
I thought about other option to pass that client data to the server - by postback the server with a hidden runat=server textboxes but still, malicious use can change those textboxes. I've read here about the option to let the users add password to their Facebook username but it sounds a bit not user-friendly.
Am I right? is that a way to do it more secure? Is there any cookie that Facebook put on the client browser that I can read from the server? as though a lot of websites use this "Facebook login" there might be another way that I didnt think about...
Pass the access token up to the server (or check for it from the cookie Facebook sets) and then have the server call https://graph.facebook.com/me?access_token=... and get the Facebook ID that way. You can get the access_token by calling FB.getLoginStatus from the javascript sdk.
You can use oauth to transfer this operation to server side.
Have a look at this blog post:
http://you.arenot.me/2010/09/28/facebooks-graph-api-and-asp-net/
It is important to make an independent call from the server, especially if you are storing their facebook user id in a database or something. That way, you know whether or not it is valid.
First, after calling the FB.init function in the Facebook Javascript SDK, you want to get the user's access token and facebook user id via the Javascript SDK similar to this:
FB.getLoginStatus(function (response)
{
if (response.status === 'connected')
{
var token = response.authResponse.accessToken;
var facebookUserID = response.authResponse.userID;
}
});
Second, once you got a token and facebook user ID, you will want to pass those variables to your server. If you are using WCF or some other form of web service along with JSON.NET, you could create a method such as this:
[WebInvokeAttribute(BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContractAttribute]
public Stream AuthenticateFacebook(string facebookUserId, string token)
{
var json = new WebClient().DownloadString(string.Format("https://graph.facebook.com/me?access_token={0}", token));
JObject parsedJson = JObject.Parse(json);
//Ensure that there isn't a random Facebook server error
if (parsedJson["error"] != null)
{
throw new FaultException("Error parsing Facebook token.");
}
//Ensure the facebook user ID passed in via the client matches the one received from the server.
if (Convert.ToString(parsedJson["id"]) != facebookUserId)
{
throw new FaultException("Facebook login ids do not match. Something fishy is going on...");
}
//Now you know you have a valid facebook login id. Do your database stuff or whatever else here.
}
You now have validated that the user is who they say they are.

Facebook access token only valid for user that created the facebook application

I have some JavaScript that logs in a Facebook user and saves the access token to a database:
window.fbAsyncInit = function () {
FB.init({
appId: '<%=FaceBookApplicationId() %>',
status: false, // check login status
cookie: true,
oauth: true
});
};
function facebookLogin() {
FB.login(function(response) {
if (response.authResponse) {
__doPostBack('__Page', 'FacebookDeliveryButton: ' + JSON.stringify(response.authResponse));
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: 'offline_access,read_stream,publish_stream,user_photos' });
}
A button click fires facebookLogin() which logs in a facebook user, getting a facebook session that includes an access token, which I JSON serialize and post to the server. The server then saves this access token to the database table FacebookDeliveryQueue.
I have a Windows service running that periodically queries the FacebookDeliveryQueue table and attempts to post on a user's wall using the access token we saved earlier:
IQueryable<FacebookDeliveryQueue> toSend = objectContext.FacebookDeliveryQueues.Where(p => !p.IsDelivered);
foreach (FacebookDeliveryQueue facebookDeliveryQueueItem in toSend)
{
string facebookAccessToken = facebookDeliveryQueueItem.Cart.FacebookAccessToken;
string facebookRecipientId = facebookDeliveryQueueItem.Cart.FacebookRecipientId;
var client = new FacebookClient(facebookAccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = facebookDeliveryQueueItem.Cart.CustomMessageBody;
client.Post(facebookRecipientId + "/feed", parameters);
}
My problem is, this ONLY works with access tokens from the user that created the facebook application. E.g.
Success:
I, the creator of this application, log in and pick one of my friends to send a message to, this info is saved to the database, the service runs, my message is posted to my friend's wall.
Failure:
I log in on my dummy test account (approving the app permissions on this account), pick one of my dummy test account's friend, this info is saved to the database, the service runs and throws an invalid access token error.
Any ideas why?
Update: Switched to Oauth login -- no change. Still getting "(OAuthException) Invalid access token signature." when attempting to post to friend's wall.
Looks like you're using facebook's old login methods, which they recently just turned off, so your old access tokens aren't valid anymore? And your javascript isn't generating the right kind of token. Read the latest version of the FB.login documentation for more info on what changes you need to make. Specifically,
pass oauth: true to the FB.init call
check for response.authResponse instead of response.session now.
Also, check that your app isn't in "sandbox mode". Go to the app settings page and click on "advanced". Sandbox mode makes it so that only developers can use the app.
The persistence to the database was silently trimming the access token to 75 characters, which in the case of my own user, was enough (small user id because it's an old account) -- but five characters too short in the case of my test account which has a very large user id.
Woops.

Categories

Resources