Sie sind auf Seite 1von 11

OAuth

Steps
1. Client Credentials: making API requests for our own account
2. Authorization Code: Getting a token for another user’s account
3. Logging in via OAuth
4. OAuth with Facebook
5. OAuth in JavaScript with Google+
6. Handling Expired Tokens
7. Using Refresh Tokens
8. Tightening up Security

OAuth is an Authorization Framework. Tokens are better than just user/password

Credentials

OAuth Token
So what’s this token? It’s just a unique string tied to my account that gives you access to make API requests
on my behalf. It’s like a
username and password all rolled into one.

For example, if ABCD1234 is a valid token to my Facebook account, then an HTTP request that
looks like this would post to my timeline:

POST /weaverryan/feed HTTP/1.1


Host: graph.facebook.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length
access_token=ABCD1234&message=Hello

Application (human speak) == Client (nerd speak)

http://coop.apps.knpuniversity.com/api

My user id es: 540

Necesito crear mi Application. Es la Aplicación la que pide permisos.


Los datos de mi Application son:

Gallinero
Client ID Gallinero
Client Secret 1acccea927d286d4b13cf21a98ca7817
Redirect URI
Scope eggs-collect

Client Id y Client Secret son como User y Password

Client Credentials
Client (application) ———————> Resource Server
(‘collect-eggs.php’) ———————> (COOP API)

¡Not Users involved!

Necesito generar un token: e48a8653d70d4163ff89fdf06751a953cc2664ea

yerco@yerco:~/webdev/oauth$ php collect.php


