eydjey / google-api-dotnet-client

Automatically exported from code.google.com/p/google-api-dotnet-client
Apache License 2.0
0 stars 0 forks source link

How To Call OAuth 2.0 With Web Page? #179

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
I have created a web page to call 'OAuth 2.0 to Access Google APIs' and want to 
get my infomation.but i didn't get it .Please help me.

 if (Request.QueryString["Code"] != null)
        {
            //I can get the code from google api callback url
            string authCode = Request.QueryString["Code"].ToString();       
            if (!string.IsNullOrEmpty(authCode))
            {

                List<string> scopes = new List<string>();
                scopes.Add("https://www.googleapis.com/auth/plus.me");
                scopes.Add("https://www.googleapis.com/auth/userinfo.email");
                var state = new AuthorizationState(scopes);
                state.Callback = new Uri("http://localhost:3877/WEB/Default2.aspx");
                // i can get the accesstoke and refreshtoken
                stat = provider.ProcessUserAuthorization(authCode, state);

                // but in these. i can get the oAuth2Auth , plese 
                // see   GetAuthentication function
                var oAuth2Auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication);

                // get user profile
                var objService = new PlusService(oAuth2Auth);
                var me = objService.People.Get("me").Fetch();
            }
        }
        else
        {

            List<string> scopes = new List<string>();
            scopes.Add("https://www.googleapis.com/auth/plus.me");
            scopes.Add("https://www.googleapis.com/auth/userinfo.email");
            var state = new AuthorizationState(scopes);
            state.Callback = new Uri("http://localhost:3877/WEB/Default2.aspx");

            Uri ur = provider.RequestUserAuthorization(state);// this.provider.RequestUserAuthorization(state);
            string requestUrl = ur.ToString();

             requestUrl += "&access_type=offline";
             requestUrl += "&approval_prompt=force";

             requestUrl += "&state=" + provider.ClientIdentifier + "_" + provider.ClientSecret;
            //Plese see below post URL
            this.Response.Redirect(requestUrl);

        }

post URL:
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=416498199
195.apps.googleusercontent.com&redirect_uri=http://localhost:3877/WEB/Default2.a
spx&scope=https://www.googleapis.com/auth/plus.me 
https://www.googleapis.com/auth/userinfo.email&access_type=offline&approval_prom
pt=force&state=416498199195.apps.googleusercontent.com_OwRLquE3NTKhjY7dLFHgPLOl
========================

   private static IAuthorizationState GetAuthentication(NativeApplicationClient client)
    {
        // You should use a more secure way of storing the key here as
        // .NET applications can be disassembled using a reflection tool.

        const string STORAGE = "google.plus";
        const string KEY = "plus";

        // Check if there is a cached refresh token available.

        IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY);
        if (state != null)
        {
            try
            {
                client.RefreshToken(state,null);
                return state; // Yes - we are done.
            }
            catch (DotNetOpenAuth.Messaging.ProtocolException ex)
            {
                CommandLine.WriteError("Using existing refresh token failed: " + ex.Message);
            }
        }

        //Retrieve the authorization from the user.
        string Scope = SiteVerificationService.Scopes.Siteverification.GetStringValue();
        // the below function will open a new page and post url to google and will return code to my call back url. but the url is this page. i can't get the code. how to fix this question ???
        state = AuthorizationMgr.RequestNativeAuthorization(client, Scope);
        AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state);
        return state;
    }

============================
all the api i use latest version . 
Could anyone provide a web page call OAuth 2.0 sample to me?thanks!!!

Original issue reported on code.google.com by ypca...@163.com on 4 Jan 2012 at 11:52

GoogleCodeExporter commented 9 years ago
Hi there!

If you are using ASP.NET/A webserver as a base for your project, you cannot use 
the NativeApplicationFlow as that one will only work for client-based 
applications. It won't allow a specific Callback URI.

We don't have an ASP.NET example for the shopping api per se, but you can 
easily use the Tasks-API example by just replacing the "TasksService" with the 
"PlusService":

http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.ASP.NET.Si
mpleOAuth2/Default.aspx.cs?repo=samples

Hope this helps!

Original comment by mlinder...@gmail.com on 4 Jan 2012 at 12:13

GoogleCodeExporter commented 9 years ago
HI ,thank you for your help.
I have downloaded and tested the samples code.

