How to manage multiple connection on laravel sanctum package? - laravel

We are working on project where multiple databases are connected. We have created connections i.e. dbconnection1 and api. We are facing problem in connecting sanctum auth to different connection i.e. api after upgrading Laravel to 9.
Earlier it was working perfectly, after upgrading Laravel version, we could not connect to different connection.
We have mentioned connection in respective Modal i.e. protected $connection = 'api';.
But still sanctum is not connecting to correct database. Currently we have extended PersonalAccessToken Model as per sanctum documentation and added protected $connection = 'api'; line there.
But we would like to know if there is any better option for this? As We don't think just to mention connection we should extend PersonalAccessToken Model.

You are correct, since PersonalAccessToken extends Model, which by default uses the default connection, you need to specify different connection like other models.
Otherwise you can set 'api' as the default connection

Related

How to register on Jetstream via Postman (API)

First step: I am posting data via Postman on the api/reg
Second step: I am getting perfectly all the sent data
Third step: nothing lol, I can't get to this 3rd step, what to do to send this data to database how Jetstream does?
Somehow I found this CreateNewUser.php and via dd() I found out that my regular blade register information is coming to this point, but from where is it coming, and where is it going after is a mystery, There is no any information on the internet, so I am getting the register data (name,email...) in my Laravel project, somewhere AGAIN in my Laravel project there is some mechanism that upgrades (adds tokens etc...) and sends my data to database, how to connect that two things to each other? Thanks in advance
Jetstream is not intended to be used in this manner, if you want to expose an API you should use something like Laravel Sanctum or Laravel Passport. Sanctum is more lgihtwieght and has simpler workflow, Passport is heavier and provides a full oauth workflow which might be overkill in some scenarios. Both of these solutions use token authentication with Jetstream does not provide out of the box.
That said, to answer you question of how this all works.
Jetstream uses Laravel Fortify as its web authentication provider. It comes with a bunch of routes predefined, all of which you can see using php artisan route:list --compact. The route you're interested in is the POST /register route which is mapped to Laravel\Fortify\Http\Controllers\RegisteredUserController#store. When the registration form is submitted, the data is sent to that controller/method. The method expects two parameters, a Request object and a CreatesNewUsers object, both of which are injected by Laravels IoC service container.
The CreatesNewUsers object that is passed to the store method, is an instance of the CreateNewUser class you've found in App\Actions\Fortify which then performs the action of registering a new user. If you were to modify the structure of your User class, such as adding a phone number for example, you would need to edit CreateNewUser to include that new requirement if it was required when a user registers.
Here is a nice tutorial on how to Build a Restful API in PHP with Laravel Sanctum.

Laravel Auth with different connection for each subdomain?

I'm building an app where each subdomain has its own database.
For example:
"example1.app.dev" uses "example1_dbo" database
"example2.app.dev" uses "example2_dbo" database
Each subdomain has its own users, meaning that for example:
user_ex1 can only login on example1.app.dev because he is set in example1_dbo
user_ex2 can only login on example2.app.dev because he is set in example2_dbo
How do I achieve this with Laravel Auth?
Basicaly I have set subdomain routing:
Route::domain('{account}.myapp.dev')->group(function () {})
And i have set up database connections in config/database.php and env file.
I have used this concept on Eloquent models with Model->setConnection($account)
But this method is exhausting while app is growing...
I'm looking for Middleware solution where i can change default DB connection for request globally and for Auth as well while i was not able to get authentication to work.
Have you tried this package:
https://github.com/stancl/tenancy
It provide that out of the box.
hope it is helpful.

Laravel - read database credentials from a remote api

There is a central web app 'AppsManager' that stores users and database credentials for all other web apps. This has an api to validate the login in other web apps and also serves database credentials.
So in a different laravel app -that has it's own database- I am asked to implement a different way of using database credentials.
The request is forLaravel to read it's database credentials from the 'AppsManager' api instead of the default .env file.
Is this a good practice ? How can be done in Laravel ?
I am not sure if this is a good practice or not, personnally I dont think it is a good idea to have credentials sent between apps.
Nonetheless, what I would do, in your situation, is create a new configuration in config/database.php to explicitly tell Laravel what connection it should use to have this distant database.
Inside the models that use this database you can specify :
<?php
class MyModel extends Model {
protected $connection = 'name-of-the-connection-you-gave-in-the-config-file';
}
Or if you use the DB facade, you can just call DB::connection('name-of-the-connection-you-gave-in-the-config-file') as explained here in the docs.

