Skip to content

Instantly share code, notes, and snippets.

@vitor-mariano
Last active September 8, 2015 14:56
Show Gist options
  • Save vitor-mariano/721b09d977d6c3f03558 to your computer and use it in GitHub Desktop.
Save vitor-mariano/721b09d977d6c3f03558 to your computer and use it in GitHub Desktop.

Authentication

On client, you can use two authentication levels:

  • API key
  • OAuth

With the API key, the simplest one, you just need to set the client with you Consumer Key, provided by Tumblr API, like this

$client = new Tumblr\API\Client($consumerKey);

for use methods which are accessible from the API key. E.g.

$client->getBlogInfo($blogName);

The OAuth level is a little more complex, because it gives more access to user account. You need tokens which are provided only by user authorization. To obtain these tokens, first you need:

  • Guarantee that your application credentials are valid
  • Tell which page should the user return to
  • Redirect user to the Tubmlr authorization page

For this, let's consider you are coding the page https://example.com/auth/tumblr. You should configure your client with your application credentials, provided by OAuth

$client = new Tumblr\API\Client($consumerKey, $consumerSecret);

Point the request handler to Tumblr

$requestHandler = $client->getRequestHandler();
$requestHandler->setBaseUrl('https://www.tumblr.com/');

And send the request to Tumblr with your callback URL. Let's consider it would be https://example.com/auth/tumblr/callback.

$response = $requestHandler->request('POST', 'oauth/request_token', [
    'oauth_callback' => 'https://example.com/auth/tumblr/callback'
]);

If your credentials are valid, you will receive temporary tokens to continue. You can extract them this way

parse_str((string) $response->body, $tokens);

$tokens will contain

['oauth_token' => '...', 'oauth_token_secret' => '...']

Save these tokens somehow (e.g. using $_SESSION), because we will need them in the next session. After this, the user should be redirected to the URL https://www.tumblr.com/oauth/authorize?oauth_token={$tokens['oauth_token']}.

Now, the user will decide if authorizes your application and then will be redirected to your callback page with 'get' param oauth_verifier. Now let's consider you're coding the page https://example.com/auth/tumblr/callback. One more time you should set the client with your application credentials and termporary tokens stored in the last session.

$client = new Tumblr\API\Client($consumerKey, $consumerSecret, $oauthToken, $oauthTokenSecret);

Again let's point the request handler to Tumblr

$requestHandler = $client->getRequestHandler();
$requestHandler->setBaseUrl('https://www.tumblr.com/');

And send the request to Tumblr with param oauth_verifier, at this time receiving the definitive tokens

$response = $requestHandler->request('POST', 'oauth/access_token', [
    'oauth_verifier' => $oauthVerifier
]);

You can also use the variable $_GET to recover $oauthVerifier.

If everything runs correctly, you will receive the definitive tokens, which can be extracted this way

parse_str((string) $response->body, $tokens);

Remember: you can verify the response status with $response->status. If everything runs correctly, the status will be 200. Otherwise, will be 401. You can see all status here.

Finally, you can use any method provided by client.

$client = new Tumblr\API\Client($consumerKey, $consumerSecret, $oauthToken, $oauthTokenSecret);
$client->getUserInfo();

Autenticação

Com o cliente, você pode utilizar dois níveis de autenticação:

  • API key
  • OAuth

No mais simples destes, o API key, basta que você configure o cliente com seu Consumer Key, provido pela API do Tumblr, desta forma

$client = new Tumblr\API\Client($consumerKey);

para utilizá-lo com métodos que são acessíveis a partir da API key. Por exemplo

$client->getBlogInfo($blogName);

O nível OAuth é um pouco mais complexo, pois dá maior acesso à conta do usuário. Você necessita de tokens que são providos apenas por autorização do usuário. Para conseguir esses tokens, primeiro você necessita:

  • Garantir que as credenciais do seu aplicativo são válidas
  • Especificar qual página o usuário deve retornar após autorizar
  • Redirecionar o usuário para a página de autorização do Tumblr

Para isso, vamos considerar que você está desenvolvendo a página https://example.com/auth/tumblr. Você deve configurar seu cliente com as credenciais do seu aplicativo, providas pelo OAuth

$client = new Tumblr\API\Client($consumerKey, $consumerSecret);

Apontar o manipulador de requisições para o Tumblr

$requestHandler = $client->getRequestHandler();
$requestHandler->setBaseUrl('https://www.tumblr.com/');

E enviar a requisição para o Tumblr com a página de retorno. Vamos considerar que seja https://example.com/auth/tumblr/callback.

$response = $requestHandler->request('POST', 'oauth/request_token', [
    'oauth_callback' => 'https://example.com/auth/tumblr/callback'
]);

Se suas credenciais forem válidas, você receberá tokens temporários para prosseguir. Você pode extraí-los desta forma

parse_str((string) $response->body, $tokens);

$tokens irá conter

['oauth_token' => '...', 'oauth_token_secret' => '...']

Guarde os tokens de alguma forma, pois serão necessários na próxima sessão. Depois disso, o usuário deve ser redirecionado para o endereço https://www.tumblr.com/oauth/authorize?oauth_token={$tokens['oauth_token']}.

Feito isso, o usuário decidirá se autoriza seu aplicativo a ter acesso à conta dele e então será redirecionado para sua página de callback com o parâmetro 'get' oauth_verifier. Agora vamos considerar que você esteja desenvolvendo a página https://example.com/auth/tumblr/callback. Novamente você deve configurar o cliente com as credenciais e também os tokens temporários armazenados na sessão anterior.

$client = new Tumblr\API\Client($consumerKey, $consumerSecret, $oauthToken, $oauthTokenSecret);

Novamente vamos apontar o manipulador de requisição para o Tumblr

$requestHandler = $client->getRequestHandler();
$requestHandler->setBaseUrl('https://www.tumblr.com/');

E enviar a requisição para o Tumblr com o parâmetro oauth_verifier, desta vez para receber os tokens definitivos.

$response = $requestHandler->request('POST', 'oauth/access_token', [
    'oauth_verifier' => $oauthVerifier
]);

Você pode também utilizar a variável $_GET para recuperar $oauthVerifier.

Se tudo ocorrer corretamente, você receberá os tokens definitivos, que podem ser extraídos desta forma

parse_str((string) $response->body, $tokens);

Lembre-se: você pode verificar o status da resposta com $response->status. Se tudo ocorrer como planejado, o status será 200. Caso não autorizado, será 401. Você pode consultar todos os status aqui.

Depois de todo esse processo, você pode utilizar qualquer método provido pelo cliente.

$client = new Tumblr\API\Client($consumerKey, $consumerSecret, $oauthToken, $oauthTokenSecret);
$client->getUserInfo();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment