Skip to content

Instantly share code, notes, and snippets.

@thephucit
Last active January 7, 2021 10:14
Show Gist options
  • Save thephucit/821db535ee7609e17b81d27af9d19667 to your computer and use it in GitHub Desktop.
Save thephucit/821db535ee7609e17b81d27af9d19667 to your computer and use it in GitHub Desktop.
Config JWT in Octobercms
  • cài package: "tymon/jwt-auth": "^0.5.12"
  • tạo file config/auth.php với nội dung bên dưới
  • tạo file authorName/pluginName/config/config.php với nội dung bên dưới
  • tạo fiel authorName/pluginName/classes/JWTAuthServiceProvider.php với nội dung bên dưới
  • vào function boot của Plugin.php thêm nội dung
use App;
use Illuminate\Foundation\AliasLoader;

$this->app->bind(\Illuminate\Auth\AuthManager::class, function($app){
    return new \Illuminate\Auth\AuthManager($app);
});

App::register('\Cma\HbcStore\Classes\JWTAuthServiceProvider');
$facade = AliasLoader::getInstance();
$facade->alias('JWTAuth', '\Tymon\JWTAuth\Facades\JWTAuth');
$facade->alias('JWTFactory', '\Tymon\JWTAuth\Facades\JWTFactory');

App::singleton('auth', function ($app) {
    return new \Illuminate\Auth\AuthManager($app);
});
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \Backend\Models\User::class,
],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| Here you may set the options for resetting passwords including the view
| that is your password reset e-mail. You may also set the name of the
| table that maintains all of the reset tokens for your application.
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
<?php
return [
'packages' => [
'tymon/jwt-auth' => [
'config_namespace' => 'jwt',
'config' => [
'secret' => env('JWT_SECRET', '7MWOiEIaQ5KK8faP9EwfIxVcatEl05SX'),
'ttl' => env('JWT_TTL', 10080), // 1 week is default
'refresh_ttl' => 20160,
'algo' => 'HS256',
'user' => 'Backend\Models\User',
'identifier' => 'id',
'required_claims' => ['iss', 'iat', 'exp', 'nbf', 'sub', 'jti'],
'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),
'providers' => [
'user' => 'Tymon\JWTAuth\Providers\User\EloquentUserAdapter',
'jwt' => 'Tymon\JWTAuth\Providers\JWT\NamshiAdapter',
'auth' => 'Tymon\JWTAuth\Providers\Auth\IlluminateAuthAdapter',
'storage' => 'Tymon\JWTAuth\Providers\Storage\IlluminateCacheAdapter',
],
]
]
],
/*
|--------------------------------------------------------------------------
| JWT Authentication Secret
|--------------------------------------------------------------------------
|
| Don't forget to set this, as it will be used to sign your tokens.
| A helper command is provided for this: `php artisan jwt:generate`
|
*/
'secret' => env('JWT_SECRET', '7MWOiEIaQ5KK8faP9EwfIxVcatEl05SX'),
/*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour
|
*/
// 'ttl' => 100031,
/*
|--------------------------------------------------------------------------
| Refresh time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token can be refreshed
| within. I.E. The user can refresh their token within a 2 week window of
| the original token being created until they must re-authenticate.
| Defaults to 2 weeks
|
*/
// 'refresh_ttl' => 20160,
/*
|--------------------------------------------------------------------------
| JWT hashing algorithm
|--------------------------------------------------------------------------
|
| Specify the hashing algorithm that will be used to sign the token.
|
| See here: https://github.com/namshi/jose/tree/2.2.0/src/Namshi/JOSE/Signer
| for possible values
|
*/
'algo' => 'HS256',
/*
|--------------------------------------------------------------------------
| User Model namespace
|--------------------------------------------------------------------------
|
| Specify the full namespace to your User model.
| e.g. 'Acme\Entities\User'
|
*/
'user' => 'Backend\Models\User',
/*
|--------------------------------------------------------------------------
| User identifier
|--------------------------------------------------------------------------
|
| Specify a unique property of the user that will be added as the 'sub'
| claim of the token payload.
|
*/
'identifier' => 'id',
/*
|--------------------------------------------------------------------------
| 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' => ['iss', 'iat', 'exp', 'nbf', 'sub', 'jti'],
/*
|--------------------------------------------------------------------------
| Blacklist Enabled
|--------------------------------------------------------------------------
|
| In order to invalidate tokens, you must have the the blacklist enabled.
| If you do not want or need this functionality, then set this to false.
|
*/
'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),
/*
|--------------------------------------------------------------------------
| Providers
|--------------------------------------------------------------------------
|
| Specify the various providers used throughout the package.
|
*/
'providers' => [
/*
|--------------------------------------------------------------------------
| User Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to find the user based
| on the subject claim
|
*/
'user' => 'Tymon\JWTAuth\Providers\User\EloquentUserAdapter',
/*
|--------------------------------------------------------------------------
| JWT Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to create and decode the tokens.
|
*/
'jwt' => 'Tymon\JWTAuth\Providers\JWT\NamshiAdapter',
/*
|--------------------------------------------------------------------------
| Authentication Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to authenticate users.
|
*/
'auth' => 'Tymon\JWTAuth\Providers\Auth\IlluminateAuthAdapter',
/*
|--------------------------------------------------------------------------
| Storage Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to store tokens in the blacklist
|
*/
'storage' => 'Tymon\JWTAuth\Providers\Storage\IlluminateCacheAdapter',
],
];
<?php namespace \Classes;
use Config;
class JWTAuthServiceProvider extends \Tymon\JWTAuth\Providers\JWTAuthServiceProvider
{
/**
* Helper to get the config values.
*
* @param string $key
* @param mixed $default
* @return string
*/
protected function config($key, $default = null)
{
$val = Config::get('cma.hbcstore::' . $key);
return $val ?: parent::config($key, $default);
}
}
<?php
/**
* login
* @return json
*/
public function login()
{
$credentials = [
'login' => strtolower(post('login')),
'password' => post('password'),
];
try {
if (! $token = JWTAuth::attempt($credentials)) {
return ['error' => 'Tên đăng nhập hoặc mật khẩu không đúng.', 'status' => false];
}
} catch (JWTException $e) {
return ['error' => $e->getMessage(), 'status' => false];
}
$user = JWTAuth::authenticate($token);
$user->token = $token;
AccessLog::add($user);
return $user;
}
/**
* register user
* @return json
*/
public function register()
{
try {
$user = BackendAuth::register([
'login' => post('email'),
'email' => post('email'),
'phone' => post('phone'),
'address' => post('address'),
'first_name' => post('fullname'),
'password' => post('password'),
'password_confirmation' => post('password_confirmation'),
], true);
return $user;
} catch (\Exception $e) {
return ['error' => $e->getMessage(), 'status' => false];
}
}
@thephucit
Copy link
Author

{
"require": {
"php": ">=7.0",
"ext-mbstring": "",
"ext-openssl": "
",
"october/rain": "~1.0",
"october/system": "~1.0",
"october/backend": "~1.0",
"october/cms": "~1.0",
"laravel/framework": "5.5.*",
"tymon/jwt-auth": "^0.5.12"
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment