2010-06-04 5 views
2

J'essaie d'authentifier quelque chose (dans ce cas LinkedIn) en utilisant OAuth mais le jeton demandé retourne toujours null?OAuth Demande jeton = null dans l'application android

Voici mon code ci-dessous:

public void authenticateAppOauthApi() { 
     Log.d(TAG, "authenticateAppOauthApi"); 

     OAuthServiceProvider provider = new OAuthServiceProvider(
       REQUEST_TOKEN_PATH, AUTHORIZE_PATH, ACCESS_TOKEN_PATH); 

     OAuthConsumer consumer = new OAuthConsumer(CALLBACK_URL, API_KEY, 
       SECRET_KEY, provider); 

     OAuthAccessor accessor = new OAuthAccessor(consumer); 

     Intent intent = new Intent(Intent.ACTION_VIEW); 
     Log.d(TAG, "Intent intent = new Intent(Intent.ACTION_VIEW);"); 
     // intent.setData(Uri.parse(url)); 
     String url = accessor.consumer.serviceProvider.userAuthorizationURL 
       + "?oauth_token=" + accessor.requestToken + "&oauth_callback=" 
       + accessor.consumer.callbackURL; 

     intent.setData(Uri.parse(url)); 
     Log.d(TAG, "intent.setData(Uri.parse(url)); = " + url); 
     mContext.startActivity(intent); 

     Log.d(TAG, "finish authenticateApp"); 
} 

J'ai suivi basiquement l'exemple ici http://donpark.org/blog/2009/01/24/android-client-side-oauth

merci à l'avance

+0

Bonjour, est-ce que quelqu'un a des suggestions? merci – jonney

Répondre

0

Juste une idée, est-il HTTP URL ou URL HTTPS?

J'ai eu quelques problèmes pour accéder URL HTTPS, navigateur & app dit que le certificat était erroné.

Certains certificats racine ne sont pas connus par Android.

+0

Oui c'est une URL HTTPS mais elle ne me dit rien sur les certificats. il lance juste le navigateur avec une erreur chargeant la page d'authentification en raison de la nullité du jeton de requête. L'exemple que j'ai trouvé utilise tous l'ancien Signpost 1.1 mais lorsque vous allez sur le panneau http://code.google.com/p/oauth-signpost/downloads/list ses 1.2 et plusieurs des objets utilisés dans les exemples précédents ne fonctionnent pas. – jonney

0

J'ai eu quelques problèmes en utilisant l'une des librairies OAuth que j'ai trouvées sur le net dans mon application Scala Android. Au lieu de trouver un moyen d'utiliser la lib je viens de rouler la mienne ... Je ne sais pas si ça marcherait contre linkedin (ça marche bien avec Yammer, qui utilise HTTPS). Eh bien, ci-dessous est le code pertinent, gardez à l'esprit que je suis assez nouveau pour Android et Scala, donc il y a probablement de meilleurs moyens d'y parvenir.

Le fichier de disposition "R.layout.authorization" est très basique avec deux boutons et un champ de texte dans un RelativeLayout.

class Authorization extends Activity { 

    val client = new DefaultHttpClient() 
    val reqUrl = "https://www.yammer.com/oauth/request_token" 
    val authUrl = "https://www.yammer.com/oauth/authorize?oauth_token=" 
    val accessUrl = "https://www.yammer.com/oauth/access_token" 

    override def onCreate(bundle:Bundle) = { 
    super.onCreate(bundle) 
    this.setContentView(R.layout.authorization) 

    val authButton = findViewById(R.id.authButton).asInstanceOf[Button] 
    val getCodeButton = findViewById(R.id.getCode).asInstanceOf[Button] 

    val prefs = getSharedPreferences(PreferenceFile(), 0) 
    if(prefs.contains("oauth_request_token")) { 
     authButton.setVisibility(View.VISIBLE) 
    } 

    setupListeners(authButton, getCodeButton) 
    } 

    private def getAuthVerifier() = { 
    val authVerifierBox:EditText = Authorization.this.findViewById(R.id.authVerifier).asInstanceOf[EditText] 
    if(authVerifierBox != null && authVerifierBox.getText() != null) { 
     authVerifierBox.getText().toString()  
    } else { 
     "" 
    } 
    } 

