I'm a refugee from the old Facebook Developer Toolkit porting my app to the newer Facebook C# SDK. I've got the MVC web app side of my solution worked out, but I also have a console application that I run in batch as part of my overall solution. I obtain the offline_access extended permission for all of my users and store the non-expiring session key for later use in my console app.
With the Facebook Developer Toolkit I was able to spin up a Connect Session and REST api using my API Key, API Secret, and the saved user session key and make Facebook api calls.
In the Facebook C# SDK the non-web samples seem to rely on popping up some kind of browser control for interactive user login. That won't work for a console batch application processing users offline.
I've got this far:
string oAuthAccessToken = "{access token}"
var app = new Facebook.FacebookApp(oAuthAccessToken );
// now I can make api calls like this:
dynamic currentPermissionsJson = new ExpandoObject();
currentPermissionsJson = app.Query(string.Format("SELECT publish_stream, offline_access, email from permissions where uid = {0}", {userid}));
var currentPermissions = ((JsonArray)currentPermissionsJson)[0] as IDictionary<string, object>;
and away we go.
I'm just stuck on how to convert my existing stored session keys to Facebook OAuth access tokens. I can see how I can construct POSTs to https://graph.facebook.com/oauth/exchange_sessions with params such as
client_id={my app id}
&client_secret={my app secret}
&sessions={previously stored session keys}
and get the access token back in the response.
But I'm thinking the SDK must offer some method of doing this for me. Or does it?
Unfortunately, we dont have any helpers in the current Facebook C# SDK to exchange the access tokens. I have created an issue and I will try to get it in there shortly. http://facebooksdk.codeplex.com/workitem/5788
For now I wrote up this. Give it a try and let me know how it works:
public class FacebookOAuth
{
public static IEnumerable<ExchangeSessionResult> ExchangeSessions(string appId, string appSecret, params string[] sessionKeys)
{
WebClient client = new WebClient();
var dict = new Dictionary<string, object>();
dict.Add("client_id", appId);
dict.Add("client_secret", appSecret);
dict.Add("sessions", String.Join(",", sessionKeys));
string data = dict.ToJsonQueryString();
string result = client.UploadString("https://graph.facebook.com/oauth/exchange_sessions", data);
return Newtonsoft.Json.JsonConvert.DeserializeObject<ExchangeSessionResult[]>(result);
}
}
public class ExchangeSessionResult
{
[Newtonsoft.Json.JsonProperty("access_token")]
public string AccessToken { get; set; }
[Newtonsoft.Json.JsonProperty("expires")]
public string Expires { get; set; }
}
Related
I downloaded the example below to get an access token from MS Graph and it worked fine. Now I changed the code to get a token from a custom web API. On apps.dev.microsoft.com I registered a client application and an the API.
Client and server registration in AD
private static async Task<AuthenticationResult> GetToken()
{
const string clientId = "185adc28-7e72-4f07-a052-651755513825";
var clientApp = new PublicClientApplication(clientId);
AuthenticationResult result = null;
string[] scopes = new string[] { "api://f69953b0-2d7f-4523-a8df-01f216b55200/Test" };
try
{
result = await clientApp.AcquireTokenAsync(scopes, "", UIBehavior.SelectAccount, string.Empty);
}
catch (Exception x)
{
if (x.Message == "User canceled authentication")
{
}
return null;
}
return result;
}
When I run the code I login to AD via the dialog en get the following exception in the debugger:
Error: Invalid client Message = "AADSTS65005: The application
'CoreWebAPIAzureADClient' asked for scope 'offline_access' that
doesn't exist on the resource. Contact the app vendor.\r\nTrace ID:
56a4b5ad-8ca1-4c41-b961-c74d84911300\r\nCorrelation ID:
a4350378-b802-4364-8464-c6fdf105cbf1\r...
Error message
Help appreciated trying for days...
For anyone still striking this problem, please read this:
https://www.andrew-best.com/posts/please-sir-can-i-have-some-auth/
You'll feel better after this guy reflects all of your frustrations, except that he works it out...
If using adal.js, for your scope you need to use
const tokenRequest = {
scopes: ["https://management.azure.com/user_impersonation"]
};
I spent a week using
const tokenRequest = {
scopes: ["user_impersonation"]
};
.. since that is the format that the graph API scopes took
As of today, the V2 Endpoint does not support API access other than the Microsoft Graph. See the limitations of the V2 app model here.
Standalone Web APIs
You can use the v2.0 endpoint to build a Web API that is secured with
OAuth 2.0. However, that Web API can receive tokens only from an
application that has the same Application ID. You cannot access a Web
API from a client that has a different Application ID. The client
won't be able to request or obtain permissions to your Web API.
For the specific scenario that you are trying to accomplish, you need to use the V1 App Model (register apps on https://portal.azure.com).
In the very near future, V2 apps will be enabled to call other APIs other than Microsoft Graph, so your scenario will be supported, but that is just not the case today. You should keep an eye out on our documentation for this update.
In your (server) application registration in AAD, you need to specify your scopes in the oauth2Permissions element.
You may already have a user_impersonation scope set. Copy that as a baseline, give it a unique GUID and value, and then AAD will let your client request an access token with your new scope.
Background
I am wanting to write a small, personal web app in .NET Core 1.1 to interact with YouTube and make some things easier for me to do and I am following the tutorials/samples in Google's YouTube documentation. Sounds simple enough, right? ;)
Authenticating with Google's APIs seems impossible! I have done the following:
Created an account in the Google Developer Console
Created a new project in the Google Developer Console
Created a Web Application OAuth Client ID and added my Web App debug URI to the list of approved redirect URIs
Saved the json file provided after generating the OAuth Client ID to my system
In my application, my debug server url is set (and when my application launches in debug, it's using the url I set which is http://127.0.0.1:60077).
However, when I attempt to authenticate with Google's APIs, I recieve the following error:
That’s an error.
Error: redirect_uri_mismatch
The redirect URI in the request, http://127.0.0.1:63354/authorize/,
does not match the ones authorized for the OAuth client.
Problem
So now, for the problem. The only thing I can find when searching for a solution for this is people that say
just put the redirect URI in your approved redirect URIs
Unfortunately, the issue is that every single time my code attempts to authenticate with Google's APIs, the redirect URI it is using changes (the port changes even though I set a static port in the project's properties). I cannot seem to find a way to get it to use a static port. Any help or information would be awesome!
NOTE: Please don't say things like "why don't you just do it this other way that doesn't answer your question at all".
The code
client_id.json
{
"web": {
"client_id": "[MY_CLIENT_ID]",
"project_id": "[MY_PROJECT_ID]",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "[MY_CLIENT_SECRET]",
"redirect_uris": [
"http://127.0.0.1:60077/authorize/"
]
}
}
Method That Is Attempting to Use API
public async Task<IActionResult> Test()
{
string ClientIdPath = #"C:\Path\To\My\client_id.json";
UserCredential credential;
using (var stream = new FileStream(ClientIdPath, FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.YoutubeReadonly },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
var channelsListRequest = youtubeService.Channels.List("contentDetails");
channelsListRequest.Mine = true;
// Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
var channelsListResponse = await channelsListRequest.ExecuteAsync();
return Ok(channelsListResponse);
}
Project Properties
The Original Answer works, but it is NOT the best way to do this for an ASP.NET Web Application. See the update below for a better way to handle the flow for an ASP.NET Web Application.
Original Answer
So, I figured this out. The issue is that Google thinks of a web app as a JavaScript based web application and NOT a web app with server side processing. Thus, you CANNOT create a Web Application OAuth Client ID in the Google Developer Console for a server based web application.
The solution is to select the type Other when creating an OAuth Client ID in the Google Developer Console. This will have Google treat it as an installed application and NOT a JavaScript application, thus not requiring a redirect URI to handle the callback.
It's somewhat confusing as Google's documentation for .NET tells you to create a Web App OAuth Client ID.
Feb 16, 2018 Updated Better Answer:
I wanted to provide an update to this answer. Though, what I said above works, this is NOT the best way to implement the OAuth workflow for a ASP.NET solution. There is a better way which actually uses a proper OAuth 2.0 flow. Google's documentation is terrible in regards to this (especially for .NET), so I'll provide a simple implementation example here. The sample is using ASP.NET core, but it's easily adapted to the full .NET framework :)
Note: Google does have a Google.Apis.Auth.MVC package to help simplifiy this OAuth 2.0 flow, but unfortunately it's coupled to a specific MVC implementation and does not work for ASP.NET Core or Web API. So, I wouldn't use it. The example I'll be giving will work for ALL ASP.NET applications. This same code flow can be used for any of the Google APIs you've enabled as it's dependent on the scopes you are requesting.
Also, I am assuming you have your application set up in your Google Developer dashboard. That is to say that you have created an application, enabled the necessary YouTube APIs, created a Web Application Client, and set your allowed redirect urls properly.
The flow will work like this:
The user clicks a button (e.g. Add YouTube)
The View calls a method on the Controller to obtain an Authorization URL
On the controller method, we ask Google to give us an Authorization URL based on our client credentials (the ones created in the Google Developer Dashboard) and provide Google with a Redirect URL for our application (this Redirect URL must be in your list of accepted Redirect URLs for your Google Application)
Google gives us back an Authorization URL
We redirect the user to that Authorization URL
User grants our application access
Google gives our application back a special access code using the Redirect URL we provided Google on the request
We use that access code to get the Oauth tokens for the user
We save the Oauth tokens for the user
You need the following NuGet Packages
Google.Apis
Google.Apis.Auth
Google.Apis.Core
Google.apis.YouTube.v3
The Model
public class ExampleModel
{
public bool UserHasYoutubeToken { get; set; }
}
The Controller
public class ExampleController : Controller
{
// I'm assuming you have some sort of service that can read users from and update users to your database
private IUserService userService;
public ExampleController(IUserService userService)
{
this.userService = userService;
}
public async Task<IActionResult> Index()
{
var userId = // Get your user's ID however you get it
// I'm assuming you have some way of knowing if a user has an access token for YouTube or not
var userHasToken = this.userService.UserHasYoutubeToken(userId);
var model = new ExampleModel { UserHasYoutubeToken = userHasToken }
return View(model);
}
// This is a method we'll use to obtain the authorization code flow
private AuthorizationCodeFlow GetGoogleAuthorizationCodeFlow(params string[] scopes)
{
var clientIdPath = #"C:\Path\To\My\client_id.json";
using (var fileStream = new FileStream(clientIdPath, FileMode.Open, FileAccess.Read))
{
var clientSecrets = GoogleClientSecrets.Load(stream).Secrets;
var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = clientSecrets, Scopes = scopes };
var googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow(initializer);
return googleAuthorizationCodeFlow;
}
}
// This is a route that your View will call (we'll call it using JQuery)
[HttpPost]
public async Task<string> GetAuthorizationUrl()
{
// First, we need to build a redirect url that Google will use to redirect back to the application after the user grants access
var protocol = Request.IsHttps ? "https" : "http";
var redirectUrl = $"{protocol}://{Request.Host}/{Url.Action(nameof(this.GetYoutubeAuthenticationToken)).TrimStart('/')}";
// Next, let's define the scopes we'll be accessing. We are requesting YouTubeForceSsl so we can manage a user's YouTube account.
var scopes = new[] { YouTubeService.Scope.YoutubeForceSsl };
// Now, let's grab the AuthorizationCodeFlow that will generate a unique authorization URL to redirect our user to
var googleAuthorizationCodeFlow = this.GetGoogleAuthorizationCodeFlow(scopes);
var codeRequestUrl = googleAuthorizationCodeFlow.CreateAuthorizationCodeRequest(redirectUrl);
codeRequestUrl.ResponseType = "code";
// Build the url
var authorizationUrl = codeRequestUrl.Build();
// Give it back to our caller for the redirect
return authorizationUrl;
}
public async Task<IActionResult> GetYoutubeAuthenticationToken([FromQuery] string code)
{
if(string.IsNullOrEmpty(code))
{
/*
This means the user canceled and did not grant us access. In this case, there will be a query parameter
on the request URL called 'error' that will have the error message. You can handle this case however.
Here, we'll just not do anything, but you should write code to handle this case however your application
needs to.
*/
}
// The userId is the ID of the user as it relates to YOUR application (NOT their Youtube Id).
// This is the User ID that you assigned them whenever they signed up or however you uniquely identify people using your application
var userId = // Get your user's ID however you do (whether it's on a claim or you have it stored in session or somewhere else)
// We need to build the same redirect url again. Google uses this for validaiton I think...? Not sure what it's used for
// at this stage, I just know we need it :)
var protocol = Request.IsHttps ? "https" : "http";
var redirectUrl = $"{protocol}://{Request.Host}/{Url.Action(nameof(this.GetYoutubeAuthenticationToken)).TrimStart('/')}";
// Now, let's ask Youtube for our OAuth token that will let us do awesome things for the user
var scopes = new[] { YouTubeService.Scope.YoutubeForceSsl };
var googleAuthorizationCodeFlow = this.GetYoutubeAuthorizationCodeFlow(scopes);
var token = await googleAuthorizationCodeFlow.ExchangeCodeForTokenAsync(userId, code, redirectUrl, CancellationToken.None);
// Now, you need to store this token in rlation to your user. So, however you save your user data, just make sure you
// save the token for your user. This is the token you'll use to build up the UserCredentials needed to act on behalf
// of the user.
var tokenJson = JsonConvert.SerializeObject(token);
await this.userService.SaveUserToken(userId, tokenJson);
// Now that we've got access to the user's YouTube account, let's get back
// to our application :)
return RedirectToAction(nameof(this.Index));
}
}
The View
#using YourApplication.Controllers
#model YourApplication.Models.ExampleModel
<div>
#if(Model.UserHasYoutubeToken)
{
<p>YAY! We have access to your YouTube account!</p>
}
else
{
<button id="addYoutube">Add YouTube</button>
}
</div>
<script>
$(document).ready(function () {
var addYoutubeUrl = '#Url.Action(nameof(ExampleController.GetAuthorizationUrl))';
// When the user clicks the 'Add YouTube' button, we'll call the server
// to get the Authorization URL Google built for us, then redirect the
// user to it.
$('#addYoutube').click(function () {
$.post(addYoutubeUrl, function (result) {
if (result) {
window.location.href = result;
}
});
});
});
</script>
As referred here, you need to specify a fix port for the ASP.NET development server like How to fix a port number in asp.NET development server and add this url with the fix port to the allowed urls. Also as stated in this thread, when your browser redirects the user to Google's oAuth page, you should be passing as a parameter the redirect URI you want Google's server to return to with the token response.
I noticed that there is easy non-programmatic way around.
If you have typical monotlith application built in typical MS convention(so not compatible with 12factor and typical DDD) there is an option to tell your Proxy WWW server to rewrite all requests from HTTP to HTTPS so even if you have set up Web App on http://localhost:5000 and then added in Google API url like: http://your.domain.net/sigin-google, it will work perfectly and it is not that bas because it is much safer to set up main WWW to rewrite all to HTTPS.
It is not very good practice I guess however it makes sense and does the job.
I've struggled with this issue for hours in a .net Core application. What finally fixed it for me was, in the Google developers console, to create and use a credential for "Desktop app" instead of a "Web application".
Yeah!! Using credentials of desktop app instead of web app worked for me fine. It took me more than 2 days to figure out this problem. The main problem is that google auth library dose not adding or supporting http://localhost:8000 as redirect uri for web app creds but credentials of desktop app fixed that issue. Cause its supporting http://___ connection instead of https: connection for redirect uri
We have angularJs & C# web aplication.
We are planning to use our facebook page to handle our customer issues and complaints.
We will show facebook visitor posts in our website so our representative notice it and reply on same. (may be new comment or reply existing)
Our representative ask customer to send private message and then user initiate message to us and then we can see that message in our website and reply to that message through our website.
By this way we will able to sort out problems of our customer through our application.
public static FacebookClient GetClientApplicationAccessToken(FacebookClient client)
{
dynamic accessToken = client.Get("oauth/access_token", new
{
client_id = "my_ApplicationId",
client_secret = "my_AppSecretKey",
grant_type = "client_credentials"
});
client.AccessToken = accessToken.access_token;
return client;
}
public static dynamic GetFacebookPosts(string pageId)
{
var client = new FacebookClient();
GetClientApplicationAccessToken(client);
dynamic postObject = client.Get("/" + pageId + "/feed?fields=message,from,created_time,full_picture");
dynamic postJson = JsonConvert.DeserializeObject(posts);
return postJson;
}
By this access token we are able to fetch Facebook post, but not possible when we try to fetch conversation between Our Facebook page & our customers through private messages.
dynamic postdaObject = newclient.Get("me?fields=conversations{messages{created_time,message}}");
I think when we use access token from above method i.e.GetClientApplicationAccessToken() it is not working. but if I replace hard coded user access token then it's working. As our application end user will see Facebook messages and will reply to them, it does not require FaceBook Login button. We need some permanent access token by which we can fetch private messages from Facebook without any login button. Kindly help me to solve this issue.
I'm developing an app for iOS and Android that uses Facebook to login. The users will login on their phones using their Facebook credentials and I use Facebook's GraphAPI to authenticate them. I do not want to store their email/password unless I absolutely have to.
After authentication, I can get a myriad of information from Facebook but the one that's of most interest to my question is the access token's authorization token.
Since my app has a server side component, I also need to validate that this access token is valid on the server side (so given the access token and the Facebook user id, i should be able to validate this client), otherwise the entirety of using Facebook to authenticate users is pointless as I would need to also store username/password of the users myself.
My thought was to send the userId and the access token via SSL to my server and then use a library to validate that these tokens are valid and the user is indeed who it says it is in order to proceed with DB access and everything else server related.
I am however having a hard time finding a library in .NET that does not use ASP.NET.
Is there any library out there that can do this simple validation (given an authorization token and a user id, tell me if the user is logged in to Facebook and if so, how long the token is valid for) that does not need to inject 20 different DLLs and does not rely on ASP.NET?
I've had a look at DotNetOpenAuth but (1) it seems to need quite a few DLLs to operate which is kind of fine on its own although not ideal and (2) it seems to rely on ASP.NET and microsoft libraries that I would strongly like to avoid.
I'm running my server on Mono and would ideally like to avoid doing anything with ASP.NET since they have proven to be very unstable in the past.
Many thanks,
You might want to try a service like https://oauth.io/home which handles that oAUth stuff for you. According to the docs once you set it up you can simply use rest to make authenticated calls. http://docs.oauth.io/#simple-server-side-authorization
Ok I found an easy way to do it.
First, I downloaded their .Net library from NuGet:
<package id="Facebook" version="7.0.6" targetFramework="net40" />
Then here's the process in order to authenticate users.
Step 1
Get the server's Access Token (this has to be done once at the startup of the service)
var client = new FacebookClient
{
AppId = appId, // get this from developer.facebook
AppSecret = appSecret, // get this from developer.facebook
};
dynamic appTokenQueryResponse = client.Get("oauth/access_token"
, new
{
client_id = appId,
client_secret = appSecret,
grant_type = "client_credentials"
});
_appAccessToken = appTokenQueryResponse.access_token;
Step 2
With the server access token, We're able to make the appropriate calls into the API in order to make sure the token is valid.
private FacebookAuthorizationResponse AuthorizeUser(FacebookClient client, string userId, string accessToken)
{
dynamic expirationToken = client.Get("debug_token", new
{
input_token = accessToken,
access_token = _appAccessToken
});
DateTime expiresAt = DateTimeConvertor.FromUnixTime(expirationToken.data.expires_at);
bool isValid = expirationToken.data.is_valid;
if (!isValid)
{
return new FacebookAuthorizationResponse
{
IsAuthorized = false,
};
}
dynamic response = client.Get(userId, new
{
access_token = accessToken,
fields = "id,name"
});
return new FacebookAuthorizationResponse
{
IsAuthorized = isValid,
ExpiresAt = expiresAt,
Name = response.name
};
}
Where
public class FacebookAuthorizationResponse
{
public bool IsAuthorized { get; set; }
public DateTime ExpiresAt { get; set; }
public string Name { get; set; }
}
I have to use Facebook's notification for my web app.
Facebook Graph API requires the Application Access Token for this action.
Is there a way to get this token by code (C# SDK) or is this generated by Facebook a single time?
Is this token static (and secret) or with expire datetime?
For info: https://developers.facebook.com/tools/access_token/ - App Token, not User Token!
Thanks
The answer is the dynamic way by code:
var fb = new FacebookClient();
dynamic result = fb.Get( "oauth/access_token", new
{
client_id = <myAppID>,
client_secret = <mySecretID>,
grant_type = "client_credentials"
} );
var apptoken = result.access_token;
Or by the combination or appid|secretid
You can just use the concatenation of id and secret with a pipe symbol in the middle:
app_id|app_secret
This is actually how the PHP SDK creates the app access token internally, so there should be no question about the reliability of this method. (From other endpoints where you actively query for an app access token you might get another token that does not match this scheme though.)
you can investigate the getApplicationAccessToken method as in another c# sdk project from github
https://github.com/barans/FacebookCsharpSdk/blob/master/FacebookCSharpSDK/FacebookClient/FacebookClient.cs