//in the below code, i can get the code from google api,but if i click the 
//'Fetch Tasklists' button it will call  FetchTaskslists() function and get the
// error. the error is DotNetOpenAuth.Messaging.ProtocolException: Precondition 
//failed: !authorization.AccessTokenExpirationUtc.HasValue
// || authorization.AccessTokenExpirationUtc < DateTime.UtcNow 
//|| authorization.RefreshToken != null 

// i hace checked the post it saied need to add
// access_type=offline and  approval_prompt=force int the URL of post. but i 
// have checked the function GetAuthorization(WebServerClient client) (see 
below code). i can't change the URL of post. any idea for this? Please help 
me.thanks!

 protected void Page_Load(object sender, EventArgs e)
        {
            // Create the Tasks-Service if it is null.
            if (_service == null)
            {
                _service = new TasksService(_authenticator = CreateAuthenticator());
            }

            // Check if we received OAuth2 credentials with this request; if yes: parse it.
            if (HttpContext.Current.Request["code"] != null)
            {
                _authenticator.LoadAccessToken();
            }

            // Change the button depending on our auth-state.
            listButton.Text = AuthState == null ? "Authenticate" : "Fetch Tasklists";
        }

=================

  private IAuthorizationState GetAuthorization(WebServerClient client)
        {
            // If this user is already authenticated, then just return the auth state.
            IAuthorizationState state = AuthState;
            if (state != null)
            {
                return state;
            }

            // Check if an authorization request already is in progress.
            state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
            if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken)))
            {
                // Store and return the credentials.
                HttpContext.Current.Session["AUTH_STATE"] = _state = state;
                return state;
            }

            // Otherwise do a new authorization request.
            string scope = TasksService.Scopes.TasksReadonly.GetStringValue();
// The below code will generate url of post but i can't change the url.Please 
// help me.

            OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope });
            response.Send(); // Will throw a ThreadAbortException to prevent sending another response.
            return null;
        }

Original comment by ypca...@163.com on 5 Jan 2012 at 2:19

GoogleCodeExporter commented 9 years ago
@ypca...@163.com

response.Headers["Location"] += "&access_type=offline&approval_prompt=force";
response.Send();

Hope this helps.
Kha

Original comment by kha.th...@gmail.com on 6 Jan 2012 at 1:47

GoogleCodeExporter commented 9 years ago
thanks.

I have checked this code.it can post to google plus.
After i click the 'Fetch Tasklists' the google plus return error. the error is:
==================
The request 'Google.Apis.Requests.Request(list @  
https://www.googleapis.com/tasks/v1/users/@me/lists?alt=json&prettyPrint=true)' 
has failed. The service tasks has thrown an exception: 
Google.GoogleApiRequestException: Google.Apis.Requests.RequestError 
Access Not Configured [403] 
Errors [ 
Message[Access Not Configured] Location[ - ] Reason[accessNotConfigured] 
Domain[usageLimits] 
] 
=========================
How to fix this question. Please help me thanks!!!

Original comment by saishang...@126.com on 6 Jan 2012 at 9:27

GoogleCodeExporter commented 9 years ago
You will need to enable the appropriate services in the Google API Console, 
which can be found by going to the link below and clicking on "Services":

  https://code.google.com/apis/console/

Also, on a side note: Which API are you currently trying to access? The error 
message seems to come from the Tasks API. If you intent to use the Google+ API, 
you will have to use the PlusService instead.

Original comment by mlinder...@gmail.com on 6 Jan 2012 at 3:02

GoogleCodeExporter commented 9 years ago
thanks!

I want to use Google+ API. I just want to created a web page to call 'OAuth 2.0 
to Access Google APIs' and want to get my infomation with Google+API. Please 
see below code:

---------------------------------------step one
// page load,use below code to Redirect to goole and google will call 
//Callback URL to my project.

            List<string> scopes = new List<string>();
            scopes.Add("https://www.googleapis.com/auth/plus.me");
            scopes.Add("https://www.googleapis.com/auth/userinfo.email");
            var state = new AuthorizationState(scopes);
            state.Callback = new Uri("http://localhost:3877/WEB/Default2.aspx");

            Uri ur = provider.RequestUserAuthorization(state);// this.provider.RequestUserAuthorization(state);
            string requestUrl = ur.ToString();

             requestUrl += "&access_type=offline";
             requestUrl += "&approval_prompt=force";

             requestUrl += "&state=" + provider.ClientIdentifier + "_" + provider.ClientSecret;
            //Plese see below post URL
            this.Response.Redirect(requestUrl);
