How to get data from JWT if didn't have users table in laravel? - laravel

I try to implement microservice arhitecture.Because I new in it,can maybe someone can tell me:
- can I use JWT for communication to services,when someone login into one service.Is that secure way or there is something better?
- how do I parse JWT and get user id or some other data from it to have it in other service which didn't have users table?Like is it expiried,user id...
Thank you a loot if someone can help me to send me a direction for it.

I'm partial to the tymon/jwt-auth package for this, which largely uses 'namshi/jose' under the hood. As long as the jwt.secret is the same between each system that may need to use the tokens, you should be able to just call JWTAuth::getPayload($token)->toArray() to decode them.
You do need a user table, but it doesn't have to be the user table already speced out in Laravel. Any Model that implements the Illuminate\Auth\Authenticatable interface, such as by extending the Illuminate\Foundation\Auth\User model will do.
If you want to inject additional data into the token beyond the user table that the login credentials are being validated against, just add an array as the second parameter to the login attempt:
//The key names here are defined by the return values of methods described in the Authenticatable interface.
$credentials = [
'username' => 'your_user',
'password' => 'your_password'
];
$customClaims = [
'someOtherDatapoint' => 'more_data'
];
$token = JWTAuth::attempt($credentials, $customClaims);
You could also go directly to the token-creation without authentication:
$user = app(YourUserModel::class)->first($id);
$token = JWTAuth::fromUser($user, $customClaims);
This is relatively secure, but I'm not sure if it's the best way to communicate encrypted data. You might want to just use the encrypt() and decrypt() helper functions, that are based off the APP_KEY. You could also look at Laravel-Passport, https://laravel.com/docs/5.6/passport, for authentication, which uses OAuth2.

Related

Add UserType To JWT Token IN laravel

