Looking for a start-to-finish how-to on Laravel 5.2 OAuth2 implementation - rest

Quick background: I'm fairly experienced with PHP, but needed to build my first RESTful API. I figured I'd try Laravel (5.2) and am starting to feel pretty comfortable with it.
I started adding auth to my project over the weekend and I am really struggling to get it working. I got the basic Laravel Auth middleware working quickly, but I think I need to be using OAuth2 for production (I will be building a mobile app that will connect up to this server). I'm using the Luca Degasperi OAuth2 package, which seems to be pretty popular.
I reviewed the actual documentation: https://github.com/lucadegasperi/oauth2-server-laravel/tree/master/docs#readme)
I also went through this tutorial: https://medium.com/#mshanak/laravel-5-token-based-authentication-ae258c12cfea#.5lszb67xb
And, most recently, I found this thread about the need to seed the OAuth tables before anything will work: https://github.com/lucadegasperi/oauth2-server-laravel/issues/56
That's all great, but there are some minor differences in the most recent distribution of Laravel. For example, /app/Http/Kernel.php is slightly different from what's shown in some of the examples I found because it now uses middleware groups. I thought I handled those differences correctly (I added the OAuthExceptionHandlerMiddleware class to the 'web' section of $middlewareGroups instead of $middleware). I got my seeder working (the current oauth_scopes table only allows you to supply a description, so I had to slim down what was provided in the third link above).
If I put a test route in my 'web' group in routes.php, I would have thought this would require OAuth because I added OAuth to the 'web' middleware group in Kernel.php. That's not the case. My route works with no authentication if I do that.
I then explicitly added the OAuth middleware to my test route as follows:
Route::get('tests/events', ['middleware' => 'oauth', function() {
$events = App\Event::get();
return response()->json($events);
}]);
That causes a 500 error ("ErrorException in OAuth2ServerServiceProvider.php line 126: explode() expects parameter 2 to be string, object given").
I'm to feel pretty lost. Each of these packages seems to be shifting so quickly that there's no complete documentation on how to get this up and running.
What else do I need to do to get this functioning?