--------------------------------step two
after the google return to my web project:

if (Request.QueryString["Code"] != null)
        {
            //I can get the code from google api callback url
            string authCode = Request.QueryString["Code"].ToString();       
            if (!string.IsNullOrEmpty(authCode))
            {

                List<string> scopes = new List<string>();
                scopes.Add("https://www.googleapis.com/auth/plus.me");
                scopes.Add("https://www.googleapis.com/auth/userinfo.email");
                var state = new AuthorizationState(scopes);
                state.Callback = new Uri("http://localhost:3877/WEB/Default2.aspx");
                // i can get the accesstoke and refreshtoken
                stat = provider.ProcessUserAuthorization(authCode, state);

                // but in these. i can't get the oAuth2Auth , plese 
                // see   GetAuthentication function
                var oAuth2Auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication);

                // get user profile
                var objService = new PlusService(oAuth2Auth);
                var me = objService.People.Get("me").Fetch();
            }
        }

=============> your saied:  "you cannot use the NativeApplicationFlow as that 
one will only work for client-based applications. It won't allow a specific 
Callback URI.
"

var oAuth2Auth = new OAuth2Authenticator<NativeApplicationClient>(provider, 
GetAuthentication);
// get user profile
var objService = new PlusService(oAuth2Auth);
var me = objService.People.Get("me").Fetch();

if i want to use PlusService to get my infomation how to get the 
"oAuth2Auth"(plase see above code) and don't use NativeApplicationClient ? 
Please help me thanks!!!

Original comment by saishang...@126.com on 9 Jan 2012 at 7:10

GoogleCodeExporter commented 9 years ago
The (unchecked) code which can be found at the URL below demonstrates how you 
can use the Google+ API with ASP.NET using the WebServerFlow:

http://codereview.appspot.com/5530061/

Hope this helps!

Original comment by mlinder...@gmail.com on 10 Jan 2012 at 2:32

GoogleCodeExporter commented 9 years ago
Thank you very much.

Could you provide a link that we can download all code?Thanks!!!

Original comment by saishang...@126.com on 12 Jan 2012 at 6:35

GoogleCodeExporter commented 9 years ago
hi, when i click the 'Fetch info'. I get the error,the error is :
============================
The request 'Google.Apis.Requests.Request(get @ 
https://www.googleapis.com/plus/v1/people/me?alt=json&prettyPrint=true)' has 
failed. The service plus has thrown an exception: 
Google.GoogleApiRequestException: Google.Apis.Requests.RequestError 
Invalid Credentials [401] 
Errors [ 
Message[Invalid Credentials] Location[Authorization - header] Reason[authError] 
Domain[global] 
] 
===============
How to fix this? what services we should enable ?

Original comment by saishang...@126.com on 12 Jan 2012 at 7:50

GoogleCodeExporter commented 9 years ago
There are several possible issues for this error. Try checking those things:

(a) Have you entered your client secret and client ID in the 
ClientCredentials.cs file or when creating the authenticator? Make sure the 
values entered are equal to those displayed on the API Console.

(b) If you are running the ASP.NET sample make sure that you created a client 
id+secret set which is also configured as a Web-Application, not as an Native 
Application. You can create multiple client id/secret sets if you require both 
kinds of applications.

(c) Enable the "Google Plus" service in your API Console Access Tab

(d) Make sure you are using a valid access token. Access Tokens only stay valid 
for about two hours, and old ones might get invalidated once you re-request a 
new access token using the same client id/secret set. If the problem persists, 
debug the code and make sure the access token you just acquired when clicking 
"Authenticate" on your ASP.NET page gets passed into the Authenticator when 
clicking "Fetch Info".

Original comment by mlinder...@gmail.com on 12 Jan 2012 at 12:25

GoogleCodeExporter commented 9 years ago
I have read this thread and implements all like above. I still got 401 error, I 
use this to access latitude API. I had checked client Id and secret, all were 
same as my console. My authenticator was also WebServerClient type, Latitude 
API had been turned on. Token had been acquired correctly and the expiration 
time still 1 hour left. Is anyone have a solution for this? I was in urgent, 
cause of client demanded. 

Original comment by jh.tech....@gmail.com on 1 Feb 2012 at 11:57

GoogleCodeExporter commented 9 years ago
Hi, when we use this code for Google Task

