Unable to get AccessToken using OAuth2 to impliment Google Document List Api - asp.net

In my ASP.NET application I am implementing Google Document List API, to fetch User data I using OAuth2 to do so I did some code:
string CLIENT_ID = "123456789321.apps.googleusercontent.com";
string CLIENT_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxx";
string SCOPE = "https://docs.google.com/feeds/ https://docs.googleusercontent.com/ https://spreadsheets.google.com/feeds/";
string REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
parameters = new OAuth2Parameters();
parameters.ClientId = CLIENT_ID;
parameters.ClientSecret = CLIENT_SECRET;
parameters.RedirectUri = REDIRECT_URI;
parameters.Scope = SCOPE;
parameters.AccessCode = Convert.ToString(HttpContext.Current.Session["AccessCode"]);
OAuthUtil.GetAccessToken(parameters);
settings = new RequestSettings("My Application", parameters);
Every time OAuthUtil.GetAccessToken(parameters); gives error that is:
Can any one tell me where I am doing mistake?
Also, how to access RefreshToken??

You are using the redirect URI for installed in a web application.
I'd recommend you to update your code to use the newer Drive API, which also includes a complete ASP.NET sample application and tutorial:
https://developers.google.com/drive/examples/dotnet

Related

Simple Odata Client to consume Odata with Authentication not working

I m new to Simple.Odata.client. I had a problem to access the Odata Service with below code. The below code return null. but Postman return with result.
suspected Problem : How to pass a url string with '1000' &format=json
Is the below Simple odata client setup correctly?
There is no UrlBase in Simple Odata client, but there is BAseUri
Is this ODataClientSettings working??
var settings = new Simple.OData.Client.ODataClientSettings();
settings.BaseUri = new Uri("https://..../UoM?$filter=wer eg '1000' &format=json");
settings.Credentials = new NetworkCredential("user1", "usrpwd");
var client = new ODataClient(settings);
please help
Thanks
This worked for me
var credentials = new NetworkCredential(userName, password); //you can use the override with the domain too.
var settings = new ODataClientSettings(baseUrl, credentials) //baseUrl is a string.
{
IgnoreResourceNotFoundException = true,
OnTrace = (x, y) => Debug.WriteLine(x, y),
PayloadFormat = ODataPayloadFormat.Json, //here is where you specify the format
IgnoreUnmappedProperties = true,
RenewHttpConnection = true,
TraceFilter = ODataTrace.All,
PreferredUpdateMethod = ODataUpdateMethod.Merge
};
var client = new ODataClient(settings);
Your baseUrl should not contain all those OData tags but the endpoint of your service like https://myservice.mysite.com/api.svc. Then as you use the Simple.OData.Client the resource url will be automatically completed.
Please, take a look at the OData standard to figure out how it works and see the Simple.OData.Client repo's examples to better understand how to use it.
To better understand how to use the Windows Authentication you can check Authentication and Authorization with Windows Accounts and how to access website with Windows credential
Hope this help.

Google Apps Admin Settings API - 401

I'm trying to get the Organization name for a Google Apps domain. For this, I'm using the Google Apps Admin Settings API. I saw that it required 3-Legged OAuth. I try to implement OAuth 2.0 because OAuth 1 is deprecated. I try many thing to get this work but I'm always getting a 401 unautorized.
I request a token for the scope : https://apps-apis.google.com/a/feeds/domain/
Here is my code:
// ClientID & ClientSecret values
var requestFactory = GDAPI.GoogleApps.GetAuthRequestFactory();
string organizationName = String.Empty;
Google.GData.Apps.AdminSettings.AdminSettingsService service =
new Google.GData.Apps.AdminSettings.AdminSettingsService(auth.Domain, Excendia.Mobility.Utilities1.BLL.WebConfig.ExcendiaAppName);
service.RequestFactory = requestFactory;
service.SetAuthenticationToken(token);
try
{
var result = service.GetOrganizationName(); // throw exception here...
}
catch (Exception ex)
{
log.Error(ex);
}
What am I doing wrong?
Is this compatible with OAuth 2?
I also want to ask if there is another way to get organization name because GData library is supposed to be obsolete and replaced by new Google.Apis...
Resolved!
Thanks Jay. It works on OAuth 2.0 playground. Something on my side was not set correctly.
Using Fiddler I saw the Authorization header being set by my application. It was set to OAuth v1 instead of v2. So I found out I was using the wrong RequestFactory class.
Need to use GOAuth2RequestFactory instead of GOAuthRequestFactory...
So this is now working:
string organizationName = String.Empty;
Google.GData.Apps.AdminSettings.AdminSettingsService service =
new Google.GData.Apps.AdminSettings.AdminSettingsService(auth.Domain, "myAppName");
service.RequestFactory =
new Google.GData.Client.GOAuth2RequestFactory("cl", "MyAppName",
new Google.GData.Client.OAuth2Parameters()
{ ClientId = ClientID,
ClientSecret = ClientSecret,
AccessToken = token });
try
{
var result = service.GetOrganizationName();
if (result != null)
{
organizationName = result.OrganizationName;
}
}
catch (Exception ex)
{
log.Error(ex);
}
return organizationName;
You are using the correct API. Though GData is being replaced by the new Google APIs, Admin Settings API still uses the old GData format for now.
Are you using a super administrator account to authenticate with? Can you try the operation on the OAuth 2.0 playground and see if it works for the account there?
You can also take a look at how Dito GAM, an open source Google Apps tool implements this call. If you create a file named debug.gam in the same path as GAM, GAM will print out all the raw HTTP calls and responses it's making/getting.