{"action":"eggs-collect","success":true,"message":"Hey look at that, 3 eggs
have been collected!","data":3}

Código hasta esta parte:

<?php
include __DIR__.'/vendor/autoload.php';
use Guzzle\Http\Client;

// create http client (Guzzle)


$http = new Client('http://coop.apps.knpuniversity.com', array(
'request.options' => array(
'exceptions' => false,
)
));

$request = $http->post('/api/540/eggs-collect');
$request->addHeader('Authorization', 'Bearer e48a8653d70d4163ff89fdf06751a9
53cc2664ea');
$response = $request->send();
echo $response->getBody();

echo "\n\n";

Access Credentials
Every OAuth server has an API endpoint used to request access tokens. Por ejemplo la authenticación de
COOPS indica

POST /token
The endpoint used for requesting an access token, using either the authoriz
ation_code or client_credentials grant type.

http://coop.apps.knpuniversity.com/token
This accepts the following POST fields:

client_id
client_secret
grant_type Either client_credentials or authorization_code
redirect_uri (authorization_code only) Must match redirect_uri from the
original /authorize call
code (authorization_code only) The authorization code

Utilizando este código, que incorpora los valores registrados:

<?php
include __DIR__.'/vendor/autoload.php';
use Guzzle\Http\Client;

// create http client (Guzzle)


$http = new Client('http://coop.apps.knpuniversity.com', array(
'request.options' => array(
'exceptions' => false,
)
));

$request = $http->post('/token', null, array(


'client_id' => 'Gallinero',
'client_secret' => '1acccea927d286d4b13cf21a98ca7817',
'grant_type' => 'client_credentials',
));
$response = $request->send();
$responseBody = $response->getBody(true);
var_dump($responseBody);die;

Se recibe:

yerco@yerco:~/webdev/oauth$ php collect.php


string(123) "{"access_token":"5333e140140773395006385ed00c6b5696200022","ex
pires_in":86400,"token_type":"Bearer","scope":"eggs-collect"}"

Fresh tokens
Ahora se puede usar el access_token en lugar de valor que estaba pegado carepalo al principio. Y en cada
llamada se refrescan:

<?php
include __DIR__.'/vendor/autoload.php';
use Guzzle\Http\Client;

// create http client (Guzzle)


$http = new Client('http://coop.apps.knpuniversity.com', array(
'request.options' => array(
'exceptions' => false,
)
));

$request = $http->post('/token', null, array(


'client_id' => 'Gallinero',
'client_secret' => '1acccea927d286d4b13cf21a98ca7817',
'grant_type' => 'client_credentials',
));
$response = $request->send();
$responseBody = $response->getBody(true);
$responseArr = json_decode($responseBody, true);
$accessToken = $responseArr['access_token'];

$request = $http->post('/api/540/eggs-collect');
$request->addHeader('Authorization', 'Bearer ' . $accessToken);
$response = $request->send();
echo $response->getBody();

yerco@yerco:~/webdev/oauth$ php collect.php


{"action":"eggs-collect","success":true,"message":"Hey look at that, 5 eggs
have been collected!","data":5}

yerco@yerco:~/webdev/oauth$ php collect.php


{"action":"eggs-collect","success":true,"message":"Hey, give the ladies a b
reak. Makin\u0027 eggs ain\u0027t easy!","data":null}

Usando tokenes frescos se acaban los probelmas de expiración.

Authorization Code
Se puede tener un server de prueba así (ojo con la carpeta donde se echa a correr):

yerco@yerco:~/Documents/knp_oauth/start/client/web$ php -S localhost:9000


PHP 5.6.4-4 Development Server started at Tue Jan 27 00:25:20 2015
Listening on http://localhost:9000
Document root is /home/yerco/Documents/knp_oauth/start/client/web
Press Ctrl-C to quit.

A la vez este sitio local va a correr toda una implementación, así que para que esa implementación funcione
copio composer.phar a la carpeta

yerco@yerco:~/Documents/knp_oauth/start/client$ ls -lah
total 1.2M
drwx------ 7 yerco yerco 4.0K Jan 27 00:32 .
drwx------ 7 yerco yerco 4.0K Jan 13 22:43 ..
-rw------- 1 yerco yerco 132 Jan 13 22:43 behat.yml.dist
-rw------- 1 yerco yerco 342 Jan 13 22:43 bootstrap.php
-rw------- 1 yerco yerco 518 Jan 13 22:43 composer.json
-rw------- 1 yerco yerco 66K Jan 13 22:43 composer.lock
-rwxr-xr-x 1 yerco yerco 1.1M Jan 26 00:24 composer.phar
drwx------ 2 yerco yerco 4.0K Jan 13 22:43 data
drwx------ 3 yerco yerco 4.0K Jan 13 22:43 features
-rw------- 1 yerco yerco 904 Jan 13 22:43 README.md
drwx------ 3 yerco yerco 4.0K Jan 13 22:43 src
drwx------ 3 yerco yerco 4.0K Jan 13 22:43 views
drwx------ 6 yerco yerco 4.0K Jan 13 22:43 web

e instalo lo que necesito yerco@yerco:~/Documents/knp_oauth/start/client$ php


composer.phar install

Este es todo el log de la instalación

yerco@yerco:~/Documents/knp_oauth/start/client$ php composer.phar install


Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
- Installing facebook/php-sdk (v3.2.3)
Downloading: connection... Failed to download facebook/php-sdk from
dist: The "https://api.github.com/repos/facebook/facebook-php-sdk/zipball/6
714042fa2f5979d4c64c7d11fb4bcab16bdf6cb" file could not be downloaded (HTTP
/1.1 404 Not Found)
Now trying to download from source
- Installing facebook/php-sdk (v3.2.3)
Cloning 6714042fa2f5979d4c64c7d11fb4bcab16bdf6cb

- Installing psr/log (1.0.0)


Downloading: 100%

- Installing symfony/routing (v2.4.1)


Downloading: 100%

- Installing symfony/http-foundation (v2.4.1)


Downloading: 100%

- Installing symfony/event-dispatcher (v2.4.1)


Downloading: 100%

- Installing symfony/debug (v2.4.1)


Downloading: 100%

- Installing symfony/http-kernel (v2.4.1)


Downloading: 100%

- Installing pimple/pimple (v1.1.0)


Downloading: 100%

- Installing silex/silex (v1.1.2)


Downloading: 100%

- Installing symfony/security (v2.4.1)


Downloading: 100%

- Installing twig/twig (v1.15.0)


Downloading: 100%

- Installing symfony/twig-bridge (v2.1.13)


Downloading: 100%

- Installing symfony/finder (v2.4.1)


Downloading: 100%

- Installing behat/gherkin (v2.3.5)


Downloading: 100%

- Installing symfony/css-selector (v2.4.1)


Downloading: 100%

- Installing behat/mink (v1.5.0)


Downloading: 100%

- Installing symfony/yaml (v2.4.1)


Downloading: 100%

- Installing symfony/translation (v2.4.1)


Downloading: 100%

- Installing symfony/dependency-injection (v2.4.1)


Downloading: 100%

- Installing symfony/console (v2.4.1)


Downloading: 100%

- Installing symfony/filesystem (v2.4.1)


Downloading: 100%

- Installing symfony/config (v2.4.1)


Downloading: 100%
- Installing behat/behat (v2.5.1)
Downloading: 100%

- Installing behat/mink-extension (v1.2.0)


Downloading: 100%

- Installing symfony/process (v2.4.1)


Downloading: 100%

- Installing symfony/dom-crawler (v2.4.1)


Downloading: 100%

- Installing symfony/browser-kit (v2.4.1)


Downloading: 100%

- Installing guzzle/guzzle (v3.7.4)


Downloading: 100%

- Installing fabpot/goutte (v1.0.3)


Downloading: connection... Failed to download fabpot/goutte from dis
t: The "https://api.github.com/repos/fabpot/Goutte/zipball/75c9f23c4122caf4
ea3e87a42a00b471366e707f" file could not be downloaded (HTTP/1.1 404 Not Fo
und)
Now trying to download from source
- Installing fabpot/goutte (v1.0.3)
Cloning 75c9f23c4122caf4ea3e87a42a00b471366e707f

- Installing behat/mink-browserkit-driver (v1.1.0)


Downloading: 100%

- Installing behat/mink-goutte-driver (v1.0.9)


Downloading: 100%

- Installing instaclick/php-webdriver (1.0.17)


Downloading: 100%

- Installing behat/mink-selenium2-driver (v1.1.1)


Downloading: 100%
symfony/routing suggests installing doctrine/annotations (For using the ann
otation loader)
symfony/routing suggests installing symfony/expression-language (For using
expression matching)
symfony/http-kernel suggests installing symfony/class-loader ()
silex/silex suggests installing symfony/form (>=2.3,<2.5-dev)
symfony/security suggests installing doctrine/dbal (For using the built-in
ACL implementation)
symfony/security suggests installing ircmaxell/password-compat (For using t
he BCrypt password encoder in PHP <5.5)
symfony/security suggests installing symfony/class-loader (For using the AC
L generateSql script)
symfony/security suggests installing symfony/expression-language (For using
the expression voter)
symfony/security suggests installing symfony/validator (For using the user
password constraint)
symfony/twig-bridge suggests installing symfony/form (2.1.*)
symfony/twig-bridge suggests installing symfony/templating (2.1.*)
behat/mink suggests installing behat/mink-zombie-driver (fast and JS-enable
d headless driver for any app (requires node.js))
symfony/dependency-injection suggests installing symfony/proxy-manager-brid
ge (Generate service proxies to lazy load them)
behat/behat suggests installing behat/symfony2-extension (for integration w
ith Symfony2 web framework)
behat/behat suggests installing behat/yii-extension (for integration with Y
ii web framework)
Generating autoload files

El servidor estaba corriendo en yerco@yerco:~/Documents/knp_oauth/start/client/web$ php -


S localhost:9000

Y aparecieron dramas al estilo

Uncaught exception 'PDOException' with message 'could not find driver' in [


...]

Solución acá http://stackoverflow.com/questions/2852748/pdoexception-could-not-find-driver con el


sqlite fue resuelto.

Ahora tengo un sitio totalmente funcional en http://localhost:9000/ en el cual me puedo registrar


http://localhost:9000/register
Luego de registrarme soy informado

Your Basket of Eggs


To start counting your eggs, you need to authorize Top Cluck to use your CO
OP account! Once you do that, we can count your eggs!

Authorize (este es un botón)

Al clickear el botón (Authorize) aparece el siguiente mensaje:

Implement this in CoopOAuthController::redirectToAuthorization

Esto está en el Controller de la aplicación, a saber:


/home/yerco/Documents/knp_oauth/start/client/src/OAuth2Demo/Client/Controllers/Co
opOAuthController.php . En este archivo se puede cambiar la rutina
redirectToAuthorization(Request $request) que es smplemente lo que hace que se vea ese
texto luego de presionar Authenticate

sqlite

sqlite> .open 'speurders.db'

sqlite> .tables
speurders

sqlite> .schema speurders


CREATE TABLE speurders (
id INTEGER PRIMARY KEY autoincrement,
caller_name text NOT NULL,
phone text NOT NULL,
time_event TIMESTAMP NOT NULL ,
notes text
);

sqlite> select * from speurders;


1|a|34|1449515980|ajhs
2|pep|123456|1449517760|cualquier cosa aqui
sqlite> pragma table_info(speurders);
0|id|INTEGER|0||1
1|caller_name|text|1||0
2|phone|text|1||0
3|time_event|TIMESTAMP|1||0
4|notes|text|0||0

Notes
Para compilar este documento (a pdf):

$ pandoc --latex-engine=xelatex -p -V geometry:margin=2cm oauth.md -s -o


oauth.pdf

Das könnte Ihnen auch gefallen