I am creating a package which uses API calls which I need to protect with auth middleware. I am looking at using Laravel Passport to accomplish this.
I am developing this as a package, ergo, I want to keep everything as unobtrusive as possible from the primary Laravel installation.
The issue I'm facing is in setting the relevant configuration files. Namely, in config/auth.php I need to set
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport', // change "token" -> "passport"
'provider' => 'users',
],
],
Now, how can I do this in a way that will only apply to my package?
Thanks.
If you want your package to use a different set of configurations, independent of what the installation might have defined, you could temporarily change the configuration before making your calls. In this case I'd wrap it up in a reusable class method:
use Config;
class ApiCalls {
public static function usingPackageConfig(callable $callback)
{
// Fetch original config.
$originalDriver = Config::get('auth.api.driver');
// Set custom config.
Config::set('auth.api.driver', 'passport');
// Execute callback with custom config.
$result = $callback();
// Reset config.
Config::set('auth.api.driver', $originalDriver);
return $result;
}
}
You could then call it like this:
ApiCalls::usingPackageConfig(function() {
// Make your Passport call here and it will use your package's configuration.
});
Related
I'm working on a small project using Laravel / VueJS, I'm using Passport for Authentication.
I have three pages: Login, Register, HomeController
My Question is since now I'm using Passport to login ( Token ), which middleware I should use for HomeController? I tried to use:
public function __construct()
{
$this->middleware('auth:api');
}
but it didn't work since I'm sending the Bearer token using Postman just for test.
HomeController contains a static view with no dynamic data, but I want to protect it, so that only logged users can see it.
in your application's config/auth.php configuration file the driver should be set to passport :
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
reference: https://laravel.com/docs/8.x/passport#installation
as for the middleware, it stays the same : auth:api
i'm reading in Authentication section in laravel website https://laravel.com/docs/5.2/authentication
can anyone explain how I can do this , like the documentation explains , to specify separate tables for authentication ... i will quotes from laravel like below :
Accessing Specific Guard Instances
You may specify which guard instance you would like to utilize using
the guard method on the Auth facade. This allows you to manage
authentication for separate parts of your application using entirely
separate authenticatable models or user tables.
The guard name passed to the guard method should correspond to one of
the guards configured in your auth.php configuration file:
if (Auth::guard('admin')->attempt($credentials)) {
//
}
You kinda have to read the examples of adding custom guards and providers, the configuration part of it mainly. You can use the same auth 'driver', you just want to adjust what model is used by the Auth user provider.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
// add another one
// use the same driver, 'session', but a different user provider
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// add a provider using Eloquent but using a different model
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
]
Then you should be able to specify the guard admin to Auth. As long as that Admin model implements Authenticatable and you are passing the appropriate credentials to attempt on Auth you should be good.
If you have more middlewares and you want to apply more than one guard and by this i mean middleware you can do this in any Middleware.php file:
public function handle($request, Closure $next)
{
// if a user is Agency or Admin, let him through
if (Auth::user()->isAgency() || Auth::user()->isAdmin()) {
return $next($request);
}
// else show error page
abort(403);
}
Just can't get the Lumen authentication to work at all.
I have a fresh install and trying to follow the docs here:
https://lumen.laravel.com/docs/5.2/authentication
I've Uncommented the AuthProvider line in the app.php file (along with everything else, facade, etc). Then in a simple controller I just do dd(Auth::use()).
I just can't get around this error:
Undefined index: provider
in AuthManager.php line 152
at Application->Laravel\Lumen\Concerns\{closure}('8', 'Undefined index: provider', '/home/vagrant/Code/gryd/api.gryd.com/vendor/illuminate/auth/AuthManager.php', '152', array('name' => 'api', 'config' => array('driver' => 'token'))) in AuthManager.php line 152
Any ideas?
EDIT:
Since someone asked for a code sample.
Install Lumen
Uncomment everything in app.php
Put this in routes:
$app->get('/api/v1/users/{id}', function () {
dd(\Auth::user());
});
This is what I've got so far, which is working but not quite how I'd like it. The following works for Token-based auth, which is the default setting in Lumen.
Enable Authentication
Register routeMiddleware and AuthServiceProvider by un-commenting the following lines in bootstrap/app.php.
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
and
$app->register(App\Providers\AuthServiceProvider::class);
Configuration
Copy vendor/laravel/lumen-framework/config/auth.php to config/auth.php. Create the root config folder if you have to.
Inside we will find four items (defaults, guards, providers, passwords). We're concerned with the first three.
First we name the default guard as ABC.
'defaults' => [
'guard' => env('AUTH_GUARD', 'ABC'),
],
Next we define the ABC guard with token as its driver and XYZ as its provider.
'guards' => [
'ABC' => [
'driver' => 'token',
'provider' => 'XYZ'
],
],
And the XYZ provider is defined with eloquent as the driver and App\User::class as the model.
'providers' => [
'XYZ' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
],
Completing Setup
Finally, we use the auth middleware in our routing setup, as usual.
$app->group(['middleware' => 'auth'], function () use ($app) {
So this is what gets the token auth up and running. It uses the api_token field in the users table to authenticate, which can be found in TokenGuard.
I still haven't found out what effect AuthServiceProvider and $this->app['auth']->viaRequest('api', function ($request) { have on my app yet.
Well I still haven't found out how to change the api request type via .env. But for now switching it to token seems to work.
Changed Auth::viaRequest('api', functi to Auth::viaRequest('token', funct.
I want to register a custom broadcaster with the BroadcastManager without having to change the internal framework code...
Now I have to do something like this in the Illuminate\Broadcasting\BroadcasterManager class:
protected function createMyCustomDriver(array $config) {
// return instance....
}
There is an extend method however, but I don't know if it's ment for this use case or how to use it...
The goal is to use a Broadcaster implementation that uses ZMQ to send these broadcasted events to the WebSocket php server instance.
Any help appreciated!
edit: Link to api doc http://laravel.com/api/5.1/Illuminate/Broadcasting/BroadcastManager.html
You need to extend Illuminate\Broadcasting\BroadcastManager\BroadcastManager using a service provider. This is pretty similar to adding a custom guard but here's a super basic example:
Create a new service provider, I've called mine BroadcastServiceProvider, and add the following to the boot method:
/**
* Bootstrap the application services.
*
* #param BroadcastManager $broadcastManager
*/
public function boot(BroadcastManager $broadcastManager)
{
$broadcastManager->extend('slack', function (Application $app, array $config) {
return new Slack;
});
}
All that does is add your broadcast driver (a class which implements the Illuminate\Contracts\Broadcasting\Broadcaster interface which in my example is Slack) to the broadcast manager with the name slack (you can call your broadcaster anything you like).
Make sure you add this service provider to you app.php config file.
Then, in your broadcasting.php config file add your new driver as a connection. Mine looks something like this:
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_KEY'),
'secret' => env('PUSHER_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'slack' => [
'driver' => 'slack'
]
],
You'll notice that the driver name is the same as what's in the service provider extend call. You can call the connection anything you like really and you can add extra parameters which are passed into the service provider should you need them.
After that, your custom broadcaster is registered and ready for use!
I created a simple login and registration in my page and I also added some new columns in the default users table. Now my problem is I have another table named as admin and the default Laravel's Auth table is users. How can I implement the same functionality in my table?
In the Users model it has the declaration for the table name
protected $table = 'users';
Can you give me an example how can I use the default laravel's auth class?
Thats all thanks. :-)
Laravel takes default users table for an application. For a change of laravel authentication different table relevant table name, we need to make a small change in authentication file of config.
Go to
config/auth.php
'providers' => [
// 'users' => [
// 'driver' => 'eloquent',
// 'model' => App\User::class,
// ],
'users' => [
'driver' => 'database',
'table' => 'user',
],
],
Do you hear about Multiauth in laravel. in this library there are two or more type user can login in one laravel application. In our case there are two type user Admin and Public that means User right.
Both forgot password and reset password functionality works separately in one application.
After install this library have have one step like below.
'multi' => [ 'admin' => [ 'driver' => 'database', 'table' => 'admin', 'email' => 'client.emails.password' ], 'users' => [ 'driver' => 'database', 'table' => 'users', 'email' => 'client.emails.password', ] ],
change your Auth.php file code with this one.
installation
Firstly you want to include this package in your composer.json file.
"require": {
"sboo/multiauth" : "4.0.*"
}
Now you'll want to update or install via composer.
composer update
Usage
Everything is done the exact same way as the original library, the one exception being that all method calls are prefixed with the key (account or user in the above examples) as a method itself.
Auth::admin()->attempt(array(
'email' => $attributes['email'],
'password' => $attributes['password'],
));
Auth::client()->attempt(array(
'email' => $attributes['email'],
'password' => $attributes['password'],
));
Auth::admin()->check();
Auth::client()->check();
Here is your library
I don't think the best way is to duplicate your table. I would extend users table with a role field that indicates if the user is a standard one or an admin. This way, you can keep the same code and add the ADMIN functionality that you are looking for.
If you NEED to do that and you are using Laravel 4, maybe you can use this plugin:
https://github.com/ollieread/multiauth/
Also in this thread you have code that implements Auth in different tables:
https://gist.github.com/danielcoimbra/64b779b4d9e522bc3373
But I strongly suggest to integrate both tables in one with an Admin flag/field