Redirecting From One Page to Another After Sending Login Credentials

While I'm logged into a web application 1, I would like to navigate to web application 2 without explicitly logging on manually.
In application 1 I have an OnClick that gathers up my current login credentials and attempts to POST them to applications 2:
long timestamp = DateTime.Now.Ticks;
string userName = currentUser.Credentials.UserName;
string accountName = currentUser.Account.Name;
string ssoUrl = AppUtil.SalesViewSsoUrl;
var ssoKey = new Guid(AppUtil.SalesViewHashKey);
// Build request
System.Net.WebRequest request = System.Net.WebRequest.Create(ssoUrl);
string postData = BuildPostString(userName, accountName, timestamp.ToString("x"), ssoKey);
byte[] postDataBytes = Encoding.Default.GetBytes(postData);
//Request.Headers.Add("SSOParams", postData);
//request.Method = "POST";
//request.ContentType = "application/x-www-form-urlencoded";
//request.ContentLength = postDataBytes.Length;/
//Stream sOut = request.GetRequestStream();
//sOut.Write(postDataBytes, 0, postDataBytes.Length);
//sOut.Flush();
//sOut.Close();
So, the problem here is that I remain on the same page. I can't figure out how to do that basic operation but stay on the newly logged-in application 2 page.
Is there any other way to send those parameters over without putting them in a query string? I want to avoid that.
Any assistance is appreciated.
To my knowledge you should use ASP.NET Web Config tool. You can also handcraft your code. This website has lots of tutorials on ASP.NET. It has some videos about the Authentication and Authorization, etc. in the Advanced ASP.NET section. Manzoor the trainer

Does the Facebook C# SDK depend on cookies on the server?

I'm using the Facebook C# SDK and am trying to figure out exactly how it works. I actually use an AJAX web method to lookup the Facebook account details based on the authenticated user ID, which looks something like this:
if (response.status === "connected")
{
KitchenPC.LogonFB(response.authResponse.userID, checkResult, facebookError);
}
On the server side, the LogonFB web method does something like:
Client = new FacebookClient(applicationId, applicationSecret);
var result = Client.Get(path) as IDictionary<string, object>;
UserId = Int64.Parse((String)result["id"]);
Name = result["name"] as String;
FirstName = result["first_name"] as String;
LastName = result["last_name"] as String;
Location = result.ContainsKey("location") ? result["location"] as String : "";
Gender = result.ContainsKey("gender") ? result["gender"] as String : "";
Email = result["email"] as String;
Where path is the user ID passed in from the client.
My Question:
I'm switching from ASP.NET Web Service to WCF, and WCF does not support cookies. In fact, HttpContext.Current will be null within the WCF pipeline. I was under the impression that the Facebook C# SDK depended on the fbm_ and fmsr_ cookies being passed in on the request, which would be used to validate the session with the Facebook server. However, much to my surprise, the .Get() call still works, and user information is returned. I also dug through the SDK source code and nowhere in it do I find references to HttpContext.Current.
Does the Facebook C# SDK work completely independently of cookies? Does this mean that all I need is the user's Facebook ID, and as long as they've previously approved my app ID, I can grab information about their account?
I just want to make sure I'm not doing anything wrong, and I'm not going to run into trouble in production.
When you pass the constructor with appId and appSecret, it will auto set the access token as app access token using string.Concat(appId, '|', appSecret). That constructor has been removed in newer version of the sdk. https://github.com/facebook-csharp-sdk/facebook-csharp-sdk/issues/103
Set it to null if you don't want the access token.
Client = new FacebookClient(applicationId, applicationSecret);
Client.AccessToken = null;
var result = Client.Get(path) as IDictionary<string, object>;

Using Facebook Connect auth.RevokeAuthorization in ASP.NET

I'm confused as to how revoking authorization works in the ASP.NET Toolkit. I've tried issuing the following:
ConnectSession connect =
new ConnectSession(FacebookHelper.ApiKey(), FacebookHelper.SecretKey());
Auth x = new Auth(fbSession);
x.RevokeAuthorization();
But I get an object reference error during the RevokeAuthorization call. Here's the call definition.
Any idea what I'm doing wrong?
Finally found a working example
Facebook.Session.ConnectSession fbSession =
new Facebook.Session.ConnectSession(ApiKey, SecretKey);
fbSession.UserId = iFBUserID;
fbSession.SessionKey = SessionKey;
Api oApi = new Api(fbSession);
oApi.Auth.RevokeAuthorization();
http://forum.developers.facebook.com/viewtopic.php?id=50938

Resources