/******************
  _service = New TasksService(CreateAuthenticator())

   Dim response As TasklistsResource = _service.Tasklists

   Return ShowTaskslists(response.List(100).Fetch())

*******************/

we got below error and after that this error also got when add task in loop

/****************

Google.Apis.Requests.RequestError
Bad Request [400]
Errors [
    Message[Bad Request] Location[ - ] Reason[badRequest] Domain[global]
]
****************/

Original comment by ghanshya...@xtremeheights.com on 29 Mar 2012 at 5:35

GoogleCodeExporter commented 9 years ago
Matthias, you have accepted this issue, what were you planning to do for action 
on this item. Otherwise we might need to split the issues into other issues for 
tracking. I would like to clean this up.

Austin

Original comment by asky...@google.com on 25 Apr 2012 at 6:34

GoogleCodeExporter commented 9 years ago
I planned on adding a sample for the plus API to the samples/ repository (as 
shown in the codereview CL), but didn't get any chance to do it. So for the 
moment I am just changing the status back.

Original comment by mlin...@google.com on 25 Apr 2012 at 7:01

GoogleCodeExporter commented 9 years ago
Created sample request issue.

Original comment by asky...@google.com on 25 Apr 2012 at 8:55

GoogleCodeExporter commented 9 years ago
Eu estou usando o Google Prediction e Preciso de autenticar para fazer minhas 
previsões. quando peço autorização eu passo o:

          // Display the header and initialize the sample.
            CommandLine.EnableExceptionHandling();
            CommandLine.DisplayGoogleSampleHeader("Tasks API");

            // Register the authenticator.
            // Get the auth URL:
            //IAuthorizationState state = new AuthorizationState(new[] { TasksService.Scopes.Tasks.GetStringValue() });

            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            FullClientCredentials credentials = new FullClientCredentials();
            credentials.ApiKey = "AIzaSyCrNndiZazK3zbJxdZu6cSfVCLLuN5FFog";
            credentials.ClientId = "741663684804-uqr49f937fi48l5apg9rnmreq7b4ugp6.apps.googleusercontent.com";
            credentials.ClientSecret = "I7uvCW8gsnmVz2_fy0u8Uef3";
            provider.ClientIdentifier = credentials.ClientId;
            provider.ClientSecret = credentials.ClientSecret;
            var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

            List<string> scopes = new List<string>();
            scopes.Add("https://www.googleapis.com/auth/plus.me");
            scopes.Add("https://www.googleapis.com/auth/userinfo.email");
            var state = new AuthorizationState(scopes);
            state.Callback = new Uri("http://localhost:15709");

            var service = new TasksService(auth);
            TaskLists results = service.Tasklists.List().Fetch();
      }

só que quando eu solicito a autenticação ele retorna esse erro: 