The following link is what finally got me un-stuck:
https://github.com/lucadegasperi/oauth2-server-laravel/blob/master/docs/authorization-server/password.md
Now that I have it working, I'll try and make this a complete how-to FOR PASSWORD GRANT TYPES ONLY. I didn't play with other grant types. So this assumes you're building something like a RESTful API where users will connect to it with a client app that you're going to build. So users will create a user account in your system and then when they send a REST request, the OAuth2 package will authenticate them and send them a token to stay logged in.
I'm using Laravel 5.2 and already had the basic Auth package up and running. Be advised that a lot of these steps seem to change even with incremental releases of Laravel or the OAuth2 package.
The first part of getting this working is fairly well documented already (https://github.com/lucadegasperi/oauth2-server-laravel/tree/master/docs#readme), but here's a summary just in case...
Edit the require section of your composer.json file to look something like this:
"require": {
"php": ">=5.5.9",
"laravel/framework": "5.2.*",
"lucadegasperi/oauth2-server-laravel": "5.1.*"
},
Run composer update to download the package.
Open your config/app.php file and add the following two lines to the end of the providers section:
LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider::class,
LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider::class,
Also in config/app.php, add this line to the aliases array:
'Authorizer' => LucaDegasperi\OAuth2Server\Facades\Authorizer::class,
Now we start to do things a little differently from the documentation to accommodate the current version of Laravel...
Open app/Http/Kernel.php. Laravel now uses groups and it didn't used to. Update your $middlewareGroups to look like this:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
//Added for OAuth2 Server
\LucaDegasperi\OAuth2Server\Middleware\OAuthExceptionHandlerMiddleware::class,
//Commented out for OAuth2 Server
//\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
Also in app/Http/kernel.php, update $routeMiddleware to look like this:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
//Added for OAuth2 Server
'oauth' => \LucaDegasperi\OAuth2Server\Middleware\OAuthMiddleware::class,
'oauth-user' => \LucaDegasperi\OAuth2Server\Middleware\OAuthUserOwnerMiddleware::class,
'oauth-client' => \LucaDegasperi\OAuth2Server\Middleware\OAuthClientOwnerMiddleware::class,
'check-authorization-params' => \LucaDegasperi\OAuth2Server\Middleware\CheckAuthCodeRequestMiddleware::class,
'csrf' => App\Http\Middleware\VerifyCsrfToken::class,
];
You now have to set up your grant types. You used to do this all in one place in config\oauth2.php using an array with a closure for callback. With the most recent version of the OAuth2 server package, you can't use a closure for callback anymore. It has to be a string. So your grant_types should look something like this:
'grant_types' => [
'password' => [
'class' => '\League\OAuth2\Server\Grant\PasswordGrant',
'callback' => '\App\PasswordGrantVerifier#verify',
'access_token_ttl' => 3600
]
]
access_token_ttl is the duration that an auth token will be good for (in seconds). The main package documentation uses 3600 (1 hour) by default. You might want to try 604800 (1 week) instead -- at least during testing.
You now need to create the PasswordGrantVerifier class and verify method that you just called in the code section above. So you create a file App/PasswordGrantVerifier.php and use the following code (which is basically what used to go in the closure for callback).
<?php
namespace App;
use Illuminate\Support\Facades\Auth;
class PasswordGrantVerifier
{
public function verify($username, $password)
{
$credentials = [
'email' => $username,
'password' => $password,
];
if (Auth::once($credentials)) {
return Auth::user()->id;
}
return false;
}
}
You will need at least one row in the oauth_clients table before OAuth2 will work. You can insert something manually or create a seeder. To create a seeder, modify database/seeds/DatabaseSeeder.php and add the following to the end of the run() method:
$this->call(OAuthClientsTableSeeder::class);
Now create a file called database/seeds/OAuthClientsTableSeeder.php and enter something like this:
<?php
use Illuminate\Database\Seeder;
class OAuthClientsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//Add sample users
$oAuthClients = array(
array(
'id' => 'TEST_ENVIRONMENT',
'secret' => 'b17b0ec30dbb6e1726a17972afad008be6a3e4a5',
'name' => 'TEST_ENVIRONMENT'
)
);
foreach ($oAuthClients as $oAuthClient) {
App\OAuthClient::create($oAuthClient);
}
}
}
Run php artisan vendor:publish to publish the package configuration and migrations. Run php artisan migrate to set up the billion-or-so new tables for OAuth. Run php artisan db:seed to seed your database.
You can now set up some test routes in app\Http\routes.php. They should look something like this:
Route::post('oauth/access_token', function() {
return Response::json(Authorizer::issueAccessToken());
});
Route::group(['middleware' => 'oauth'], function () {
Route::get('authroute', function() {
//OAuth will be required to access this route
});
Route::post('postwithauth', function(Request $request) {
$userID = Authorizer::getResourceOwnerId();
$input = $request->input();
return response()->json(array('userID' => $userID, 'input' => $input));
});
});
Route::get('noauthroute', function () {
//No authorization will be required to access this route
});
Pay close attention to the postwithauth route I included above. The OAuth2 package recently changed how you access the user's ID and it took me quite a while to figure out how to get it.
Now that it's time for testing, point your browser to localhost:8000 (or whatever the path is for your test environment) and create a user account for yourself (this step just uses the standard Laravel Auth package).
Go into your HTTP client (I'm currently using Paw and I like it). Go to request->authorization->OAuth2 to set up authorization for the route you're going to test. For Grant Type, select Resource Owner Password Credentials. If you used the seed example I provided above, the Client ID is TEST_ENVIRONMENT, the Client Secret is b17b0ec30dbb6e1726a17972afad008be6a3e4a5, enter the username (email) and password you created through the web Auth interface, your Access Toekn URL will be something like localhost:8000/oauth/access_token (depending on how you set up your test environment), leave Scope blank, and Token should say Bearer. Click on Get Access Token then say Use Access Token when prompted.
That should be it!

Related

What is the best way to connect TYPO3 fe_users from an Azure AD with SAML 2?

I need to implement SSO on a TYPO3 intranet, where the fe_users are synchronized from an Azure AD. the platform will be in V9.
Is there a compatible extension that I haven't found yet ?
If no, what would be the best way to implement the automatic authentication with SAML 2.0 ?
thanks in advance,
Rachel
Thanks to #Rakel (and others) I managed to finally solve my SAML authentication requirement. Still I used a slightly different and more direct approach then described in her solution.
I used an Authentication Service to implement the SAML Login Process.
For handling the SAML login itself I used the library SimpleSamlPHP, which I can truly recommend. Its really simple and the provided frontend to test the SAML configuration comes really handy to test the Identity Provider (Idp) configuration without dealing with TYPO3.
For details please look into this: https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html
First you need to create a class which extends TYPO3\CMS\Core\Authentication\AuthenticationService. This class must implement the methods "getUser" and "authUser".
namespace Vendor\Extension\Service;
use SimpleSAML\Auth\Simple;
use TYPO3\CMS\Core\Authentication\AuthenticationService;
class SamlAuth extends AuthenticationService
{
public function getUser() {
// Create new Simple Auth with SimpleSamlPHP
$as = new Simple($config['sp']);
// Require authentication, this redirects you to the Idp and then comes back
$as->requireAuth();
// Get the attributes provides by your Idp
$attributes = $as->getAttributes();
// Please consult the API for details on fetchUserRecord
// Also the SAML attributes may vary depending on your Idp implementation
$user = $this->fetchUserRecord($attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'];
}
public function authUser(array $user): int {
return is_array($user) ? 200 : 0;
}
}
Then you need to register the service in your extensions "ext_localconf.php".
...
TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addService(
'my_extension',
'auth',
Vendor\Extension\Service\SamlAuth::class,
[
'title' => 'Saml Authentication for Frontend Users',
'description' => 'Authenticates FeUsers via Saml',
'subtype' => 'authUserFE,getUserFE',
'available' => true,
'priority' => 80,
'quality' => 80,
'os' => '',
'exec' => '',
'className' => Vendor\Extension\Service\SamlAuth::class
]
);
...
Please note:
This is just a over simplified version of my final code. Just to get you started on the idea.
Also you need to configure SimpleSamlPHP correctly. Please look at their documentation for details.
The method "getUser" is supposed to return an array holding the to be logged in FeUser with all its parameters.
The method "authUser" is only to return 200 or 0. Take a look at this link to understand which number are there to return: https://docs.typo3.org/m/typo3/reference-services/7.6/en-us/Authentication/Index.html#authentication-service-chain
After returning "200" the FeUser object is created and the user is logged in. No need to fiddle around with $GLOBALS['TSFE'] by yourself. This is a huge benefit, as it makes your code shorter and easier to read.
Nethertheless I learned a lot from reading through all the documentations and responses here and on Slacks TYPO3 channel.
Thanks to everybody who helped me. Greatly appreciated.
Yes we solved that requirements. We used SimpleSAMLphp to implement the authentication, following this great tutorial :
https://www.lewisroberts.com/2015/09/05/single-sign-on-to-azure-ad-using-simplesamlphp/.
When you are able to connect then you just have to implement a process to auto connect a fe_user when you get the saml user attributes.
Here is a simplified summary of the process:
if we reach a TYPO3 site url without being authenticated then redirection to a script like this :
// SimpleSamlPHP library
require_once (dirname(__FILE__) . /../../../../../../simplesamlphp/lib/_autoload.php');
//instanciation of a simple authentication
$as = new SimpleSAML_Auth_Simple('default-sp');
//requires authentication from Office 365
$as->requireAuth();
//retrieving information from the logged-in user
$attributes = $as->getAttributes();
//retrieve original url
$returnURL = $_GET['returnURL'];
//if a user is well connected
if($attributes){
//redirection to the TYPO3 site with the username
header('Location: /auth/?samlUident='.$attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'][0].'&recupURL='.$returnURL);
}
and here's a simplified summary of what the auth page does:
//if a get saml is in the url
if(\TYPO3\CMS\Core\Utility\GeneralUtility::_GP('samlUident')){
//recovering username for TYPO3 authentication
$loginData = array(
'uname' => \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('samlUident'), //username
'status' => 'login'
);
//TYPO3 session creation
$frontendUserAuthentication = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Authentication\\FrontendUserAuthentication');
$frontendUserAuthentication->checkPid = false;
$info = $frontendUserAuthentication->getAuthInfoArray();
$user_db = $frontendUserAuthentication->fetchUserRecord($info['db_user'], $loginData['uname']);
//if a user exists
if ($user_db){
//authentication
$GLOBALS['TSFE']->fe_user->forceSetCookie = TRUE;
$GLOBALS['TSFE']->fe_user->dontSetCookie = false;
$GLOBALS['TSFE']->fe_user->start();
$GLOBALS['TSFE']->fe_user->createUserSession($user_db);
$GLOBALS['TSFE']->fe_user->user = $user_db;
$GLOBALS['TSFE']->fe_user->setAndSaveSessionData('dummy', TRUE);
$GLOBALS['TSFE']->fe_user->loginUser = 1;
}
}
Cheers,
Rachel

How to Disallow User Access to CRUD Backend

I've got Backpack for Laravel installed and have been using it for some time as an admin back end on a project. I'm also using the spatie/permission module (might come with Backpack, can't remember) to create users for the front end.
Currently, all users are able to access both front end and back end regardless of the group they belong to. I'd like to change that so that only members in an "admin" group are able to access the back end. I've followed the instructions here for separating front end and back end sessions but that's not really what I want as all users are still able to access both sites of the project.
I'm guessing I need to add a guard to the CRUD routes but I'm finding it to be much harder than it should be. Any pointers on how to do this would be greatly appreciated. TIA.
You can create a new middleware and use it in your routes group for admin routes.
To create a new middleware use the php artisan command like so: (you can name the new middleware what ever you want:
php artisan make:middleware RequireAdminRole
Now, inside your new middleware, on the handle function you can have something like this that returns a 403 Forbidden error message:
public function handle($request, Closure $next)
{
$user = auth()->user();
if (!$user) return $next($request);
if (!$user->hasRole('Admin'))
{
// if your sessions are decoupled from the frontend
// you can even logout the user like so:
// auth()->logout();
abort(403, 'Access denied');
}
return $next($request);
}
Here we are using the hasRole method, but there are more that you can use. See the spatie/laravel-permissions documentation for more info.
Now, let's assign this middleware a 'name' so we can use it in our route groups for the admin. Inside the App\Kernel.php file, in the end, inside the $routeMiddleware array add it and give it a new, for example:
'isadmin' => \App\Http\Middleware\RequireAdminRole::class,
And finally, you can add this middleware to your admin routes group (which should be in custom.php file if you're using latest backpack 3.4 version) :
Route::group([
'prefix' => 'admin',
'middleware' => ['web', 'isadmin', config('backpack.base.middleware_key', 'admin')],
'namespace' => 'App\Http\Controllers\Admin',
], function () {
// your routes are here
});
Now all your requests to the admin routes should be protected by the user role check.
Please let us know how it went for you, and if you encountered any issues.
Best regards,
~Cristian

Laravel 5.1 - Facebook Authentication through Socialite

I am trying to implement Facebook Login to my project however I receive an error:
ClientException in Middleware.php line 69:
Client error: 400
in /Applications/MAMP/htdocs/laratest/vendor/guzzlehttp/guzzle/src/Middleware.php line 69
at Middleware::GuzzleHttp{closure}(object(Response)) in Promise.php line 199
at Promise::callHandler('1', object(Response), array(object(Promise), object(Closure), null)) in Promise.php line 152
at Promise::GuzzleHttp\Promise{closure}() in TaskQueue.php line 60
at TaskQueue->run() in CurlMultiHandler.php line 96
Steps I've gone through:
composer require laravel/socialite & composer update.
In my config>services.app,
'facebook' => [
'client_id' => env('FB_CLIENT_ID'),
'client_secret' => env('FB_SECRET_ID'),
'redirect' => 'http://localhost.com:8888',
],
Added
Laravel\Socialite\SocialiteServiceProvider::class, & 'Socialite' => Laravel\Socialite\Facades\Socialite::class, in config>app.php
Set up the routes successfully.
Route::get('auth/facebook', 'Auth\AuthController#redirectToProvider');
Route::get('auth/facebook', 'Auth\AuthController#handleProviderCallback');
Setup the link successfully in my blade file. Login with Facebook
In my Controller>AuthController.php, I added:
use Laravel\Socialite\Facades\Socialite;
** Beside everything that AuthController has, inside the AuthController class, I added:**
public function redirectToProvider()
{
return Socialite::driver('facebook')
->scopes(['scope1', 'scope2'])->redirect();
}
/**
* Obtain the user information from Facebook.
*
* #return Response
*/
public function handleProviderCallback()
{
$user = Socialite::driver('facebook')->user();
// $user->token;
}
Also users table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->string('avatar');
$table->string('provider');
$table->string('provider_id');
$table->rememberToken();
$table->timestamps();
});
}
Edit:
When I comment out $user = Socialite::driver('facebook')->user(); part, I get redirected to localhost.com/auth/facebook
Edit 2:
My .env file:
'facebook' => [
FB_CLIENT_ID => '###',
FB_SECRET_ID => 'this-is-secret!',
],
I think your two routes should not have the same URL, because Laravel has no way to know which to use.
Facebook returns a ?code parameter, so make use of it! If ?code is included, then handle the login logic from Socialite, if not, redirect to Facebook.
You have two unknown scopes in your code, scope1 and scope2, those are unknown to Facebook and will return an error when trying to access them. Use real scopes like public_profile or email and you should be set. (scopes are the permissions you are requesting)
Make sure Laravel is calling properly your config entries with
php artisan config:clear
And also check your .env file for FB_CLIENT_ID and FB_SECRET_ID entries. Probably client's failing because it's trying to connect to facebook without client and secret, falling into an exception.
I've had the same problem(ClientException in Middleware.php line 69: Client error: 400).
I just switch off "Require App Secret " in the facebook's advanced settings and this solved the problem. Maybe this information will be helpful.
I had a similar problem with Facebook APi - it gave Response code 400
and Ive just tried:
composer require laravel/socialite & composer update
and it updated dependencis:
Updating dependencies (including require-dev)
- Removing laravel/socialite (v2.0.11)
- Installing laravel/socialite (v2.0.14)
Im Using Laravel 5.1:
composer.json:
"laravel/framework": "5.1.*",
"laravel/socialite": "^2.0"
And it seems to work fine now
Hope this helps someone

Testing a JSON PUT request in mojolicious

I am creating test cases for my app developed using Mojolicious framework. I am testing the routes for appropriate responses for the REST calls that are made. I use JSON as a means of communication between the server and client. To test GET, POST and DELETE requests I use the following functions
GET : get_ok()POST: post_json_ok() DELETE: delete_ok()
but for PUT I am not able to use put_ok(). And example of my usage of put_ok() would be my $t = Test::Mojo->new;$t->put_ok('this/is/url/to/resource'=>{ "element" => "modified value"})->status_is(204)
I get a bad request status every time(400) and so the test fails. I use Test::Mojo for testing my application.
Additional information:
$t->put_ok('http://localhost:3000/application/instances/system/test'=>{"model" => "testing put"})->status_is(204);
This is the exact test for PUT request that is attempted. model is a property of resource test that is being attempted to be changed to testing put and the expected status response is 204.
The mapping to the controller is done by
$r->route('/application/instances/system/:id, id => qr/[A-Za-z0-9 ]+/ -> via('put')
->to(controller => 'system', action => 'update_sys');
This route calls the update_sys method in the system controller and that is how the resource is located.
Actually, after discussions with SRI on IRC, he pointed me to an example almost identical you your needs in the documentation.
# Test custom transaction
my $tx = $t->ua->build_json_tx('/user/99' => {name => 'sri'});
$tx->req->method('PUT');
$t->tx($t->ua->start($tx))
->status_is(200)
->json_is('/message' => 'User has been replaced.');
So this should work for you!
Postscript:
You might be interested to know that this discussion has brought some progress: the next release of Mojolicious (version 3.66) will now have a cleaner syntax for this purpose, the new request_ok method. The above example can then be rewritten as
my $tx = $t->ua->build_json_tx('/user/99' => {name => 'sri'});
$tx->req->method('PUT');
$t->request_ok($tx)
->status_is(200)
->json_is('/message' => 'User has been replaced.');
Can you share the definition of your route for 'this/is/url/to/resource' ? the server is returning 400, so it appears Mojo::Controller in your app does not understand what you are sending ...

Unit Testing (PHPUnit): how to login?

I'm writing tests for my current project, made with Zend Framework.
Everything's fine, but I have a problem testing the logged users actions/controllers: I need to be logged in to be able to perform the action/controller.
How can I be logged in PHPUnit?
As you are saying you want to test actions/controllers, I suppose you are not writting unit-tests, but functional/integration tests -- ie, working with Zend_Test and testing via the MVC.
Here is a test-function I used in a project, where I'm testing if logging in is OK :
public function testLoggingInShouldBeOk()
{
$this->dispatch('/login/login');
$csrf = $this->_getLoginFormCSRF();
$this->resetResponse();
$this->request->setPost(array(
'login' => 'LOGIN',
'password' => 'PASSWORD',
'csrfLogin' => $csrf,
'ok' => 'Login',
));
$this->request->setMethod('POST');
$this->dispatch('/login/login');
$this->assertRedirectTo('/');
$this->assertTrue(Zend_Auth::getInstance()->hasIdentity());
}
Simply : I'm loading the login form, extracting the CSRF token, populating the form, and posting it.
Then, I can test if I'm connected.
With that, you can probably extract the logging-in part, to call it before each one of your tests that require a valid user to be logged-in.
There is another way. On my User entity I have a login() method that puts the user's id into the session and a static variable. What I just do in the test setUp() is call $user->login() and it works. In testing environment sessions are not used (setting Zend_Session::$isUnitTested = true has this effect) and tests rely on the static variable. Just remember to clear the static variable (logout() the user) on tearDown().
I think this article could help you:
http://perevodik.net/en/posts/7/
It describes how to create a fake identity you can use to set the environment to a state equivalent to a user being logged in.
In much the same way Pascal is using this function:
$this->_getLoginFormCSRF();
I have created a generic function that returns the value by loading the form using the form element manager:
public function _getCSRFHashValueFromForm($formAlias, $csrfName) {
$form = $this->servicemanager->get('FormElementManager')->get($formAlias);
return $form->get($csrfName)->getValue(); }
This of course assumes that the CSRF is bound to the form and not within any fieldset etc.