2011-06-06 15 views
5

Estoy jugando un poco con OAuth 2.0 en combinación con alguna API de Google. Aunque el proceso de autorización es bastante fácil, tengo un problema con la autorización automática después de que se haya completado la autorización inicial.Google/OAuth 2 - Inicio de sesión automático

Así:

1. Authorization is done for the first time. (user grants access, I get the token etc etc) 
2. User exits the application 
3. User starts the application again 
4. How to logon automatically here? 

En el punto 4, tengo una refresh_token por lo que sólo debe solicitar un nuevo token usando ese request_token. Pero sigo recibiendo 401 resultados no autorizados en mis llamadas.

Así que lo que trato de hacer es que mi solicitud puede iniciar sesión en silencio para que el usuario no tiene que permitir el acceso cada vez.

Respuesta

2

Usted debe ser capaz de refrescar token de OAuth 2.0 utilizando la siguiente solicitud:

POST /o/oauth2/token HTTP/1.1 
Host: accounts.google.com 
Content-Type: application/x-www-form-urlencoded 

client_id=21302922996.apps.googleusercontent.com& 
client_secret=XTHhXh1SlUNgvyWGwDk1EjXB& 
refresh_token=1/6BMfW9j53gdGImsixUH6kU5RsR4zwI9lUVX-tqf8JXQ& 
grant_type=refresh_token 

Como se señaló en Google OAuth 2.0 documentation.

yo sólo probé usando rizo y funciona como se esperaba:

curl -d client_id=$CLIENT_ID -d client_secret=$CLIENT_SECRET -d refresh_token=$REFRESH_TOKEN -d grant_type=refresh_token https://accounts.google.com/o/oauth2/token 

{"access_token":"$ACCESS_TOKEN","token_type":"Bearer","expires_in":3600} 
+0

Todavía no sé lo que hice mal ; ¡pero de alguna manera funciona ahora! Gracias – Rhapsody

1

Lo hago en .NET utilizando el Google.GData.Client. Una vez que he ido, aunque el proceso de autorización y guardar las fichas, la próxima vez que mi usuario llega al sitio que tire de la autorización mediante la generación de un objeto GOAuthRequestFactory.

public GOAuthRequestFactory GetGoogleOAuthFactory(int id) 
    { 
     // build the base parameters 
     OAuthParameters parameters = new OAuthParameters 
     { 
      ConsumerKey = kConsumerKey, 
      ConsumerSecret = kConsumerSecret 
     }; 

     // check to see if we have saved tokens and set 
     var tokens = (from a in context.GO_GoogleAuthorizeTokens where a.id = id select a); 
     if (tokens.Count() > 0) 
     { 
      GO_GoogleAuthorizeToken token = tokens.First(); 
      parameters.Token = token.Token; 
      parameters.TokenSecret = token.TokenSecret; 
     } 

     // now build the factory 
     return new GOAuthRequestFactory("somevalue", kApplicationName, parameters); 
    } 

Una vez que tengo la fábrica petición, puedo llamar a una de las diversas API que tengo permiso para usar y hacer algo como esto:

// authenticate to the google calendar 
CalendarService service = new CalendarService(kApplicationName); 
service.RequestFactory = GetGoogleOAuthFactory([user id]); 

// add from google doc record 
EventEntry entry = new EventEntry(); 
entry.Title.Text = goEvent.Title; 
entry.Content.Content = GoogleCalendarEventDescription(goEvent); 

When eventTime = new When(goEvent.StartTime, goEvent.EndTime.HasValue ? goEvent.EndTime.Value : DateTime.MinValue, goEvent.AllDay); 
entry.Times.Add(eventTime); 

// add the location 
Where eventLocation = new Where(); 
eventLocation.ValueString = String.Format("{0}, {1}, {2} {3}", goEvent.Address, goEvent.City, goEvent.State, goEvent.Zip); 
entry.Locations.Add(eventLocation); 

Uri postUri = new Uri(kCalendarURL); 

// set the request and receive the response 
EventEntry insertedEntry = service.Insert(postUri, entry); 
+0

¿tienes una solución con esto publicado en cualquier lugar? – Micah

+1

que no tienen una solución, pero lo hice después en otro hilo con los detalles de la conexión a Oauth de Google si eso le ayuda. http://stackoverflow.com/a/7854919/947898 – uadrive

+0

gracias! ¡muy apreciado! – Micah

Cuestiones relacionadas