Laravel `jwt.refresh` token? - php

I'm using the tymon/jwt-auth package for authentication an api with Laravel. It's working quite well and I have everything working properly.
However I'm unsure how to setup the jwt.refresh token middleware. I'm under the assumption that it will "auto-refresh" the token when expired?
I've add both to my middleware but can't seem to make it work.
Route::group([
'prefix' => 'api/v1',
'namespace' => 'Api\v1',
'middleware' => ['jwt.auth', 'jwt.refresh']
], function ($app) {
// Routes here
});
Perhaps I'm not sure how it works exactly, do I need to do polling for a some refresh end point. I kind of thought that was what the middleware was supposed to do automatically per request?

If you use the jwt.refresh middleware, the token is refreshed on every request. It's returned as a header on the response, so you need to take that header and store the new token on every request.
The returned Authorization header will be of the form Token: xxxxxxxxx

Related

Can't get Auth object and cookies by consuming my own Laravel API

I'm currently trying to build a secure SPA application in Laravel by using :
Laravel 5.6
Laravel Passport
Guzzle client
To make the whole application secure, I created a proxy to prefix all requests to the API and :
User the password grand type of token
Hide the client ID
Hide the client secret
Add automatic scopes based on the role of the user
This is how the Proxy works :
// The proxify endpoint for all API requests
Route::group(['middleware' => ['web']], function ()
{
Route::any('proxify/{url?}', function(Request $request, $url) {
return Proxify::makeRequest($request->method(), $request->all(), $url);
})->where('url', '(.*)');
});
Each time a request is made, it goes through that package I built to create the access token, refreshing it, or deleting it.
To create the access token for the user I'm using a MiddleWare at loggin :
$response = $http->post('http://myproject.local/proxify/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'username' => $request->get('email'),
'password' => $request->get('password'),
]
]);
This is working well, excepting the fact that I'm setting cookies in the Proxify::makeRequest, so I have to create them in the call, return them in the $response, and then at the end of the Middleware, attaching them to the request (Cookie::queue and Cookie::Make are not working in a Guzzle call it seems).
The access token is created and stored in a cookie.
First problem is that in this call, even in the middleware, and especially in that URL http://myproject.local/proxify/oauth/token, I don't have any access to the Auth trait, even if it's specified as a middleware attached to the route, so impossible to fetch information from the authenticated user.
Then the other problem is that when I'm making a call to get a ressource API such as :
$http = new Client();
$response = $http->get('http://myproject.local/proxify/api/continents');
$continents = $response->getBody()->getContents();
return view('dashboard')->with("continents", $continents);
In that case, when I'm calling the URL, the proxy is not able to get the access_token defined in the cookie with the CookieFacade through the HTTP call, neither the Auth object I'm whiling to use. The $_COOKIE variable is not working neither.
What is wrong with my structure so that I don't have any access to the cookie even if it's set and in the browser ? Any other way to get the info ? I tried to get the cookie from the request in the proxy, not working.
Have you tried using the Illuminate or Symfony Request classes and handling the routing via the Laravel instance? My immediate suspicion is Guzzle is the culprit behind no cookies coming through with the requests. Cookie::queue() is a Laravel specific feature so I wouldn't think Guzzle would know anything about them.
Replace Guzzle in one of the routes where the issue occurs. Start with a new Request instance and make the internal api call like:
// create new Illuminate request
$request = Request::create('/api/users', $action, $data, [], [], [
'Accept' => 'application/json',
]);
// let the application instance handle the request
$response = app()->handle($request);
// return the Illuminate response with cookies
return $response->withCookies($myCookies);
I do something similar to this in a couple applications and never had any problems with cookies or accessing server variables. Granted, it's only for authentication, the rest of the api calls are through axios.

Laravel OAuth token not working with Barryvdh\Cors and Passport

I'm working with laravel, using Cors and passport. Everything works great but authentication with the route ({{HOST/oauth/token}}) is not working always get
"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource"
every other route is working perfectly. SO I just need to tell passport to use cors, I have tried this
In AuthServiceProvider
Passport::routes(null, ['middleware' => [\Barryvdh\Cors\HandleCors::class]]);
and this
Route::group(['middelware' => 'cors'], function () {
Passport::routes();
});
but nothing, login with oauth no working at all. Thank you in advance!!!
change the middleware statement to
Passport::routes(null, ['middleware' => [ \Barryvdh\Cors\HandleCors::class ]]);
refer to https://github.com/barryvdh/laravel-cors/issues/243