Login Required [401]
Errors [Message[Login Required] Location[Authorization - header] 
Reason[required] Domain[global]

ALGUÉM PODE ME AJUDAR?

Original comment by produtos...@gmail.com on 7 Aug 2012 at 4:56

GoogleCodeExporter commented 9 years ago
Your main/setup method looks ok, although the 'state' variable seems to be 
unused/misplaced here. Can you show your GetAuthorization method? The 
authorization will only be added if the GetAuthorization method returns a 
non-null IAuthorizationState.

Original comment by mlinder...@gmail.com on 7 Aug 2012 at 6:34

GoogleCodeExporter commented 9 years ago
a sim segue o modelo do:

        private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
        {

            // Get the auth URL:
            IAuthorizationState state = new AuthorizationState(new[] { TasksService.Scopes.Tasks.GetStringValue() });

            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = arg.RequestUserAuthorization(state);

            // Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString());

            string authCode = null;

            // Retrieve the access token by using the authorization code:
            return arg.ProcessUserAuthorization(authCode, state);
        }

Espero que veja o que está de errado, pois eu já tentei tudo!

Original comment by produtos...@gmail.com on 8 Aug 2012 at 3:21

GoogleCodeExporter commented 9 years ago
That is definitely where things go wrong. AuthCode should not be null, 
otherwise you won't be able to get a valid refresh & access token. Have a look 
at this implementation of the GetAuthorization method, and try using it:

http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.CreateTask
s/Program.cs?repo=samples

The AuthorizationMgr used by this code can be found here:

http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg
%2FSampleHelper

Hope this helps!

Original comment by mlinder...@gmail.com on 8 Aug 2012 at 3:25

GoogleCodeExporter commented 9 years ago
Eu também passo pelo mesmo problema.

e encontro esse erro: 

The request 'Google.Apis.Requests.Request(list @ 
https://www.googleapis.com/tasks/v1/users/@me/lists?alt=json&prettyPrint=true)' 
has failed. The service tasks has thrown an exception: 
Google.GoogleApiRequestException: Google.Apis.Requests.RequestError
 Access Not Configured [403] 
Errors [ 
Message[Access Not Configured] Location[ - ] Reason[accessNotConfigured] 
Domain[usageLimits]
 ] 
---> System.Net.WebException: O servidor remoto retornou um erro: (403) 
Proibido.
   em System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) 
  em Google.Apis.Requests.Request.InternalEndExecuteRequest(IAsyncResult asyncResult) na z:\google-api\google-api-dotnet-client\9-7-2012\default\Src\GoogleApis\Apis\Requests\Request.cs:linha 327
   --- Fim do rastreamento de pilha de exceções internas --- 
  em Google.Apis.Requests.Request.AsyncRequestResult.GetResponse() na z:\google-api\google-api-dotnet-client\9-7-2012\default\Src\GoogleApis\Apis\Requests\Request.cs:linha 301
   em Google.Apis.Requests.ServiceRequest`1.GetResponse() na z:\google-api\google-api-dotnet-client\9-7-2012\default\Src\GoogleApis\Apis\Requests\ServiceRequest.cs:linha 183
   em Google.Apis.Requests.ServiceRequest`1.Fetch() na z:\google-api\google-api-dotnet-client\9-7-2012\default\Src\GoogleApis\Apis\Requests\ServiceRequest.cs:linha 203
   em Tasks.ASP.NET.SimpleOAuth2._Default.FetchTaskslists() na D:\Dropbox\Takenet\PROJETOS\Prediction\Tasks.ASP.NET.SimpleOAuth2\Default.aspx.cs:linha 116

Recebo  tokem mas não consigo fazer o Fetch Tasklists

estou utilizando a biblioteca exemplo do golgle: GoogleApisSamples -->  
Tasks.ASP.NET.SimpleOAuth2

Original comment by produtos...@gmail.com on 14 Sep 2012 at 9:08

GoogleCodeExporter commented 9 years ago
I also spend the same problem.

and encounter this error:

The request 'Google.Apis.Requests.Request (list 
https://www.googleapis.com/tasks/v1/users/ @ @ me / lists? Alt = json = true & 
prettyprint)' has failed. The service tasks has thrown an exception: 
Google.GoogleApiRequestException: Google.Apis.Requests.RequestError
  Access Not Configured [403]
errors [
Message [Access Not Configured] Location [-] Reason [accessNotConfigured] 
Domain [usageLimits]
  ]
---> System.Net.WebException: The remote server returned an error: (403) 
Forbidden.
    in System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult)
   in Google.Apis.Requests.Request.InternalEndExecuteRequest (IAsyncResult 
asyncResult) in 327
    --- End of exception stack trace --- internal
   Google.Apis.Requests.Request.AsyncRequestResult.GetResponse in () in 301
    in Google.Apis.Requests.ServiceRequest `1.GetResponse () in 183
    in Google.Apis.Requests.ServiceRequest `1.Fetch () in 203
    in Tasks.ASP.NET.SimpleOAuth2._Default.FetchTaskslists () in D: \ 
Dropbox \ Takenet \ PROJECTS \ Prediction \ Tasks.ASP.NET.SimpleOAuth2 \ 
Default.aspx.cs: line 116

I get TOKEM but I can not do the Fetch Tasklists

I'm using the library's golgle example: GoogleApisSamples -> 
Tasks.ASP.NET.SimpleOAuth2

Original comment by produtos...@gmail.com on 14 Sep 2012 at 9:08

GoogleCodeExporter commented 9 years ago
Hi there,
I am using google api sample code. I can successfully get all the tasklist as 
well as task using asp.net but when I want to insert  a task using the 
following code(where listID is a valid tasklist id):
_service.Tasks.Insert(new Task { Title = "Party for DL2" }, listID).Fetch();

I got the following error:
Google.Apis.Requests.RequestError
Invalid Credentials [401]
Errors [
    Message[Invalid Credentials] Location[Authorization - header] Reason[authError] Domain[global]
]

please help me.
khabir

Original comment by khabir.a...@gmail.com on 25 Jan 2013 at 8:35