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!
Related
For apis auth I am currently using:
Route::group([
'middleware' => 'auth:api'
], function() {
Route::post('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
If I want to use same for session based logins do I need to create same routes in web.php file or can I set up middleware in AuthController constructor with something like this or this?
In this answer 'auth:api' means auth is checking for api so do I need to pass anything there to check for sessions like 'auth:api,web' or what?
Create same routes in web.php just ommit the middleware, as web middleware is applied automatically. Same goes for api.php, auth:api is default middleware there.
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.
My code is below in Routes.php
Route::group([
'middleware' => 'auth',
], function() {
Route::get('/Categories-List', 'Category_Controller#index');
Route::get('/Create-Category', 'Category_Controller#create');
Route::post('/SaveCategory', 'Category_Controller#store')->middleware(['isAdmin']);
Route::post('/UpdateCategory', 'Category_Controller#update')->middleware(['isAdmin']);
});
What's the problem ?
There are still other 100s of routes defined which contains many belongs to admin.
Is there any clean way to isolate the admin routes ?
You can nest route groups:
Route::group([
'middleware' => 'auth',
], function() {
Route::get('/Categories-List', 'Category_Controller#index');
Route::get('/Create-Category', 'Category_Controller#create');
Route::group([
'middleware' => 'isAdmin',
], function() {
Route::post('/SaveCategory', 'Category_Controller#store');
Route::post('/UpdateCategory', 'Category_Controller#update');
});
});
You could also put the admin routes in an entirely separate file via app/Providers/RouteServiceProvider.php (add another line like the existing require app_path('Http/routes.php');).
I bumped into this last week and starred it on github. You can use this Laravel package (Laravel-context) to separate your admin context all together.
Let's say you have 2 contexts in your application: an Administration Panel and a RESTful WebService. This are certainly two completely different contexts as in one context you'll maybe want to get all resources (i.e. including trashed) and in the other one you want only the active ones.
This is when Service Providers come in really handy, the only problem is that Laravel doesn't come with an out of the box solution for loading different Service Providers for different contexts.
This package gives you the possibility to register your different repositories to a single interface and bind them through your Context's Service Provider, using Laravel's amazing IoC Container to resolve which concrete implementation we need to bind depending on which context we are on.
Thanks,
Karmendra
I am attempting to implement the Satellizer authentication system into my Angular app. I have experience with PHP and Laravel, so I decided to use that as my backend.
Right now I am attempting to mimic what they do in their example Laravel code. That can be found here: https://github.com/sahat/satellizer/tree/master/examples/server/php.
I have installed Xdebug on my server and have it successfully connecting with my PHPStorm. Here is what my routes.php looks like.
// OAuth, Login and Signup Routes.
Route::post('/api/auth/facebook', 'AuthController#facebook');
Route::post('/auth/twitter', 'AuthController#twitter');
Route::get('/auth/unlink/{provider}', ['middleware' => 'auth', 'uses' => 'AuthController#unlink']);
// API Routes.
Route::get('/api/me', ['middleware' => 'auth', 'uses' => 'UserController#getUser']);
Route::put('/api/me', ['middleware' => 'auth', 'uses' => 'UserController#updateUser']);
// Initialize Angular.js App Route.
Route::get('/', 'HomeController#index');
On my sign in page, I have an authentication button for Facebook. After the Facebook popup appears, I have it calling back to my Laravel. In the JavaScript console it shows that it is attempting to contact the correct route. Heres what it prints.
POST http://localhost:8888/api/auth/facebook 404 (Not Found)
I have the following method inside AuthController.php.
/**
* Login with Facebook.
*/
public function facebook(Request $request) {...}
The function is never hit. From the information printed in the console, it appears that it doesn't know it exists at all. Is there something I am doing wrong?
The route Route::get('/', 'HomeController#index'); is hit upon every request, and it goes inside HomeController and hits the index method every time.
But
I have a bunch of controllers. One of them is ArticleController. I want the method postCreateArticle() method to require the user to be authenticated.
In the documentation, I figured you can use the auth middleware, like so:
Route::get('profile', ['middleware' => 'auth', function()
{
// Only authenticated users may enter...
}]);
However, I am registering my controllers in the routes:
Route::controller('articles', 'ArticleController');
How do I protect the postCreateArticle() method, without doing it inside the method?
In your constructor you should be able to:
$this->middleware('auth', ['only' => 'postCreateArticle'])