You can use Middleware to restrict access to public. You can simply generate token and pass it into headers, or use basic authentication with username and password and check it in your middleware. For that purpose you can use Laravel Airlock.
Is Laravel API secure? Laravel Passport is an OAuth 2.0 server implementation for API authentication using Laravel. Since tokens are generally used in API authentication, Laravel Passport provides an easy and secure way to implement token authorization on an OAuth 2.0 server.
Options: -h, –help Display help for the given command. When no command is given display help for the list command -q, –quiet Do not output any message -V, –version Display this application version –ansi|–no-ansi Force (or disable –no-ansi) ANSI output -n, –no-interaction Do not ask any interactive question –env[=ENV] The environment the command should run under -v|vv|vvv, –verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Available commands: clear-compiled Remove the compiled class file db Start a new database CLI session down Put the application into maintenance / demo mode env Display the current framework environment help Display help for a command inspire Display an inspiring quote list List commands migrate Run the database migrations optimize Cache the framework bootstrap files serve Serve the application on the PHP development server test Run the application tests tinker Interact with your application up Bring the application out of maintenance mode auth auth:clear-resets Flush expired password reset tokens cache cache:clear Flush the application cache cache:forget Remove an item from the cache cache:table Create a migration for the cache database table config config:cache Create a cache file for faster configuration loading config:clear Remove the configuration cache file db db:seed Seed the database with records db:wipe Drop all tables, views, and types event event:cache Discover and cache the application’s events and listeners event:clear Clear all cached events and listeners event:generate Generate the missing events and listeners based on registration event:list List the application’s events and listeners key key:generate Set the application key make make:cast Create a new custom Eloquent cast class make:channel Create a new channel class make:command Create a new Artisan command make:component Create a new view component class make:controller Create a new controller class make:event Create a new event class make:exception Create a new custom exception class make:factory Create a new model factory make:job Create a new job class make:listener Create a new event listener class make:mail Create a new email class make:middleware Create a new middleware class make:migration Create a new migration file make:model Create a new Eloquent model class make:notification Create a new notification class make:observer Create a new observer class make:policy Create a new policy class make:provider Create a new service provider class make:request Create a new form request class make:resource Create a new resource make:rule Create a new validation rule make:seeder Create a new seeder class make:test Create a new test class migrate migrate:fresh Drop all tables and re-run all migrations migrate:install Create the migration repository migrate:refresh Reset and re-run all migrations migrate:reset Rollback all database migrations migrate:rollback Rollback the last database migration migrate:status Show the status of each migration model model:prune Prune models that are no longer needed notifications notifications:table Create a migration for the notifications table optimize optimize:clear Remove the cached bootstrap files package package:discover Rebuild the cached package manifest passport passport:client Create a client for issuing access tokens passport:hash Hash all of the existing secrets in the clients table passport:install Run the commands necessary to prepare Passport for use passport:keys Create the encryption keys for API authentication passport:purge Purge revoked and / or expired tokens and authentication codes permission permission:cache-reset Reset the permission cache permission:create-permission Create a permission permission:create-role Create a role permission:setup-teams Setup the teams feature by generating the associated migration. permission:show Show a table of roles and permissions per guard queue queue:batches-table Create a migration for the batches database table queue:clear Delete all of the jobs from the specified queue queue:failed List all of the failed queue jobs queue:failed-table Create a migration for the failed queue jobs database table queue:flush Flush all of the failed queue jobs queue:forget Delete a failed queue job queue:listen Listen to a given queue queue:monitor Monitor the size of the specified queues queue:prune-batches Prune stale entries from the batches database queue:prune-failed Prune stale entries from the failed jobs table queue:restart Restart queue worker daemons after their current job queue:retry Retry a failed queue job queue:retry-batch Retry the failed jobs for a batch queue:table Create a migration for the queue jobs database table queue:work Start processing jobs on the queue as a daemon route route:cache Create a route cache file for faster route registration route:clear Remove the route cache file route:list List all registered routes sail sail:install Install Laravel Sail’s default Docker Compose file sail:publish Publish the Laravel Sail Docker files schedule schedule:list List the scheduled commands schedule:run Run the scheduled commands schedule:test Run a scheduled command schedule:work Start the schedule worker schema schema:dump Dump the given database schema session session:table Create a migration for the session database table storage storage:link Create the symbolic links configured for the application stub stub:publish Publish all stubs that are available for customization vendor vendor:publish Publish any publishable assets from vendor packages view view:cache Compile all of the application’s Blade templates view:clear Clear all compiled view files
# 1. Entry: Minute when the process will be started [0-60]
# 2. Entry: Hour when the process will be started [0-23]
# 3. Entry: Day of the month when the process will be started [1-28/29/30/31]
# 4. Entry: Month of the year when the process will be started [1-12]
# 5. Entry: Weekday when the process will be started [0-6] [0 is Sunday]
#
# all x min = */x
So according to this your 5 8 * * 0 would run 8:05 every Sunday.
Position 1 for minutes, allowed values are 1-60
position 2 for hours, allowed values are 1-24
position 3 for day of month ,allowed values are 1-31
position 4 for month ,allowed values are 1-12
position 5 for day of week ,allowed values are 1-7 or and the day starts at Monday.
crontab -e for edit or add cron/scheduled job
crontab -l for show list
<?php
namespace App\Http\Middleware;
use Closure;
class VerifyAPIAccess
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (
!(App::environment('local'))
&& (
!$request->header('access-token')
|| $request->header('access-token') !== env('APP_API_TOKEN')
)
) {
return response()->json(['Message' => 'You do not access to this api.'], 403);
}
return $next($request);
}
}
and then added to my route
Route::group([
'middleware' => [
VerifyAPIAccess::class,
'throttle:60,1'
]
], function () {
// list some routes
});
you could also restrict access by adding throttling which would stop someone from hammering your API, with token or not.
There are probably many approaches. A simple but effective one would be sessions. You can save the user in a session. This way you can also count his Api accesses. As soon as they are larger than allowed, you can block their requests. You also write the block in the session. But pay attention to the session duration. It must be long enough.
But the user with bad intentions can get a new session. To avoid this, you can also put his IP on an internal blacklist for a day.
Note: But an open api is always a point of attack.
Things tried:
Using passport to protect my routes and then use passport’s CreateFreshApiToken middleware. Protection works fine, unauthorized users are not able to access the routes, however I don’t get laravel_token in my cookies and therefore I can’t get access to that route if I’m not logged in.
Use passport’s client credentials grant access. Works fine and the way I want it to work but doesn’t really make sense because if I hardcode the client_secret – anyone can access it and then use it to access protected routes. If I make a proxy-like solution, to call a controller method, which would issue a valid token and thus not exposing client_secret to front-end but then anyone could just call that route which issues the token and it would be pointless once again.
You cannot stop people from trying to access of publicly visible API. You need to secure the API and only respond to those with the proper access privileges.
I stumbled upon the same problem today and did some debugging. When registering the /login route, Fortify applies the Illuminate\Routing\Middleware\ThrottleRequests:login middleware to it. This means, for every request to that route, the ThrottleRequests middleware will call the RateLimiter instance for that specified key. Apparently, Fortify doesn’t register a RateLimiter for the login key.
Due to the missing key in the $limiters property of the RateLimiter instance, the ThrottleRequests middleware uses its default fallback, which doesn’t handle the edge case “there SHOULD be a rate limiter for that key, but there isn’t.” really well. The $maxAttempts variable is set to 0 and will result in flaky rate limiting behaviour.
I feel like this is a bug in Fortify, because rate limiting is also happening in the \Laravel\Fortify\Actions\EnsureLoginIsNotThrottled action, which is invoked in the \Laravel\Fortify\Http\Controllers\AuthenticatedSessionController controller. I didn’t check this on a fresh Laravel installation, though, so I don’t want to jump to conclusions here.
Anyway, long story short: As a workaround, you can simply register a rate limiter for the “login” key in some of your providers, e. g. AppServiceProvider or AuthServiceProvider:
public function boot()
{
RateLimiter::for("login", function () {
Limit::perMinute(5);
});
}
Edit: I just realized that the rate limiter for the “login” key is indeed provided by Fortify within the FortifyServiceProvider class. If you happen to have a problem similar to the one discussed above, make sure that you added the FortifyServiceProvider class to your providers array in the config/app.php.
When injecting a model ID to a route or controller action, you will often query the database to retrieve the model that corresponds to that ID. Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user’s ID, you can inject the entire User model instance that matches the given ID.
Implicit Binding
Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name. For example:
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
return $user->email;
});
Since the $user variable is type-hinted as the App\Models\User Eloquent model and the variable name matches the {user} URI segment, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI. If a matching model instance is not found in the database, a 404 HTTP response will automatically be generated.
Of course, implicit binding is also possible when using controller methods. Again, note the {user} URI segment matches the $user variable in the controller which contains an App\Models\User type-hint:
use App\Http\Controllers\UserController;
use App\Models\User;
// Route definition...
Route::get('/users/{user}', [UserController::class, 'show']);
// Controller method definition...
public function show(User $user)
{
return view('user.profile', ['user' => $user]);
}
w command : Show who is logged on and what they are doing on Linux
who command : Display information about Linux users who are currently logged in
whoami command : Find out who you are currently logged in as on Linux
id command : See user and group information for the specified USER account on Linux
How to show current logged in users in Linux
Open the terminal window and type: w
The w command shows information about the Linux users currently on the server, and their running processes. The first line displays, in this order:
The current time ( 22:11:17 )
How long the Linux server has been running (18 days)
How many users are currently logged on Linux (2 users)
The system load averages for the past 1, 5, and 15 minutes (1.01, 1.04, 1.05)
The following info displayed for each current logged in user:
sweta pts/10 minitx 22:11 5.00s 0.04s 0.02s vim replicant.py
Where,
sweta – Login name
pts/10 – The tty name
minitx – The remote host/desktop/laptop name
22:11 – Login time
5.00s – Idle time
0.04s – JCPU (it the time used by all processes attached to the tty. It does not include past background jobs, but does include currently running background jobs.)
0.02s – PCPU (it is the time used by the current process, named in the “what” field.)
vim replicant.py – The command line of their current process
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateReminderTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('reminder', function (Blueprint $table) {
$table->id();
$table->integer('user_id')->nullable();
$table->date('date')->nullable();
$table->time('time')->nullable();
$table->text('description')->nullable();
$table->tinyInteger('type')->nullable();
$table->string('ip',150)->nullable();
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('reminder');
}
}
They do the SQL DATE() work for you, and manage the differences of SQLite.
Your result can be achieved as so:
->whereDate('date', '<=', '2014-07-10')
Though the above method is convenient, as noted by Arth it is inefficient on large datasets, because the DATE() SQL function has to be applied on each record, thus discarding the possible index.
Here are some ways to make the comparison (but please read notes below):