Laravel 5.4: how to protect api routes

I have a react app that fetch datas from laravel api defined like so in routes/api.php:
// this is default route provided by laravel out of the box
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
// ItemController provides an index methods that list items with json
Route::resource('items', 'Api\ItemController', array('except' => array('create','edit')));
// this is to store new users
Route::resource('users', 'Api\UserController', array('only' => array('store')));
for example http://example.com/api/items returns the data as intended but it's really insecure since anyone could access it through postman.
How to make those routes only accessible inside the app?
As I'm new to it I don't understand if I need to set up api_token and how?
Do I need to setup Passport?
Is is related to auth:api middleware?
It may sounds really basic but any help or tutorial suggestions would be greatly appreciated
EDIT
End up with a classic session auth. Moved routes inside web.php. Pass csrf token in ajax request. Actually i didn't need a RESTful API. You only need token auth when your API is stateless.
As you are using Laravel 5.4 you can use Passport, but I haven't implemented yet, but i implemented lucadegasperi/oauth2-server-laravel for one of my laravel projects and it was developed in Laravel 5.1
Here is the link to github repository
lucadegasperi/oauth2-server-laravel
Here is the link to the documentation Exrensive Documentation
Just add the package to the composer json and run composer update,the package will get installed to your application , once installed add the providers array class and aliases array class as mentioned in the Laravel 5 installation part of the documentation,
you have to do a small tweak in order to work perfectly cut csrf from $middleware array and paste it into $routeMiddleware array and again run php artisan vendor:publish after publishing the migrations will be created and run the migration php artisan migrate
if you only want to secure api routes for each client like ios, android and web you can implement Client Credentials Grant, or if you need to every user with oauth the you can implement Authorization Server with the Password Grant or some other.,
Never use the client id or other credentials, generating access token in the form, but add it some where in helper and attach it in the request to the api,
Hope this answer helps you.
You could use JWT it's pretty easy to get it to work. You basically generate a token by requesting Username/Password and passing that token in every request that requires authentication, your URL would look like http://example.com/api/items?token=SOME-TOKEN. without a proper token, he doesn't have access do this endpoint.
As for
How to make those routes only accessible inside the app?
If you mean only your app can use these requests, you can't. Basically the API doesn't know who is sending these requests, he can only check if what you are giving is correct and proceed with it if everything is in order. I'd suggest you to have a look at this question

Adldap 2 can connect and find a user but cannot authenticate

Question: why can I not authenticate a known registered user through Adldap despite being able to access information about the user using Adldap on laravel 5.2?
I am attempting to use Adldap on laravel 5.2 to authenticate users at a university. I have successfully managed to connect to the ldap server with the admin credentials and can even retrieve information about the user.
`
namespace App\Http\Controllers;
use Auth;
use Input;
use Adldap;
class AuthController extends Controller
{
public function authenticate()
{
$username = Input::get('username');
$password = Input::get('password');
$authentic = Adldap::authenticate($username,$password);
$userData = Adldap::users()->find($username);
var_dump( $authentic );
dd( $userData );
}
}
`
when I try to log in, dumping $authentic gives me false despite having the correct password (I dumped it as well to check). However, with the same username if I dump $userData i get a massive array of (correct) user information. Using my username, if I open the $userData object up I can see what email groups i'm in, my campus mailing address, my work title etc.
Dumped variables. I am very new to using ldap and am not quite sure how everything works. Also, its probably worth noting that despite me being the guy doing the setup and such I do not have much access to the servers. Everything is on an as needed basis.
One though was that the ldap server took care of any password hashing on that end. However, since i'm getting connected but the authentication fails could it be that I need to hash the password on my end? Please explain any solutions in detail. As an Ag engineer none of this is exactly my field but sometimes branching out is a necessity.
There are no errors. I'm on wamp and in logs/php_error (I assume this is the equivalent local version of /var/log/debug). Additionally, apache_error shows no problems.
You better check the messages created in /var/log/debug while trying to log in. Please add these messages to this post.
There was no "error" on my end. The Ldap server was simply configured to accept the users full email address and not their short id as I was using.

Resources