In my Laravel project, I use jwt for user authentication.I successfully login and receive the token. I send the token with the Barear prefix in the header but I get a 401 error.Meanwhile, my project works well on localhost, but it has this problem on cpanel hosts.My codes are below
//AuthController
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('JWT', ['except' => ['login', 'signup']]);
}
public function login(\Illuminate\Http\Request $request)
{
$credentials = request(['username', 'password']);
$result= new ResultModel();
if (!$token = auth()->attempt($credentials)) {
$result->message="Wrong username or password";
$result->code=401;
$result->is_success=false;
$result->status=ResultModel::WARNING;
$result->result= null;
return response()->json($result, 401);
}
$result->result= $token;
return response()->json($result, 200);
}
}
in config/auth.php
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
and in \config\jwt.php
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 1 hour.
|
| 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.
| Notice: If you set this to null you should remove 'exp' element from 'required_claims' list.
|
*/
'ttl' => env('JWT_TTL', 180),
/*
|--------------------------------------------------------------------------
| 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.
|
| You can also set this to null, to yield an infinite refresh time.
| Some may want this instead of never expiring tokens 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.
|
*/
'refresh_ttl' => env('JWT_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/master/src/Namshi/JOSE/Signer/OpenSSL
| for possible values.
|
*/
'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' => [
'iss',
'iat',
'exp',
'nbf',
'sub',
'jti',
],
/*
|--------------------------------------------------------------------------
| Persistent Claims
|--------------------------------------------------------------------------
|
| Specify the claim keys to be persisted when refreshing a token.
| `sub` and `iat` will automatically be persisted, in
| addition to the these claims.
|
| Note: If a claim does not exist then it will be ignored.
|
*/
'persistent_claims' => [
// 'foo',
// 'bar',
],
/*
|--------------------------------------------------------------------------
| 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,
/*
|--------------------------------------------------------------------------
| Authentication Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to authenticate users.
|
*/
'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,
/*
|--------------------------------------------------------------------------
| Storage Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to store tokens in the blacklist.
|
*/
'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,
],
];
my web route:
Route::get('/', function () {
return view('welcome');
});
Route::get('/{vue_capture?}', function () {
return view('welcome');
})->where('vue_capture', '[\/\w\.-]*');
my api route:
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('login', 'AuthController#login');
Route::post('logout', 'AuthController#logout');
Route::post('signup', 'AuthController#signup');
Route::post('refresh', 'AuthController#refresh');
Route::post('me', 'AuthController#me');
});
Route::middleware('auth')->apiResource('/fabric', 'FabricController');
Route::middleware('auth')
->post('/fabricLading','FabricController#fabricLading');
Route::middleware('auth')->get('/machines',
'FabricController#getMachines');
Thanks in advance for your guidance
I also had this problem and did the following things. My problem was solved.
First install jwt here
and finaly
composer update
I am using Laravel 5.1 and the mustafaaloko/elasticquent5 package (found here).
But when trying to return results, I can only get results when searching for the exact word. If I try to search part of the word, it returns nothing.
I am using Profile::addAllToIndex(); and dd(Profile::search(Input::get('search_term')));
My config looks like this:
<?php
return array(
/*
|--------------------------------------------------------------------------
| Custom Elasticsearch Client Configuration
|--------------------------------------------------------------------------
|
| This array will be passed to the Elasticsearch client.
| See configuration options here:
|
| http://www.elasticsearch.org/guide/en/elasticsearch/client/php-api/current/_configuration.html
*/
'config' => [
'hosts' => ['ahp.dev:9200'],
'logging' => true,
'logPath' => storage_path() . '/logs/elasticsearch.log',
'logLevel' => Monolog\Logger::WARNING,
],
/*
|--------------------------------------------------------------------------
| Default Index Name
|--------------------------------------------------------------------------
|
| This is the index name that Elastiquent will use for all
| Elastiquent models.
*/
'default_index' => 'default',
);
You should try to use searchByQuery instead of search and use a query_string query
Profile::searchByQuery(array('query_string' => array('query' => Input::get('search_term'))));
Authentication always fails (always prints bad - see the last code block below). I've tried dozens of solutions across StackOverflow.
Can anyone help me figure out what the problem is?
my user model
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'usersnew';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
my auth.php
return array(
/*
|--------------------------------------------------------------------------
| Default Authentication Driver
|--------------------------------------------------------------------------
|
| This option controls the authentication driver that will be utilized.
| This driver manages the retrieval and authentication of the users
| attempting to get access to protected areas of your application.
|
| Supported: "database", "eloquent"
|
*/
'driver' => 'eloquent',
/*
|--------------------------------------------------------------------------
| Authentication Model
|--------------------------------------------------------------------------
|
| When using the "Eloquent" authentication driver, we need to know which
| Eloquent model should be used to retrieve your users. Of course, it
| is often just the "User" model but you may use whatever you like.
|
*/
'model' => 'User',
/*
|--------------------------------------------------------------------------
| Authentication Table
|--------------------------------------------------------------------------
|
| When using the "Database" authentication driver, we need to know which
| table should be used to retrieve your users. We have chosen a basic
| default value but you may easily change it to any table you like.
|
*/
'table' => 'users',
/*
|--------------------------------------------------------------------------
| Password Reminder Settings
|--------------------------------------------------------------------------
|
| Here you may set the settings for password reminders, including a view
| that should be used as your password reminder e-mail. You will also
| be able to set the name of the table that holds the reset tokens.
|
| The "expire" time is the number of minutes that the reminder 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.
|
*/
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
The function I'm trying to run:
$input = Input::all();
$attempt = Auth::attempt( array('email' => $input['email'], 'password' => $input['password']) );
if($attempt) {
echo 123;
} else {
echo 'bad';
}
I want to thank Saint Genius and joe_archer
apparently if I don't use hashed passwords auth isn't working...
Thank you so much guys!
I've seen through all other questions but I can't figure why My Auth::attempt is not working
Then, I'll display the code involved on it:
-- models/Usuario.php --
use \Illuminate\Auth\UserInterface;
class Usuario extends Eloquent implements UserInterface{
protected $table = 'User_Account';
protected $hidden = array('password');
public function getAuthIdentifier() {
return $this->getKey();
}
public function getAuthPassword() {
return $this->password;
}
}
?>
auth.php
<?php
return array(
/*
|--------------------------------------------------------------------------
| Default Authentication Driver
|--------------------------------------------------------------------------
|
| This option controls the authentication driver that will be utilized.
| This driver manages the retrieval and authentication of the users
| attempting to get access to protected areas of your application.
|
| Supported: "database", "eloquent"
|
*/
'driver' => 'eloquent',
/*
|--------------------------------------------------------------------------
| Authentication Model
|--------------------------------------------------------------------------
|
| When using the "Eloquent" authentication driver, we need to know which
| Eloquent model should be used to retrieve your users. Of course, it
| is often just the "User" model but you may use whatever you like.
|
*/
'model' => 'Usuario',
/*
|--------------------------------------------------------------------------
| Authentication Table
|--------------------------------------------------------------------------
|
| When using the "Database" authentication driver, we need to know which
| table should be used to retrieve your users. We have chosen a basic
| default value but you may easily change it to any table you like.
|
*/
'table' => 'User_Account',
/*
|--------------------------------------------------------------------------
| Password Reminder Settings
|--------------------------------------------------------------------------
|
| Here you may set the settings for password reminders, including a view
| that should be used as your password reminder e-mail. You will also
| be able to set the name of the table that holds the reset tokens.
|
| The "expire" time is the number of minutes that the reminder 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.
|
*/
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
My Route::post(Controller#method) here:
$validator = $this->getLoginValidator();
if ($validator->passes()) {
if(Auth::attempt(array('username' => Input::get('username'), 'password' => Input::get('password')))){
echo "entrou";
}
echo "n entrou";
} else{
echo "Validation failed!";
}
I've seen what comes from each Input::get and everything seems alright.
Just to information, my tables like this:
Column Type Null Default Comments
id int(8) No
firstname varchar(40) No
lastname varchar(40) No
password varchar(60) No
username varchar(40) No
points int(8) No 0
created_at datetime No
updated_at datetime No
If you need additional information in order to help me, I'd freely give.
I'm working a reasonably large zf1 project with multiple modules. We need to store the session state in the database for a new deployment. After a quick google we came across Zend_Session_SaveHandler_DbTable and followed the simple example (almost exactly) at http://framework.zend.com/manual/1.12/en/zend.session.savehandler.dbtable.html . I've placed the code in our application/Bootstrap.php and have checked it runs. However the database table is never populated with session data.
I thought something would be overriding the Zend_Session::setSaveHandler later in the code base but I can not find any other calls to that or Zend_Session::start();
Any suggestions on what might be wrong or how to investigate further?
edit with updated information:
here's how the relevant section of the bootstrap appears, currently just set up for dev mode.
protected function _initSessionDB()
{
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' =>'localhost',
'username' => '****',
'password' => '****',
'dbname' => '****'
));
Zend_Db_Table_Abstract::setDefaultAdapter($db);
$config = array(
'name' => 'session_state',
'primary' => 'id',
'modifiedColumn' => 'modified',
'dataColumn' => 'data',
'lifetimeColumn' => 'lifetime'
);
Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_DbTable($config));
Zend_Session::start();
}
and the database has
mysql> explain session_state;
+----------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
| id | char(32) | YES | | NULL | |
| modified | int(11) | YES | | NULL | |
| lifetime | int(11) | YES | | NULL | |
| data | text | YES | | NULL | |
+----------+----------+------+-----+---------+-------+
4 rows in set (0.00 sec)
So turns out that the application I was working on sets up the FlashMessenger controller helper in the application/Bootstrap.
protected function _initAutoload()
{
Zend_Controller_Action_HelperBroker::addHelper(
new Zend_Controller_Action_Helper_FlashMessenger());
}
The FlashMessenger action helper makes its own call to Zend_Session::start(); which seems to take priority over any later calls.
Simple solution is to add a $this->bootstrap('sessionDB'); call before the FlashMessenger is created. for example,
protected function initFlashMessenger()
{
$this->bootstrap('sessionDB');
if (APPLICATION_ENV != 'testing')
Zend_Controller_Action_HelperBroker::addHelper(
new Zend_Controller_Action_Helper_FlashMessenger());
}
A better solution would be to not create the FlashMessenger in the bootstrap at all and just create it within controllers or appropriate base controller.