Unverified Commit 14304d6d authored by Viral Solani's avatar Viral Solani Committed by GitHub

Merge pull request #373 from vidhyut-pandya/use_passport_for_api

Use passport for API
parents fc72d859 64153d45
......@@ -107,8 +107,9 @@ You can now access the server at http://localhost:8000
npm run development
php artisan storage:link
php artisan key:generate
php artisan jwt:secret
php artisan vendor:publish --tag=lfm_public
php artisan migrate
php artisan passport:install
## Please note
......
......@@ -90,11 +90,6 @@ class Handler extends ExceptionHandler
switch (get_class($exception->getPrevious())) {
case \App\Exceptions\Handler::class:
return $this->setStatusCode($exception->getStatusCode())->respondWithError('Token has not been provided.');
case \Tymon\JWTAuth\Exceptions\TokenExpiredException::class:
return $this->setStatusCode($exception->getStatusCode())->respondWithError('Token has expired.');
case \Tymon\JWTAuth\Exceptions\TokenInvalidException::class:
case \Tymon\JWTAuth\Exceptions\TokenBlacklistedException::class:
return $this->setStatusCode($exception->getStatusCode())->respondWithError('Token is invalid.');
}
}
}
......
......@@ -2,10 +2,8 @@
namespace App\Http\Controllers\Api\V1;
use App\Models\Access\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Validator;
class AuthController extends APIController
......@@ -31,14 +29,26 @@ class AuthController extends APIController
$credentials = $request->only(['email', 'password']);
try {
if (!$token = auth('api')->attempt($credentials)) {
if (!Auth::attempt($credentials)) {
return $this->throwValidation(trans('api.messages.login.failed'));
}
} catch (JWTException $e) {
$user = $request->user();
$passportToken = $user->createToken('API Access Token');
// Save generated token
$passportToken->token->save();
$token = $passportToken->accessToken;
} catch (\Exception $e) {
return $this->respondInternalError($e->getMessage());
}
return $token;
return $this->respond([
'message' => trans('api.messages.login.success'),
'token' => $token,
]);
}
/**
......@@ -56,95 +66,16 @@ class AuthController extends APIController
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
public function logout(Request $request)
{
$this->guard()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken($this->guard()->refresh());
try {
$request->user()->token()->revoke();
} catch (\Exception $e) {
return $this->respondInternalError($e->getMessage());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return $token;
return response()->json([
'access_token' => $token,
// 'token_type' => 'bearer',
// 'expires_in' => $this->guard()->factory()->getTTL() * 60
return $this->respond([
'message' => trans('api.messages.logout.success'),
]);
}
/**
* Get the guard to be used during authentication.
*
* @return \Illuminate\Contracts\Auth\Guard
*/
public function guard()
{
return Auth::guard('api');
}
/*
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
// public function logout()
// {
// try {
// $token = JWTAuth::getToken();
// if ($token) {
// JWTAuth::invalidate($token);
// }
// } catch (JWTException $e) {
// return $this->respondInternalError($e->getMessage());
// }
// return $this->respond([
// 'message' => trans('api.messages.logout.success'),
// ]);
// }
/*
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
// public function refresh()
// {
// $token = JWTAuth::getToken();
// if (!$token) {
// $this->respondUnauthorized(trans('api.messages.refresh.token.not_provided'));
// }
// try {
// $refreshedToken = JWTAuth::refresh($token);
// } catch (JWTException $e) {
// return $this->respondInternalError($e->getMessage());
// }
// return $this->respond([
// 'status' => trans('api.messages.refresh.status'),
// 'token' => $refreshedToken,
// ]);
// }
}
......@@ -2,11 +2,9 @@
namespace App\Http\Controllers\Api\V1;
use App\Models\User\User;
use App\Repositories\Frontend\Access\User\UserRepository;
use Config;
use Illuminate\Http\Request;
use JWTAuth;
use Validator;
class RegisterController extends APIController
......@@ -53,7 +51,12 @@ class RegisterController extends APIController
]);
}
$token = JWTAuth::fromUser($user);
$passportToken = $user->createToken('API Access Token');
// Save generated token
$passportToken->token->save();
$token = $passportToken->accessToken;
return $this->respondCreated([
'message' => trans('api.messages.registeration.success'),
......
......@@ -3,8 +3,6 @@
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Tymon\JWTAuth\Middleware\GetUserFromToken;
use Tymon\JWTAuth\Middleware\RefreshToken;
/**
* Class Kernel.
......@@ -76,7 +74,5 @@ class Kernel extends HttpKernel
*/
'access.routeNeedsRole' => \App\Http\Middleware\RouteNeedsRole::class,
'access.routeNeedsPermission' => \App\Http\Middleware\RouteNeedsPermission::class,
'jwt.auth' => GetUserFromToken::class,
'jwt.refresh' => RefreshToken::class,
];
}
......@@ -10,12 +10,12 @@ use App\Models\Access\User\Traits\UserSendPasswordReset;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Laravel\Passport\HasApiTokens;
/**
* Class User.
*/
class User extends Authenticatable implements JWTSubject
class User extends Authenticatable
{
use UserScope,
UserAccess,
......@@ -23,7 +23,8 @@ class User extends Authenticatable implements JWTSubject
SoftDeletes,
UserAttribute,
UserRelationship,
UserSendPasswordReset;
UserSendPasswordReset,
HasApiTokens;
/**
* The database table used by the model.
*
......
......@@ -3,6 +3,7 @@
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;
/**
* Class AuthServiceProvider.
......@@ -27,6 +28,6 @@ class AuthServiceProvider extends ServiceProvider
{
$this->registerPolicies();
//
Passport::routes();
}
}
This diff is collapsed.
......@@ -198,8 +198,8 @@ return [
App\Providers\TelescopeServiceProvider::class,
App\Providers\HistoryServiceProvider::class,
App\Providers\RouteServiceProvider::class,
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
Bvipul\Generator\Provider\CrudGeneratorServiceProvider::class,
Laravel\Passport\PassportServiceProvider::class,
],
/*
......@@ -258,7 +258,6 @@ return [
'Gravatar' => Creativeorange\Gravatar\Facades\Gravatar::class,
'Html' => Collective\Html\HtmlFacade::class,
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
//'Datatables' => Yajra\DataTables\Facades\DataTables::class
],
];
......@@ -44,7 +44,7 @@ return [
],
'api' => [
'driver' => 'jwt',
'driver' => 'passport',
'provider' => 'users',
],
],
......
<?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Tymon\JWTAuth\Claims;
return [
/*
|--------------------------------------------------------------------------
| JWT Authentication Secret
|--------------------------------------------------------------------------
|
| Don't forget to set this in your .env file, as it will be used to sign
| your tokens. A helper command is provided for this:
| `php artisan jwt:secret`
|
| Note: This will be used for Symmetric algorithms only (HMAC),
| since RSA and ECDSA use a private/public key combo (See below).
|
*/
'secret' => env('JWT_SECRET'),
/*
|--------------------------------------------------------------------------
| JWT Authentication Keys
|--------------------------------------------------------------------------
|
| The algorithm you are using, will determine whether your tokens are
| signed with a random string (defined in `JWT_SECRET`) or using the
| following public & private keys.
|
| Symmetric Algorithms:
| HS256, HS384 & HS512 will use `JWT_SECRET`.
|
| Asymmetric Algorithms:
| RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below.
|
*/
'keys' => [
/*
|--------------------------------------------------------------------------
| Public Key
|--------------------------------------------------------------------------
|
| A path or resource to your public key.
|
| E.g. 'file://path/to/public/key'
|
*/
'public' => env('JWT_PUBLIC_KEY'),
/*
|--------------------------------------------------------------------------
| Private Key
|--------------------------------------------------------------------------
|
| A path or resource to your private key.
|
| E.g. 'file://path/to/private/key'
|
*/
'private' => env('JWT_PRIVATE_KEY'),
/*
|--------------------------------------------------------------------------
| Passphrase
|--------------------------------------------------------------------------
|
| The passphrase for your private key. Can be null if none set.
|
*/
'passphrase' => env('JWT_PASSPHRASE'),
],
/*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 30 minutes.
|
| You can also set this to null, to yield a never expiring token.
| Some people may want this behaviour for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
|
*/
'ttl' => env('JWT_TTL', 30),
/*
|--------------------------------------------------------------------------
| Max refresh period
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be
| refreshable for.
|
| Defaults to null, which will allow tokens to be refreshable forever.
|
*/
'max_refresh_period' => env('JWT_MAX_REFRESH_PERIOD'),
/*
|--------------------------------------------------------------------------
| JWT hashing algorithm
|--------------------------------------------------------------------------
|
| Specify the hashing algorithm that will be used to sign the token.
|
| Possible values:
|
| 'HS256', 'HS384', 'HS512',
| 'RS256', 'RS384', 'RS512',
| 'ES256', 'ES384', 'ES512'
|
*/
'algo' => env('JWT_ALGO', 'HS256'),
/*
|--------------------------------------------------------------------------
| Required Claims
|--------------------------------------------------------------------------
|
| Specify the required claims that must exist in any token.
| A TokenInvalidException will be thrown if any of these claims are not
| present in the payload.
|
*/
'required_claims' => [
Claims\Issuer::NAME,
Claims\IssuedAt::NAME,
Claims\Expiration::NAME,
Claims\Subject::NAME,
Claims\JwtId::NAME,
],
/*
|--------------------------------------------------------------------------
| Lock Subject
|--------------------------------------------------------------------------
|
| This will determine whether a `prv` claim is automatically added to
| the token. The purpose of this is to ensure that if you have multiple
| authentication models e.g. `App\User` & `App\OtherPerson`, then we
| should prevent one authentication request from impersonating another,
| if 2 tokens happen to have the same id across the 2 different models.
|
| Under specific circumstances, you may want to disable this behaviour
| e.g. if you only have one authentication model, then you would save
| a little on token size.
|
*/
'lock_subject' => true,
/*
|--------------------------------------------------------------------------
| Leeway
|--------------------------------------------------------------------------
|
| This property gives the jwt timestamp claims some "leeway".
| Meaning that if you have any unavoidable slight clock skew on
| any of your servers then this will afford you some level of cushioning.
|
| This applies to the claims `iat`, `nbf` and `exp`.
|
| Specify in seconds - only if you know you need it.
|
*/
'leeway' => env('JWT_LEEWAY', 0),
/*
|--------------------------------------------------------------------------
| Blacklist Enabled
|--------------------------------------------------------------------------
|
| In order to invalidate tokens, you must have the blacklist enabled.
| If you do not want or need this functionality, then set this to false.
|
*/
'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),
/*
| -------------------------------------------------------------------------
| Blacklist Grace Period
| -------------------------------------------------------------------------
|
| When multiple concurrent requests are made with the same JWT,
| it is possible that some of them fail, due to token regeneration
| on every request.
|
| Set grace period in seconds to prevent parallel request failure.
|
*/
'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),
/*
|--------------------------------------------------------------------------
| Cookies encryption
|--------------------------------------------------------------------------
|
| By default Laravel encrypt cookies for security reason.
| If you decide to not decrypt cookies, you will have to configure Laravel
| to not encrypt your cookie token by adding its name into the $except
| array available in the middleware "EncryptCookies" provided by Laravel.
| see https://laravel.com/docs/master/responses#cookies-and-encryption
| for details.
|
| Set it to true if you want to decrypt cookies.
|
*/
'decrypt_cookies' => false,
/*
|--------------------------------------------------------------------------
| Providers
|--------------------------------------------------------------------------
|
| Specify the various providers used throughout the package.
|
*/
'providers' => [
/*
|--------------------------------------------------------------------------
| JWT Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to create and decode the tokens.
|
*/
'jwt' => Tymon\JWTAuth\Providers\JWT\Lcobucci::class,
/*
|--------------------------------------------------------------------------
| Storage Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to store tokens in the blacklist.
|
*/
'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,
],
];
......@@ -97,7 +97,7 @@ RUN chown -R 777 /var/www/html/
RUN composer install
RUN php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
#RUN php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
......
......@@ -18,7 +18,7 @@ Route::group(['namespace' => 'Api\V1', 'prefix' => 'v1', 'as' => 'v1.'], functio
Route::post('login', 'AuthController@login');
});
Route::group(['middleware' => ['jwt.auth']], function () {
Route::group(['middleware' => ['auth:api']], function () {
Route::group(['prefix' => 'auth'], function () {
Route::post('logout', 'AuthController@logout');
Route::post('refresh', 'AuthController@refresh');
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment