Does Laravel Passport support having permissions on routes, methods, and a number of requests? e.g., the user can only send GET request, or the user can only send 50 requests for the special route, or the user only has access to special routes.
If not, do you know any package in laravel or other PHP frameworks that provide such facilities for API authentication and authorization?
For this you need to make use of the middleware throttle.
for example:
Route::middleware('auth:api', 'throttle:60,1')->group(function () {
...
}
Related
This is my first time using laravel sanctum. Before this, I use Laravel Passport for protecting the route.
So the problem is, there are 2 kind of route. Route that need user authentication, like API profile, my order, and inbox. And route that doesn't need user authentication to access, like API version control, splashscreen, and forgot password.
In my last project when using passport, in passport there was client token, that doesn't need user credential to get. Then I use auth_client middleware to protect route that doesn't need user authentication. First I want to ask, is this the correct way?
If that was correct way, and protecting no need login route is recommended, how i do the same thing using laravel sanctum?
Passport provides a convenient way of registering routes for users to create their own clients by calling Passport::routes(); in the AuthServiceProvider.
I do not wish to allow my users to create clients, as I only want to manually create clients using php artisan passport:client command, as I only need passport for machine-to-machine authentication for internal services.
How do I customize routes for Passport to only expose the necessary routes for passing a client id and secret to gain an access_token? I understand that I can dig into the framework and expose my own routes to a series of \Laravel\Passport\Http\Controllers\PassportController#action, I just didn't know if that was the only way or the preferred way.
You can pass a closure to Passport::routes() in your AuthServiceProvider.
See here
In the closure you can define which routes should be registered.
Something like this:
Passport::routes(function ($router) {
$router->forAuthorization();
$router->forAccessTokens();
// etc.
);
Here are the available methods:
forAuthorization();
forAccessTokens();
forTransientTokens();
forClients();
forPersonalAccessTokens();
I am a bit confused, I have a web application having a login, Register, Logout. Some dashboard views etc(CRUD), I want to make an api for this application too.
Like an api which third party will use, Can update records, Can delete records etc.
Actually there should be some way which can be use by mobile app for CRUD.
I know we have that routes/api.php, But i am pretty confused that when to use it. Please explain the scenario, I am blank.
Update:
Scenario
Application having views, authentication system etc, How an android app will be able to perform CRUD operations on the same application ?
1.web routing uses session state, CSRF protection. does it mean api routing not using session state, CSRF protection?
All it possible but not required. You still can using sessions etc, but this is a REST principles violation.
2.laravel 5.3 uses seperate web and api routing, is there any advantages ?
It's just for your convenience. In Laravel 5.2 you need specify middleware for routes like ['web'] or ['api'] but it doesn't required anymore. In 5.3 routes stored in separated files and specify routes middleware not required.
If you are specifying routes in api.php, you will need to use the auth:api middleware. For example:
Route::group(['middleware' => ['auth:api']], function () {
Route::get('/test', function (Request $request) {
return response()->json(['name' => 'test']);
});
});
Notes about Token auth and Laravel 5.3:
If you've setup laravel's default auth system, you will also need to add a column for api_token to the user table. If you are using DB seeders, you might want to add something like:
$table->char('api_token', 60)->nullable();
to your users table seeder. Alternatively just add the column manually and fill that column with a random 60-char key.
When making the request, you can add the api_token as a URL/Querystring parameter like so:
domain.com/api/test?api_token=[your 60 char key].
You can also send the key as a header (if using Postman or similar), i.e: Header: Authorization, Value: Bearer [your 60 char key].
I order to get a useful error if the token is incorrect, also send the following header with all requests:
Header: Accept, Value: application/json. This allows the expectsJson() check in the unauthenticated() function inside App/Exceptions/Handler.php to work correctly.
After watching laracast video relating to passport,i understood that passport is used to authenticate our own api.Still i have confusion regarding passport
1.How to validate authentication request for get ,post ,put and delete.Suppose if i pass token in my get url user can easily see and use that token.
2.Can i restrict the number of request to particular user to use my api ?
3.if any one decode the android app then they use that api token.In this case how we can protect ?
if any think wrong in my question please forgive.I am not much comfortable about passport and api routing in laravel 5.3
Thank you
Yes you pass your token to each request. Like explained here: https://laravel.com/docs/master/passport#passing-the-access-token
Yes, you would do that using Middleware. I suggest you inspire yourself with the Illuminate\Routing\Middleware\ThrottleRequests class.
You can refresh a specific token if you notice it's been stolen or something... But it's clearly not safe to store the client_id and client_secret in a mobile app.
Passport is built on top of League OAuth2 server, you should get familiar with it if you want to go in depth and read on security regarding Oauth2, it's a bit out of the scope for a question here. To keep it simple, use the built-in functionality in Laravel 5.3, SSL/TLS on the server to secure the communication between the app and the server and you'll most probably be fine unless you do some really strange stuff. OAuth2 is really robust and is used by many major players in the field so don't worry to much about the security.
It might be a bit strange to get a grip of having to pass a token to each request if you're used to traditional ways of authentication, there is a really good article about it which explains how it works on Scotch: The Ins and Outs of Token Based Authentication
You can protect routes using middleware. Passport includes an authentication guard that validates the access tokens upon the incoming requests, Example:
Route::get('/api/user', function () {
//
})->middleware('auth:api');
There is a rate limiting built in Larael that limits the rate at which any API requester can make requests. As you might have guessed, you should also use a middleware for this, for laravel it's the throttle middleware that you can use, example code (with /api as prefix):
Route::group(['prefix' => 'api', 'middleware' => 'throttle'], function () {
Route::get('user', function () {
return Person::all();
});
});
The default throttle is to 60 attempts per minute and disables access for a minute if the user hits the limit.
If you make a request to this route, you will now see the following lines in the response header:
HTTP/1.1 200 OK
... other headers here ...
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
You can of course customize the throttle middleware, if you want to limit it to 10 attempts per minute, this is how you would do it:
Route::group(['prefix' => 'api', 'middleware' => 'throttle:10'], function () {
Route::get('user', function () {
return User::all();
});
});
You can also add a second parameter which decides the number of minutes until they can try again, you would do 'throtttle:10,10' instead.
need your ideas.
I have a ZF1/Postgres application. It has its own users and all that.
Now I would like the whole application to be API-driven. I started to build
RESTful resources in a new Laravel 5 application. The Laravel app will talk to the same Postgres DB. Eventually, I want to get rid of all the DB calls within the ZF1 app, so that Laravel app is in charge of that.
The question is: I would like to add authorization for each API call, so that I know which users produce those calls and could act accordingly. What is the best way to authenticate users, so they could access Laravel endpoints?
If you want to use RFC-standard oAuth2 authentication, I would go with https://github.com/lucadegasperi/oauth2-server-laravel
Assuming you do, you'd probably want to use the "password" grant-type for internal authentication. Your client would hit the /oauth/access_token endpoint for a token using the user's username and password, which would return an access token good for the rest of the API.
To protect a route, you'd put it in the Route::group(['before' => 'oauth']...) section. To access an oauth-protected endpoint, you'd put the token in the HTTP header "authorization": "bearer ".
If you aren't using the standard laravel Users model, you may have to do a little tweaking. Most of it is covered in the oauth plugin wiki.
If the API is not public and there isn't any change to access it directly from the internet I wouldn't use any authentication. I would pass the userId in a custom http-header and and authenticate via Auth::loginUsingId(1) this will be cheaper then doing real authentication stuff. Therefore you have to map App\User to your existing user-table.
If you want to do real authentication take a look at RESTful Authentication
For inspiration on how to use Laravel for a REST-Service take a look at the dingo/api package (currently only Laravel 4, 5 is in progress).