Laravel Passport "auth:api" middleware acts as "web, auth" middleware

I have set up the Laravel Passport package for Laravel 5.3 just as described in the official documentation (https://laravel.com/docs/5.3/passport#introduction).
I want the API to be consumed by a mobile application, so I am trying to implement Password Grant Tokens. I have created a password grant client, and the token request process...
$response = $http->post('http://my-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => 'my#email.com',
'password' => 'my-password',
'scope' => '',
],
]);
...Just works as expected, returning an access-token and a refresh-token for one of my users.
On the one hand,
php artisan route:list
Lists correct middleware for api/user URI: api,auth:api
And driver for api guard is correctly set to passport in config/auth.php.
Summing up, every step of the installation process has been done (https://laravel.com/docs/5.3/passport#installation).
Defaults contents of api.php:
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:api');
The problem comes when I access to http://my-app.com/api/user, because it seems it is authenticating the request using the 'web' middleware, not the 'api'...
When I access, I am redirected to /login (login form) if the user was not logged in, and to /home if it was...
Any help would be really appreciated.
Thanks in advance.
Solved! Just for the record, the solution:
I was sending the request to http://my-app.com/api/user with HTTP Header wrong. I was sending:
Type: Authorization - Content: Bearer: $accessToken
...and the correct way was:
Type: Authorization - Content: Bearer $accessToken (without colon)
I never thought it could be a typo... Anyway, the error was not easy to detect because the redirection to the login form misleaded me from the beginning. I believe it was such an strange behaviour indeed...
The correct solution is removing redirectTo() from this file Authenticate middleware in app/http/middleware/Authenticate.php

Laravel 5.3 API

When user enter username and password on the the browser and successfully logged in.
I like to make some API requests after user have logged in.
Laravel 5.3 provide api.php in routes folder.
in api.php I have included:
Route::group(['middleware' => ['auth']], function () {
Route::get('/test', function (Request $request) {
return response()->json(['name' => 'test']);
});
});
When requesting domain.com/api/test on the browser, for some reason it is redirecting to /home?
API token is not needed.
If you are specifying routes in api.php, you will need to use the auth:api middleware. So using your example it would be:
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, and not just be redirected to login, 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.
I found it hard to find clear docs from Laravel about using token auth with 5.3, I think it's because there's a drive to make use of Passport, and it supports tokens in a different way. Here's the article that probably helped most getting it working: https://gistlog.co/JacobBennett/090369fbab0b31130b51
first install the passport as stated here laravel passport installation
while consuming your own api add below line in your config/app.php in middleware section
'web' => [
// Other middleware...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
now change your route to
Route::group(['middleware' => ['auth:api']], function () {
Route::get('/test', function (Request $request) {
return response()->json(['name' => 'test']);
});
});
now in your config/auth.php change these lines
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
The reason you are being redirected back to home is because the auth middleware checks if a user session is stored in your browser, but since api middleware does not make use of sessions (see app\http\kernel.php), your request is considered unauthenticated
If you would like to perform simple APIs that utilize sessions, feel free to add them in your web routes, and make sure to secure them by grouping them inside an auth middleware.
The standard behaviour in Laravel 5.5 is to delegate handling of authentication exceptions to app/Handler::unauthenticated(), in your project's application code. You'll find the code in there that redirects to the login page, and you can override it or perform further tests and contextualization in there. In previous versions of Laravel, 5.3 among them I believe, this exception handling was executed way down within the Laravel library within the vendor folder.

Use Laravel Spark's Controllers/Actions in my app's API

I'm up and running with Laravel Spark, but I'd like to pull some of the user auth methods (and later, some others) in to my API.
Spark's default registration method is a POST request to /register that calls Auth\RegisterController#register.
I would like registration to be POST request to api/v1/register but for the sake of simplicity, I'd like to simply call Spark's Auth\RegisterController#register method.
I did try simply copying the RegisterController from Spark in to my app's controller directory, but that didn't seem like an elegant solution and it didn't work anyway.
My app\Http\api.php contains the following group:
Route::group([
'prefix' => 'api/v1',
'middleware' => 'auth:api'
], function () {
Route::get('register', 'Auth\RegisterController#showRegistrationForm');
Route::post('register', 'Auth\RegisterController#register');
});
I'd love input and advice on the best way to pull in some of those Spark methods that I get out of the box.
Thanks in advance!

Categories