How Can I Bind userType with jwt token??
because in the frontend needs to do some operations with type of user(hide some menus if userType is different)
in laravel.. Does it possible?
The way Laravel (and you most likely using https://github.com/tymondesigns/jwt-auth), is that the JWT should probably not carry user types or really other kind of user information than maybe a name or an id. After the token is generated, you are supposed to query another endpoint that will return the user information that you are looking for.
So essentially, what you want is 2 routes, let's say:
POST /auth/login
POST /auth/me
To the first route, you are supposed to provide the username and password, to which you'll get a token if credentials are correct. Then, you take the token you were just given, and call the second endpoint, which will return all user information you might want or need. You don't specify which kind of frontend you are using, but here's an example with Nuxt.js's Auth module: https://auth.nuxtjs.org/providers/laravel-jwt/

Laravel middleware is "bypassed" when i submit the invalid token, but when it is a valid token, the middleware is executed

all my fellow friends, i have a question.
Route::group([
'middleware' => ['ensure.role:store', 'auth:api']
]
For simplification,
i have two roles : ADMIN and STORE
I have created a middleware that will validate user role, and if the user role is correct, then will allow the user to access the route.
It works fine.
I tried using ADMIN Jwt Token to access STORE routes, and rightfully i am kicked out, and vice versa.
But now, if i modify the token, lets say i add a string to any part of the token, and try to access any route, actually i am allowed to.
I tried var_dump and print something on the related middleware, and here are my observation.
1. If the token is VALID as one of the user role, then
the var_dump is executed, (means the middleware is executed)
2. if the token is INVALID as in i add / modify the original
token, then the var_dump is not executed, and so are the
others route middleware.
I am wondering what causes this behavior, and what could be the fix for this issue, as i need to throw 401 unauthenticated in any token invalid case.
Thank you
I figured it out.
After series of testing and reading, i found out that after laravel 5.3 and above, constructor is called before middleware. And because in my constructor i am using an user object before i am authenticated by the middleware, i encountered constructor error, because user is null.
Of course it is a bad practice to use user object in the construct, however due to the convenience of usage, i still decided to use it.
It sounds complex to use closure based middleware as alternative solution
So i use a workaround to do it.
I create a helper function that return me true if there is an user object or return abort(401); if there is no user object, then add this one line to all the constructors.
$this->checkAccess = EnsureRoleUtil::check('admin');
After that, i just do my next constructor as normally
public function __construct() {
$this->checkAccess = EnsureRoleUtil::check('admin');
$this->user = Auth::user();
$this->categoryM = new CategoryManager($this->user);
}
However, to be noted, it is not a good practice, it is just a hack / workaround.

Laravel Encryptable Trait Failing Authentication

I'm running into trouble with authentication handling in my Laravel 5.5. I have installed an Encryptable trait according to this post here. I then used the authentication generator to establish the base routes, views and handler.
I can successfully register new accounts and visually see that all of the data is encrypted, but I cannot successfully authenticate through the login screen.
This seems to be failing during the Auth::attempt($credentials) call. My troubleshooting is pointing to the encryptable trait because when I comment that section out, the authentication works fine.
Can someone offer insight as to how to handle authentication using this method of model encryption?
I have attempted disabling encryption for the username field, but this didn't seem to help. The password field was never being encrypted, becasue it is being hashed by bcrypt.
1st Edit:
So, with an understanding of how traits work... The Encryptable trait seems to be overloading the getAttribute/setAttribute functions. This would mean that Eloquent's querying functions like where, find, etc. will just be "looking at" encrypted values.
2nd Edit:
The source code provided for the Encryptable trait was not returning proper values for unencrypted values. This was changed and authentication was restored. To those using the same code snippet, in the get_attribute() function, change the else block so that it return $value;.
I appreciate all insights,
Dan
This form of encryption will void your ability to search the table for the encrypted fields. You won't be able to reproduce the same string because Laravel uses a random iv when producing encrypted data. An IV, or initialization vector, serves a similar purpose as a salt in hashing, to randomize the stored data.
Due to this randomization of data, you wouldn't even be able to search your table by re-encrypting the search data:
User::where('email', Crypt::encrypt('email#email.com'));
// won't find anything even if an encrypted value of email#email.com exists
Running in an interactive shell allows you to see encrypt returns a completely different value on subsequent runs:
>>> json_decode(base64_decode(Crypt::encrypt('email#email.com')))->value
=> "zpA0LBsbkGCAagxLYB6kiqwJZmm7HSCVm4QrUw6W8SE="
>>> json_decode(base64_decode(Crypt::encrypt('email#email.com')))->value
=> "VKz8CWVzR66cv/J7J09K+TIVwQPxcIg+SDqQ32Sr7rU="
Therefore, you may want to be selective about what you actually encrypt. Encrypt things that are sensitive and you wouldn't use to lookup an entity. This could be something like social security numbers, government IDs, credit card numbers, and bank account numbers.

Laravel - user login

I use Laravel 5.4 and need to login user in my system. I have next login.blade.php
where i have email and password field. In my controller I have next
protected function log() {
$email=Input::get('email');
$pass=Input::get('password');
$user = DB::select("SELECT * FROM users where email = '".$email."' and password = '".$pass."'");
foreach($user as $users){
if(Input::get('email') == $users->email){
return redirect('/');
}else{
return view('site.warning');
}
}
}
How can I return logged user in my redirect('/') and show them in my site.
Any idea?
Use the attempt() method:
if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
From the docs:
The attempt method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column. If the user is found, the hashed password stored in the database will be compared with the password value passed to the method via the array.
This method will work for you if you're using bcrypt() or Hash::make() to generate password hash.
Please do not create your own login system!
Now that's out of the way the explanation.
There is (almost) no good reason to create your own login system, as your code already showed. Your current code is very VERY insecure due to storing passwords in plain text. Please read up on resent security advice.
The even better option is using Laravels build-in auth.
https://laravel.com/docs/5.4/authentication
If you do try to use this build-in authentication methods you will be able to get the current authenticated user by using Auth::user() this can be used in your blade files as well as in your controllers.
You cannot (maybe you can) but you certainly should't store user's password unhashed. Laravel has build artisan command: php artisan make:auth. You may use it, and retrieve him in the show method for example (thro the URL, passing id). Or just retrieve him via Auth::user(). Planty of choices.

Codeigniter Authentication and Authorization libraries that works well coupled toghether

I need functionality for authentication handling and some basic role based authorization (just block some pages to a role and allow some pages on another).
I already read this question: What is the best Authentication and Authorization library for CodeIgniter?
However the question it's from 2009 so maybe there is a new technology that works better now.
Any suggestion, expecially if you have used the library, are appreciated
All of the Auth libraries I know of restrict you in some form or other out of the bag. Its usually a good idea to build your own auth library, break it down so you dont restrict yourself to using codeigniters native AR.
For role/permissions I usually just store a json object to my permissions column in say users. I prefer this over using a more complicated technique
In my main Controller(non-restrictive) I just create a permissions(array)var and loop through it inside my child controllers to implement a restriction.
example:
sql column
`permissions` varchar(200) NOT NULL DEFAULT '["r", "u", "d"]';
main controller
protected $permissions = array();
protected function _get_permissions()
{
return (array)json_encode($this->user->permissions);
//get permissions from user (array/object)
}
extended children
if(in_array('r', $this->permissions))
{
//user can read something
}
I like skittles answer so I post it here (he is not posting):
I'm pretty sure this is not what you wanted to hear, but I prefer to
roll my own classes. I'm not afraid to re-invent the wheel
I prefer to use a salted hash. What I will typically do is take their
plain text password and add a string to it derived from a $config item
I call $config['encryption_salt']. Then I run the newly built string
through php's sha1 function and store the result in the database.
As for authorization, I will typically build a permissions lookup
table in my db and assign users a permission_id value in their user
record. Then my site can be conditionalized allow or disallow
activities based on their permission_id
If Skittle will post answer I'll mark it

Resources