Crear una nueva aplicacion laravel
composer create-project --prefer-dist laravel/laravel blog
Dentro de la carpeta del proyecto creado instalar Passport
composer require laravel/passport
Editar el archivo config/app.php
y en la seccion donde se registren providers agregar una nueva entrada para Passport
'providers' =>[ Laravel\Passport\PassportServiceProvider::class, ],
Crear la base de datos que usara la aplicacion y setear los datos de conexion en el archivo .env
Ejecutar la migracion
php artisan migrate
Instalar Passport para que genere los tokens de seguridad
php artisan passport:install
Editar app/User.php
use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable;
Editar app/Providers/AuthServiceProvider.php
use Laravel\Passport\Passport; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ 'App\Model' => 'App\Policies\ModelPolicy', ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); Passport::routes(); // } }
Editar config/auth.php en la seccion de guards cambiar la entrada para api/driver a passport
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ],
Crear la api route editando el archivo routes/api.php
Route::post('login', 'API\UserController@login'); Route::post('register', 'API\UserController@register'); Route::group( ['middleware' => 'auth:api'], function(){ Route::get('details', 'API\UserController@details'); });
crear la carpeta API en app/Http/Controllers
en esa carpeta crear el controlador UserController.php
<?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\User; use Illuminate\Support\Facades\Auth; use Validator; class UserController extends Controller { public $successStatus = 200; /** * login api * * @return \Illuminate\Http\Response */ public function login(){ if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ $user = Auth::user(); $success['token'] = $user->createToken('MyApp')-> accessToken; return response()->json(['success' => $success], $this-> successStatus); } else{ return response()->json(['error'=>'Unauthorised'], 401); } } /** * Register api * * @return \Illuminate\Http\Response */ public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email', 'password' => 'required', 'c_password' => 'required|same:password', ]); if ($validator->fails()) { return response()->json(['error'=>$validator->errors()], 401); } $input = $request->all(); $input['password'] = bcrypt($input['password']); $user = User::create($input); $success['token'] = $user->createToken('MyApp')-> accessToken; $success['name'] = $user->name; return response()->json(['success'=>$success], $this-> successStatus); } /** * details api * * @return \Illuminate\Http\Response */ public function details() { $user = Auth::user(); return response()->json(['success' => $user], $this-> successStatus); } }
Ya podemos probar la api rest:
la de creacion/registro de usuarios
POST http://localhost/authblog/public/api/register
Y en el body ( fom-data ) envio
name
password
c_password
el de login
POST http://localhost/authblog/public/api/login
Y en el body ( fom-data ) enviopasswordque nos devolvera algo similar:{ "success": { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImZjODRmMzhhZjg3MmNlZTM0ZDgyZGRlZjNkNDI3OWU0OGE3MjIzYmY5ZjY1ZDVkN2ZlOWNhN2ExNWQ5NGZhNWFiMDg0ZTM1ZmE3N2U4NjgzIn0.eyJhdWQiOiIxIiwianRpIjoiZmM4NGYzOGFmODcyY2VlMzRkODJkZGVmM2Q0Mjc5ZTQ4YTcyMjNiZjlmNjVkNWQ3ZmU5Y2E3YTE1ZDk0ZmE1YWIwODRlMzVmYTc3ZTg2ODMiLCJpYXQiOjE1MzQ2NDcwMDIsIm5iZiI6MTUzNDY0NzAwMiwiZXhwIjoxNTY2MTgzMDAyLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.FWOKWiOsWLv5oWrIWPKCsMRFd9k2DXMePgr6bWZRVwQqTj-8V5c5ZNfsntDehNnZ0mP0IWBgA9NtjFBeC-VUwsN4uowi3nd8LMINtkMhPa61mPXkem83hxA0t4ZO46dWWggq64kXCkwZz0CRkv99F4RRVd3G6_upKbMZy0U-t-G0GNC8uXs6OQsIGDoTGTAxdUSs7fbS4uC4TinYAirxibBpbXGRTE0Hxr4-ji5vKU0myHPPk9xg-6x4kHin6JVXvIU5QHkWJxYDXOaou0OF2znW8huG7L-s4G4zUmHbID6vc8ycIkdpGP2lFRaomyVtwtnQMze6YLCYEQtf28JfBaMyuejsPzj788Dv0ijK7BJmfc0zOgsuOqb3xkzgczAtmlJarwbJlEVHCH99tAP1iC75lNHw1lgo1_EcU9aRvRrmmGaEb4GIQdFqf7O5Hf5trmiFpszEVOGkGxQVe1acs_HIpv9ivUAkh5aPDczI2ZrH7WAXnyIcaO92OqX4ZbdTtpyk-J-ExXiNCjjfyg7bOsh3sXwZKO76hlpp1oPiAwbj1hrTND8Gz5_0nE37pqG0cu65m81VnwGezs3nOCnBkHsvQ6FiIdK_ViBOS9rnUaypwMCEjnJLimdNjI-jFZBJ1dUkws2GHlianISxegFq6pmBiBMtX0dZTJeEUu3je_M" } }el que trae los detalles de un usuarioGET http://localhost/authblog/public/api/detailsen este caso debemos enviar en el headerAccept -> application/jsonAuthorization -> Bearer {{el token que se obtiene en el login}}que nos devolvera algo asi:{ "success": { "id": 1, "name": "ibazan", "email": "israelbazan76@gmail.com", "created_at": "2018-08-18 22:42:41", "updated_at": "2018-08-18 22:42:41" } }
Cuando lo pruebo me devuelve un error: 404 Not Found .. No se que estoy haciendo mal?
ResponderEliminar