    private def setupListeners(authButton:Button, getCodeButton:Button) = { 
    authButton.setOnClickListener(new View.OnClickListener() { 
     override def onClick(view:View) = { 
     retrieveAuthTokenAndSecret() 
     } 
    }) 
    getCodeButton.setOnClickListener(new View.OnClickListener() { 
     override def onClick(view:View) = { 
     try { 
      // Retrieve a request token with an async task and then start the browser... 
      // Use of an implicit definition to convert tuple to an async task. 
      (() => { 
       // Task to perform 
       val reqPost = new HttpPost(reqUrl) 
       reqPost.setHeader("Authorization", OAuthHeaderBuilder(null,null,null)) 
       reqPost.setHeader("Content-Type", "application/x-www-form-urlencoded") 
       val reqResp= client.execute(reqPost) 
       reqResp.getEntity() 
      }, 
      (entity:HttpEntity) => { 
      // PostExecute handle result from task... 
      if(entity != null) { 
       val reader = new BufferedReader(new InputStreamReader(entity.getContent())) 
       val line = reader.readLine() 
       val (oauth_request_token, oauth_token_secret) = OAuthTokenExtractor(line) 

       // Store request tokens so they can be used when retrieving auth tokens... 
       val editor = getSharedPreferences(PreferenceFile(), 0).edit() 
       editor.putString("oauth_request_token", oauth_request_token) 
       editor.putString("oauth_token_secret", oauth_token_secret) 
       editor.commit() 

       // Start browser... 
       val intent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl + oauth_request_token)) 
       startActivity(intent) 
       val authButton = findViewById(R.id.authButton).asInstanceOf[Button] 
       authButton.setVisibility(View.VISIBLE)     
      } 
      }).doInBackground() 
     } catch { 
      case e:Exception => Log.e("ERROR", "ERROR IN CODE:"+e.toString()) 
     } 
     } 
    }) 
    } 

    private def retrieveAuthTokenAndSecret() = { 
    val authVerifier = getAuthVerifier() 
    val accessPost = new HttpPost(accessUrl) 
    val prefs = getSharedPreferences(PreferenceFile(), 0) 
    val token = prefs.getString("oauth_request_token","") 
    val secret = prefs.getString("oauth_token_secret","") 
    accessPost.setHeader("Authorization", OAuthHeaderBuilder(token, secret, authVerifier)) 
    accessPost.setHeader("Content-Type", "application/x-www-form-urlencoded") 
    val accessResp = client.execute(accessPost) 
    val entity = accessResp.getEntity() 
    if(entity != null) { 
     val reader = new BufferedReader(new InputStreamReader(entity.getContent())) 
     val builder = new StringBuilder() 
     val line = reader.readLine() 
     val (oauth_token, oauth_token_secret) = OAuthTokenExtractor(line) 
     val result = new Intent() 
     val editor = getSharedPreferences(PreferenceFile(), 0).edit() 
     editor.putString("oauth_token", oauth_token) 
     editor.putString("oauth_token_secret", oauth_token_secret) 
     editor.commit() 

     setResult(Activity.RESULT_OK, result) 
     finish() 
    } 
    } 
} 

Le OAuthHeaderBuilder est essentiellement une copie du code exemple oauth Yammer:

object OAuthHeaderBuilder { 
    // Apply function taken from the Yammer oauth sample 
    def apply(token:String, secret:String,verifier:String):String = { 
    val buff = new StringBuilder() 
    val currentTime = System.currentTimeMillis() 
    // Hardcoded values for consumer key and secret... 
    val consumerKey = "<your consumer key here>" 
    val consumerSecret = "<your consumer secret here>" 
    buff.append("OAuth realm=\""); 
    buff.append("\", oauth_consumer_key=\""); 
    buff.append(consumerKey); 
    buff.append("\", "); 

    if (token != null) { 
     buff.append("oauth_token=\""); 
     buff.append(token); 
     buff.append("\", "); 
    } 

    buff.append("oauth_signature_method=\""); 
    buff.append("PLAINTEXT"); 
    buff.append("\", oauth_signature=\""); 
    buff.append(consumerSecret); 
    buff.append("%26"); 
    if (secret != null) { 
     buff.append(secret); 
    } 
    buff.append("\", oauth_timestamp=\""); 
    buff.append(currentTime); 
    buff.append("\", oauth_nonce=\""); 
    buff.append(currentTime); 

    if (verifier != null) { 
     buff.append("\", "); 
     buff.append("oauth_verifier=\""); 
     buff.append(verifier); 
    } 

    buff.append("\", oauth_version=\"1.0\""); 

    return buff.toString(); 
    } 
} 

Et afinde pour extraire les jetons que j'ai fait un objet OAuthTokenExtractor ...

object OAuthTokenExtractor { 
    def apply(line:String) = { 
    val token = (line split ("&")).find(x => x.startsWith("oauth_token=")) match { 
     case Some(oauth_token) => (oauth_token split ("="))(1) 
     case _ => "" 
    } 
    val secret = (line split ("&")).find(x => x.startsWith("oauth_token_secret=")) match { 
     case Some(oauth_token_secret) => (oauth_token_secret split ("="))(1) 
     case _ => "" 
    } 
    (token,secret) 
    } 
} 

espère que ce aide :)

0

Mieux vaut utiliser this article comme référence:

Il y a un code pour obtenir l'URL d'authentification dans la version actuelle de Signpost est:

provider.retrieveRequestToken(CALLBACK_URL); 

(et assurez-vous d'utiliser CommonsHttpOAuthConsumer et CommonsHttpOAuthProvider)

1

vous pouvez essayer ce code.

OAuthClient oAuthClient = new OAuthClient(new HttpClient4()); 
try { 
oAuthClient.getRequestToken(accessor); 
} catch (IOException e) { 
e.printStackTrace(); 
} catch (OAuthException e) { 
e.printStackTrace(); 
} catch (URISyntaxException e) { 
e.printStackTrace(); 
} 
Questions connexes