Coder Social home page Coder Social logo

laravel-saml2's Introduction

Status: Not Active

This project is no longer maintained. I'd be glad to transfer ownership, or otherwise you can easily replace it by some of the many forks (let me know if someone wants to list theirs here, or some oher library). The library itself shouldn't change much, but there are occational changes needed to keep up with Laravel and PHP version updates

Laravel 5 - Saml2

Build Status

A Laravel package for Saml2 integration as a SP (service provider) based on OneLogin toolkit, which is much lighter and easier to install than simplesamlphp SP. It doesn't need separate routes or session storage to work!

The aim of this library is to be as simple as possible. We won't mess with Laravel users, auth, session... We prefer to limit ourselves to a concrete task. Ask the user to authenticate at the IDP and process the response. Same case for SLO (Single Logout) requests.

Installation - Composer

You can install the package via composer:

composer require aacotroneo/laravel-saml2

Or manually add this to your composer.json:

composer.json

"aacotroneo/laravel-saml2": "*"

If you are using Laravel 5.5 and up, the service provider will automatically get registered.

For older versions of Laravel (<5.5), you have to add the service provider:

config/app.php

'providers' => [
        ...
    	Aacotroneo\Saml2\Saml2ServiceProvider::class,
]

Then publish the config files with php artisan vendor:publish --provider="Aacotroneo\Saml2\Saml2ServiceProvider". This will add the files app/config/saml2_settings.php & app/config/saml2/mytestidp1_idp_settings.php, which you will need to customize.

The mytestidp1_idp_settings.php config is handled almost directly by OneLogin so you should refer to that for full details, but we'll cover here what's really necessary. There are some other config about routes you may want to check, they are pretty strightforward.

Configuration

Define the IDPs

Define names of all the IDPs you want to configure in saml2_settings.php. Optionally keep mytestidp1 (case-sensitive) as the first IDP if you want to use the simplesamlphp demo, and add real IDPs after that. The name of the IDP will show up in the URL used by the Saml2 routes this library makes, as well as internally in the filename for each IDP's config.

config/saml2_settings.php

    'idpNames' => ['mytestidp1', 'test', 'myidp2'],

Configure laravel-saml2 to know about each IDP

You will need to create a separate configuration file for each IDP under app/config/saml2/ folder. e.g. test_idp_settings.php. You can use mytestidp1_idp_settings.php as the starting point; just copy it and rename it.

Configuration options are not explained in this project as they come from the OneLogin project, please refer there for details.

The only real difference between this config and the one that OneLogin uses, is that the SP entityId, assertionConsumerService URL and singleLogoutService URL are injected by the library.

If you don't specify URLs in the corresponding IDP config optional values, this library provides defaults values. The library creates the metadata, acs, and sls routes for each IDP. If you specify different values in the config, note that the acs and sls URLs should correspond to actual routes that you set up that are directed to the corresponding Saml2Controller function.

If you want to optionally define values in ENV vars instead of the {idpName}_idp_settings file, you'll see in there that there is a naming pattern you can follow for ENV values. For example, if in mytestipd1_idp_settings.php you set $this_idp_env_id = 'mytestidp1';, and in myidp2_idp_settings.php you set $this_idp_env_id = 'myidp2', then you can set ENV vars starting with SAML2_mytestidp1_ and SAML2_myidp2_ respectively.

For example, it can be:

.env

SAML2_mytestidp1_SP_x509="..."
SAML2_mytestidp1_SP_PRIVATEKEY="..."
// Other  SAML2_mytestidp1_* values

SAML2_myidp2_SP_x509="..."
SAML2_myidp2_SP_PRIVATEKEY="..."
// Other SAML2_myidp2_* values

URLs To Pass to The IDP configuration

As mentioned above, you don't need to implement the SP entityId, assertionConsumerService URL and singleLogoutService URL routes, because Saml2Controller already does by default. But you need to know these routes, to provide them to the configuration of your actual IDP, i.e. the 3rd party you are asking to authenticate users.

You can check the actual routes in the metadata, by navigating to http(s)://{laravel_url}/{idpName}/metadata, e.g. http(s)://{laravel_url}/mytestidp1/metadata which incidentally will be the default entityId for this SP.

If you configure the optional routesPrefix setting in saml2_settings.php, then all idp routes will be prefixed by that value, so you'll need to adjust the metadata url accordingly. For example, if you configure routesPrefix to be 'single_sign_on', then your IDP metadata for mytestidp1 will be found at http(s)://{laravel_url}/single_sign_on/mytestidp1/metadata.

The routes automatically created by the library for each IDP are:

  • {routesPrefix}/{idpName}/logout
  • {routesPrefix}/{idpName}/login
  • {routesPrefix}/{idpName}/metadata
  • {routesPrefix}/{idpName}/acs
  • {routesPrefix}/{idpName}/sls

Example: simplesamlphp IDP configuration

If you use simplesamlphp as a test IDP, and your SP metadata url is http(s)://{laravel_url}/mytestidp1/metadata, add the following to /metadata/sp-remote.php to inform the IDP of your laravel-saml2 SP identity.

For example, it can be:

/metadata/sp-remote.php

$metadata['http(s)://{laravel_url}/mytestidp1/metadata'] = array(
    'AssertionConsumerService' => 'http(s)://{laravel_url}/mytestidp1/acs',
    'SingleLogoutService' => 'http(s)://{laravel_url}/mytestidp1/sls',
    //the following two affect what the $Saml2user->getUserId() will return
    'NameIDFormat' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent',
    'simplesaml.nameidattribute' => 'uid' 
);

Usage

When you want your user to login, just redirect to the login route configured for the particular IDP, route('saml2_login', 'mytestidp1'). You can also instantiate a Saml2Auth for the desired IDP using the Saml2Auth::loadOneLoginAuthFromIpdConfig('mytestidp1') function to load the config and construct the OneLogin auth argment; just remember that it does not use any session storage, so if you ask it to login it will redirect to the IDP whether the user is already logged in or not. For example, you can change your authentication middleware.

For example, it can be:

App/Http/Middleware/RedirectIfAuthenticated.php

public function handle($request, Closure $next)
{
    if ($this->auth->guest())
    {
        if ($request->ajax())
        {
            return response('Unauthorized.', 401); // Or, return a response that causes client side js to redirect to '/routesPrefix/myIdp1/login'
        }
        else
        {
            $saml2Auth = new Saml2Auth(Saml2Auth::loadOneLoginAuthFromIpdConfig('mytestidp1'));
            return $saml2Auth->login(URL::full());
        }
    }

    return $next($request);
}

Since Laravel 5.3, you can change your unauthenticated method.

For example, it can be:

App/Exceptions/Handler.php

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson())
    {
        return response()->json(['error' => 'Unauthenticated.'], 401); // Or, return a response that causes client side js to redirect to '/routesPrefix/myIdp1/login'
    }

    $saml2Auth = new Saml2Auth(Saml2Auth::loadOneLoginAuthFromIpdConfig('mytestidp1'));
    return $saml2Auth->login('/my/redirect/path');
}

For login requests that come through redirects to the login route, {routesPrefix}/mytestidp1/login, the default login call does not pass a redirect URL to the Saml login request. That login argument is useful because the ACS handler can gets that value (passed back from the IDP as RelayPath) and by default will redirect there. To pass the redirect URL from the controller login, extend the Saml2Controller class and implement your own login() function. Set the config/saml2_settings.php value saml2_controller to be your extended class so that the routes will direct requests to your controller instead of the default.

For example, it can be:

config/saml_settings.php

    'saml2_controller' => 'App\Http\Controllers\MyNamespace\MySaml2Controller'

App/Http/Controllers/MyNamespace/MySaml2Controller.php

use Aacotroneo\Saml2\Http\Controllers\Saml2Controller;

class MySaml2Controller extends Saml2Controller
{
    public function login()
    {
        $loginRedirect = '...'; // Determine redirect URL
        $this->saml2Auth->login($loginRedirect);
    }
}

After login is called, the user will be redirected to the IDP login page. Then the IDP, which you have configured with an endpoint the library serves, will call back, e.g. /mytestidp1/acs or /{routesPrefix}/mytestidp1/acs. That will process the response and fire an event when ready. The next step for you is to handle that event. You just need to login the user or refuse.

For example, it can be:

App/Providers/MyEventServiceProvider.php

Event::listen('Aacotroneo\Saml2\Events\Saml2LoginEvent', function (Saml2LoginEvent $event) {
    $messageId = $event->getSaml2Auth()->getLastMessageId();
    // Add your own code preventing reuse of a $messageId to stop replay attacks

    $user = $event->getSaml2User();
    $userData = [
        'id' => $user->getUserId(),
        'attributes' => $user->getAttributes(),
        'assertion' => $user->getRawSamlAssertion()
    ];
        $laravelUser = //find user by ID or attribute
        //if it does not exist create it and go on  or show an error message
        Auth::login($laravelUser);
});

Auth persistence

Be careful about necessary Laravel middleware for Auth persistence in Session.

For example, it can be:

App/Http/Kernel.php

protected $middlewareGroups = [
        'web' => [
	    ...
	],
	'api' => [
            ...
        ],
        'saml' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
        ],

config/saml2_settings.php

    /**
     * which middleware group to use for the saml routes
     * Laravel 5.2 will need a group which includes StartSession
     */
    'routesMiddleware' => ['saml'],

Log out

Now there are two ways the user can log out.

  • 1 - By logging out in your app: In this case you 'should' notify the IDP first so it closes global session.
  • 2 - By logging out of the global SSO Session. In this case the IDP will notify you on /mytestidp1/slo endpoint (already provided), if the IDP supports SLO

For case 1, call Saml2Auth::logout(); or redirect the user to the logout route, e.g. mytestidp1_logout which does just that. Do not close the session immediately as you need to receive a response confirmation from the IDP (redirection). That response will be handled by the library at /mytestidp1/sls and will fire an event for you to complete the operation.

For case 2, you will only receive the event. Both cases 1 and 2 receive the same event.

Note that for case 2, you may have to manually save your session to make the logout stick (as the session is saved by middleware, but the OneLogin library will redirect back to your IDP before that happens)

For example, it can be:

App/Providers/MyEventServiceProvider.php

Event::listen('Aacotroneo\Saml2\Events\Saml2LogoutEvent', function ($event) {
    Auth::logout();
    Session::save();
});

That's it. Feel free to ask any questions, make PR or suggestions, or open Issues.

laravel-saml2's People

Contributors

aacotroneo avatar ajtrichards avatar arrowgtam avatar axis80 avatar brendantwhite avatar cwdn avatar cyrille37 avatar danmichaelo avatar darynmitchell avatar garethellis36 avatar hughvolpe avatar jacobbennett avatar jmandrade avatar joeyhoutenbos avatar jonathanwkelly avatar matijakovacevic avatar nirajp avatar nstaff avatar olivm avatar omitobi avatar perifer avatar quentinbontemps avatar rlcurrall avatar robertboes avatar s3sam avatar snipe avatar soltmar avatar technowl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-saml2's Issues

simplesamlphp

In your configuration section,

You guys said, "if you use simplesamlphp, add the following to /metadata/sp-remote.php"

I'm a little confuse right now, since this is my first time implementing this integration.

Does that mean I have to pre-installed simplesampleid in order to use this package ?

Also, I saw you start using http://laravel_url/ in

$metadata['http://laravel_url/saml/metadata'] = array(
    'AssertionConsumerService' => 'http://laravel_url/saml/acs',
    'SingleLogoutService' => 'http://laravel_url/saml/sls',
    //the following two affect what the $Saml2user->getUserId() will return
    'NameIDFormat' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent',
    'simplesaml.nameidattribute' => 'uid' 
);

What is that ? How do I get that ?

I am not implementing the iDP. I got the end point from the IT guy.
In that case, should I request for ACS, and SLS URL too ?

Are those manditory for these 2 lines ?

    'AssertionConsumerService' => 'http://laravel_url/saml/acs',
    'SingleLogoutService' => 'http://laravel_url/saml/sls',

Any hints / suggestions will mean a lot to me !!

Invalid array settings: idp_sso_url_invalid, idp_slo_url_invalid

I kept getting this error

OneLogin_Saml2_Error in Settings.php line 121:
Invalid array settings: idp_sso_url_invalid, idp_slo_url_invalid

and here is my settings

`<?php

//This is variable is an example - Just make sure that the urls in the 'idp' config are ok.
$idp_host = 'https://identityfederation.uat.connect.company/fed/idp';

return $settings = array(

/**
 * If 'useRoutes' is set to true, the package defines five new routes:
 *
 *    Method | URI                      | Name
 *    -------|--------------------------|------------------
 *    POST   | {routesPrefix}/acs       | saml_acs
 *    GET    | {routesPrefix}/login     | saml_login
 *    GET    | {routesPrefix}/logout    | saml_logout
 *    GET    | {routesPrefix}/metadata  | saml_metadata
 *    GET    | {routesPrefix}/sls       | saml_sls
 */
'useRoutes' => true,

'routesPrefix' => '/samlv20',

/**
 * which middleware group to use for the saml routes
 * Laravel 5.2 will need a group which includes StartSession
 */
'routesMiddleware' => [],

/**
 * Indicates how the parameters will be
 * retrieved from the sls request for signature validation
 */
'retrieveParametersFromServer' => false,

/**
 * Where to redirect after logout
 */
'logoutRoute' => '/',

/**
 * Where to redirect after login if no other option was provided
 */
'loginRoute' => '/admin/dashboard',


/**
 * Where to redirect after login if no other option was provided
 */
'errorRoute' => '/',




/*****
 * One Login Settings
 */



// If 'strict' is True, then the PHP Toolkit will reject unsigned
// or unencrypted messages if it expects them signed or encrypted
// Also will reject the messages if not strictly follow the SAML
// standard: Destination, NameId, Conditions ... are validated too.
'strict' => true, //@todo: make this depend on laravel config

// Enable debug mode (to print errors)
'debug' => false, //@todo: make this depend on laravel config

// Service Provider Data that we are deploying
'sp' => array(

    // Specifies constraints on the name identifier to be used to
    // represent the requested subject.
    // Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported
    'NameIDFormat' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent',

    // Usually x509cert and privateKey of the SP are provided by files placed at
    // the certs folder. But we can also provide them with the following parameters
    'x509cert' => '/benudata/certificates/testserver.benunets.com.cert.pem',
    'privateKey' => '/benudata/certificates/testserver.benunets.com.key.pem',

    // Identifier (URI) of the SP entity.
    // Leave blank to use the 'saml_metadata' route.
    'entityId' => 'testserver.benunets.com',

    // Specifies info about where and how the <AuthnResponse> message MUST be
    // returned to the requester, in this case our SP.
    'assertionConsumerService' => array(
        // URL Location where the <Response> from the IdP will be returned,
        // using HTTP-POST binding.
        // Leave blank to use the 'saml_acs' route
        'url' => 'https://testserver.benunets.com/admin/secure/dashboard',
    ),
    // Specifies info about where and how the <Logout Response> message MUST be
    // returned to the requester, in this case our SP.
    'singleLogoutService' => array(
        // URL Location where the <Response> from the IdP will be returned,
        // using HTTP-Redirect binding.
        // Leave blank to use the 'saml_sls' route
        'url' => 'https://testserver.benunets.com/admin/login/error',
    ),
),

// Identity Provider Data that we want connect with our SP
'idp' => array(
    // Identifier of the IdP entity  (must be a URI)
    'entityId' => 'Telenet',
    // SSO endpoint info of the IdP. (Authentication Request protocol)
    'singleSignOnService' => array(
        // URL Target of the IdP where the SP will send the Authentication Request Message,
        // using HTTP-Redirect binding.
        'url' => 'https://identityfederation.uat.connect.company/fed/idp/samlv20',
    ),
    // SLO endpoint info of the IdP.
    'singleLogoutService' => array(
        // URL Location of the IdP where the SP will send the SLO Request,
        // using HTTP-Redirect binding.
        'url' => 'https://identityfederation.uat.connect.company/fed/idp/samlv20',
    ),
    // Public x509 certificate of the IdP
    'x509cert' => '****',
    /*
     *  Instead of use the whole x509cert you can use a fingerprint
     *  (openssl x509 -noout -fingerprint -in "idp.crt" to generate it)
     */
    // 'certFingerprint' => 'Telenet need to provided',
),



/***
 *
 *  OneLogin advanced settings
 *
 *
 */
// Security settings
'security' => array(

    /** signatures and encryptions offered */

    // Indicates that the nameID of the <samlp:logoutRequest> sent by this SP
    // will be encrypted.
    'nameIdEncrypted' => false,

    // Indicates whether the <samlp:AuthnRequest> messages sent by this SP
    // will be signed.              [The Metadata of the SP will offer this info]
    'authnRequestsSigned' => false,

    // Indicates whether the <samlp:logoutRequest> messages sent by this SP
    // will be signed.
    'logoutRequestSigned' => false,

    // Indicates whether the <samlp:logoutResponse> messages sent by this SP
    // will be signed.
    'logoutResponseSigned' => false,

    /* Sign the Metadata
     False || True (use sp certs) || array (
                                                keyFileName => 'metadata.key',
                                                certFileName => 'metadata.crt'
                                            )
    */
    'signMetadata' => false,


    /** signatures and encryptions required **/

    // Indicates a requirement for the <samlp:Response>, <samlp:LogoutRequest> and
    // <samlp:LogoutResponse> elements received by this SP to be signed.
    'wantMessagesSigned' => false,

    // Indicates a requirement for the <saml:Assertion> elements received by
    // this SP to be signed.        [The Metadata of the SP will offer this info]
    'wantAssertionsSigned' => false,

    // Indicates a requirement for the NameID received by
    // this SP to be encrypted.
    'wantNameIdEncrypted' => false,

    // Authentication context.
    // Set to false and no AuthContext will be sent in the AuthNRequest,
    // Set true or don't present thi parameter and you will get an AuthContext 'exact' 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport'
    // Set an array with the possible auth context values: array ('urn:oasis:names:tc:SAML:2.0:ac:classes:Password', 'urn:oasis:names:tc:SAML:2.0:ac:classes:X509'),
    'requestedAuthnContext' => true,
),

// Contact information template, it is recommended to suply a technical and support contacts
'contactPerson' => array(
    'technical' => array(
        'givenName' => 'name',
        'emailAddress' => '[email protected]'
    ),
    'support' => array(
        'givenName' => 'Support',
        'emailAddress' => '[email protected]'
    ),
),

// Organization information template, the info in en_US lang is recomended, add more if required
'organization' => array(
    'en-US' => array(
        'name' => 'Name',
        'displayname' => 'Display Name',
        'url' => 'http://url'
    ),
),

/* Interoperable SAML 2.0 Web Browser SSO Profile [saml2int] http://saml2int.org/profile/current

'authnRequestsSigned' => false, // SP SHOULD NOT sign the samlp:AuthnRequest,
// MUST NOT assume that the IdP validates the sign
'wantAssertionsSigned' => true,
'wantAssertionsEncrypted' => true, // MUST be enabled if SSL/HTTPs is disabled
'wantNameIdEncrypted' => false,
*/

);
`

How can I prevent that ?

Packagist not updated

Hi, man.
I'm using this library with great satisfaction, but unfortunately I see Packagist is not updated with the latest version of onelogin/php-saml dependency (2.9.1 instead of 2.*).
According to Packagist update schedule, packages are updated once every month, in the worst case.
Is there any problem in updating Packagist?
Thanks in advance,

Francesco

What is the best practice to deal with SAML POST and still maintaining CSRF protection ?

I configured everything in the SP and iDP sections in saml2_settings.php
I go to : /admin/login
I got landed on my iDP log-in page immediately, it is a correct behavior.

I log-in with the proper username and password provided by my iDP.

screen shot 2017-03-28 at 2 53 54 pm

After successfully authenticated, I kept redirecting back to my log-in page/host.

I declared my routes like this

Route::get('/admin/login','SAMLController@adminSignIn');
Route::post('admin/secure/dashboard', 'SAMLController@saml_post');

SAMLController

public function adminSignIn(){
        return Saml2::login(URL::full());
    }

public function saml_post(){
        $inputs = json_decode(Input::get('json'), true);
        dd($inputs); <—— I never get to see what POST to me from my iDP
}

How do I prevent that redirect ? Do I need to create a middleware ?

Can someone please help me how to create a middleware to prevent this redirecting ?

Thanks..

Adding <ds:Signature> data to AuthnRequest

The IdP I use requires this data. I've tried a lot of different settings values & combinations, but neither resulted in signature being included in the samlp::AuthnRequest. Is it possible?

Better documentation or tutorial

Would it be possible for you to create a full tutorial on implementing a generic sign on for Laravel 5 ?
Or better documentation on the methods available in the package and how to use them?

New to SAML here ... proving very confusing. Any help would be appreciated.

Login fails

It says "SAML Response not found, Only supported HTTP_POST Binding" trying to log in.

NoAuthnContext

I am not all that familiar with SAML so bare with me.

I just installed this package in a new instance of Laravel 5. Unfortunately I am getting this error The status code of the Response was not Success, was Responder -> urn:oasis:names:tc:SAML:2.0:status:NoAuthnContext.

Any thoughts on how what this error means?

By the way I am connecting to ADFS and not PHPSimpleSaml as the IDP.

I would appreciate any suggestions. Thanks.

Token Mismatch

i tried to use this with my azure ad as idp got this error " TokenMismatchException in VerifyCsrfToken.php line 49:" are you familiar with this error?

Settings in database

Hi,

is it possible to use dynamic routesPrefix and Identity Provider Data from database?
Now all is in saml2_settings.php but I want create saml2 login for multiple IdP and I need keep settings in DB. Do you have any solution for this?

Next question is about saml2 routes. I have project with multiple authentication forms (admin, default etc.). Every authentication form is on the different subdomain. What I need is create route group with scope domain. Now I see something like this:

Route::group([
    'prefix' => config('saml2_settings.routesPrefix'),
    'middleware' => config('saml2_settings.routesMiddleware'),
], function () { 
...

Maybe better idea will be something like this:

Route::group(config('saml2_settings.routesGroup'), function () { ...

?

Last one question:
Are you thinking about integration saml2 with oauth2: https://help.sap.com/saphelp_nw74/helpdata/en/12/41087770d9441682e3e02958997846/content.htm ? IMHO it is great feature.

Best Regards
Peter

Saml2Controller->sls() doesn't fire Saml2LogoutEvent if application didn't initiate logout

When the current application doesn't fire the logout event, the application receives $_GET['SAMLRequest'] instead of $_GET['SAMLResponse'], which sends the OneLogin Saml2 library into a branch which redirects the user rather than returning:

else if (isset($_GET) && isset($_GET['SAMLRequest'])) {
    if (!$logoutRequest->isValid($retrieveParametersFromServer)) {
        $this->_errors[] = 'invalid_logout_request';
        $this->_errorReason = $logoutRequest->getError();
    } else {
        // ...
        $this->redirectTo($this->getSLOurl(), $parameters);
    }
}

What this means is that the function never returns, and the logout event never fires, which means that the user's session doesn't actually get cleared.

I'm not sure what the best option is here - we can look for that $_GET variable and fire off the logout event early (although that has problems because we're not verifying the logout request before firing the event).

Metadata not found for entity:

I have tried to set up this package, but I'm facing the error "Metadata not found for entity". Do you know what this can be? I'm new to SAML

Logout always return `Could not log out`

When logging out, app redirect URL to /saml2/logout (or Saml2Controller@logout), but it always return Could not log out.
I've tried:
Event::listen('Aacotroneo\Saml2\Events\Saml2LogoutEvent', function ($event) {
Auth::logout();
Session::save();
});

class 'aacotroneo\sam2\saml2serviceprovider' not found

I am new to the Laravel world!
I am trying to configure this Library in Laravel 5, I setup a dummy laravel application and followed your provided steps. But when I execute the below command then everything went wrong
php artisan config:publish aacotroneo/laravel-saml2

" [Symfony\Component\Debug\Exception\FatalErrorException]
class 'aacotroneo\sam2\saml2serviceprovider' not found "

Can you please help me, what I missed?
or this configuration steps is for Laravel 4 as mentioned in the "Installation - Composer" description.

Thanks in advance.

Dynamic idp_host

Hello,

Is it possible to use dynamic $idp_host? We would like to get that url from user's settings..

Usage Example

Hello,

I've got my SP and IDP settings all set up correctly and I can see my SAML response coming through file in the SAML tracer addon in firefox.

Please could you provide me an example of how to use this library in my controller to retrieve the attributes passed from the SAML response.

Thank you.

Load private keys and certificates from file (in openssl format)

In our codebase I have added some code to load private keys and certificates from key- and certificatefiles. The files have to be in openssl format.

Supported configuration options:

  • $config['sp']['x509cert']
  • $config['sp']['privateKey']
  • $config['idp']['x509cert']

The change adds a dependency to openssl to the codebase, but this is also a requirement for the Onelogin toolkit, so I see no BC breaks.

@aacotroneo If you're interested, I can push these changes to the laravel-saml2 codebase.

Invalid array settings: sp_acs_url_invalid

I updated my vendors today and now I have this error upon login. I think onelogin/php-saml has been updated and now your script is not compliant with it anymore.

exception 'OneLogin_Saml2_Error' with message 'Invalid array settings: sp_acs_url_invalid'

Where to put listen Aacotroneo\Saml2\Events\Saml2LoginEvent?

I'm trying to user laravel-saml2 with OpenAM but after login it ran in to endless loop. I think maybe because of Saml2LoginEvent is not listened at the right point. I've tried to add it in route.php, in middlware after 'StartSession` but it doesn't work.
http://localhost:8080/openam/XUI/#login/&realm=/&forward=true&spEntityID=http://lavapp.dev/saml2/metadata&goto=/SSORedirect/metaAlias/idp?ReqID=ONELOGIN_69bdcea5602172fa91feff7e67ecd06999c0ae37&index=null&acsURL=http://lavapp.dev/saml2/acs&spEntityID=http://lavapp.dev/saml2/metadata&binding=urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST&AMAuthCookie=

Incorrect Readme

The readme is confusing and will lead to a lot of errors and lost hours if followed verbatim. You should make the following changes:

METADATA
$metadata['http://laravel_url/saml2/metadata'] = array(
'AssertionConsumerService' => 'http://laravel_url/saml2/acs',
'SingleLogoutService' => 'http://laravel_url/saml2/sls',
//the following two affect what the $Saml2user->getUserId() will return
'NameIDFormat' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent',
'simplesaml.nameidattribute' => 'uid'
);

instead of

$metadata['http://laravel_url/saml/metadata'] = array(
'AssertionConsumerService' => 'http://laravel_url/saml/acs',
'SingleLogoutService' => 'http://laravel_url/saml/sls',
//the following two affect what the $Saml2user->getUserId() will return
'NameIDFormat' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent',
'simplesaml.nameidattribute' => 'uid'
);

LOGIN AND LOGOUT
Use Saml2;
......
......
Saml2::login() and Saml2::logout()

instead of
Saml2Auth::login() and Saml2Auth::logout()

Unable to run php artisan vendor:publish

The command doesn't appear in the php artisan list, and I tried to run clear-compiled and dump-autoload to no avail as well.

Can I just insert that config file in the location the docs showed?

Wade

Cannot set an arbitrary string as sp identifier

Assuming the SAML2 authentication uses a metadata.xml, the sp entityId automatically sets the entityId to the saml_metadata route, but the use of the metadata.xml should be optional.

When not using a metadata.xml, an sp entityId URI can be chosen at will, as long as it matches the configured entityId on the idp. At my client the entityId is simply a domain name (without scheme).

As a solution, I propose adding an empty-check on the config-value when setting the sp entityId. Line 45 in the Saml2ServiceProvider class would be changed to:

$config['sp']['entityId'] = empty($config['sp']['entityId']) ? URL::route('saml_metadata') : $config['sp']['entityId'];

If it's is ok, I'll create a PR to apply the change.

Authentication persistence

Hi Alejandro

I've successfully integrated the library in Laravel 5.0, got the login/redirecting working properly, but cannot access SSO session persistence. What this means is that the isAuthenticated() function in Saml2Auth.php returns true if it is executed in the same request where the login process succeeds, but false at any other time, even if it's in the next request immediately after the successful login.

This makes it very hard to design my middleware properly, because ideally I would run the isAuthenticated() function as a check and only allow the Saml2::login() to proceed when the isAuthenticated() function returns false. However, it always returns false, thus causing infinite looping redirects, because the login function is called on a valid session on all requests after the initial login.

Have you had this problem before?

Thanks

John

Setting RelayState

How can I set the RelayState upon login so when the user comes back to my site I can redirect them?

Class 'Illuminate\Auth\Middleware\Saml2' not found

I'm trying to use this package to login multiple applications but getting this error.
I have changed following in Illuminate\Auth\Middleware\Authenticate.php

From:
public function handle($request, Closure $next, ...$guards)
{
$this->authenticate($guards);
return $next($request);
}

To:

public function handle($request, Closure $next, ...$guards)
{
//$this->authenticate($guards);
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return Saml2::login(URL::full());
//return redirect()->guest('auth/login');
}
}

    return $next($request);
}

And I'm trying login two applications saml and saml2(application name).
What will be the solution for it.

Custom saml call after login

Is it possible to execute a custom SAML call after the user has logged in? I was thinking of dynamically changing the settings returned by saml2_settings.php and then call the Saml2::login() function again. Is that the best way to accomplish this or is there a better way?

Just to ask a question

Can i use this as a SP for developing laravel where im using azure ad as my IDP... hoping for reply !!

Error in OneLogin SAML Util.php

I have configured this per the instructions included in the readme.md. However when I attempt to go to /saml2/metadata I get PHP Fatal error: 'continue' not in the 'loop' or 'switch' context in /app/vendor/onelogin/php-saml/lib/Saml2/Utils.php on line 1006. For reference I am using V0.6.0

Need a little help - How to use this package with simplesamlphp

Hi,
Thanks for doing this development. I'm trying to use this package but I need to use simplesamlphp... I'm not sure what i need to do in order to use that instead of onelogin. Could you give me hints or steps in what i need to do for getting this work? I guess I need to install simplesamlphp library, but controllers are calling an instance of onelogin.

Thanks a lot I appreciate your time

example with custom authprovider for 5.3

Hi,

the documentation for the authprovider is for 5.2. Does anyone have a working example available for 5.3 ? Preferable with automatic user creation?

Thanks!

Questions

We would like to use this package on a project we are developing however one of the requirements is the user enters his/her credentials on our site and we send them over to the idp. Would this package work for that?

Also we are using laravel 4.2.7 could we install this package on that version or would we have to upgrade to 5.x? If we do need to upgrade, which version would be best to use 5.0 or 5.1?

Helper function misusage on Saml2User.php

With 0d5412d commit, Saml2User.php became broken.
While replacing facade usages with helper function, url() helper function misused.
url() helper function returns string, so that url()->full() usage is wrong

Reference validation failed error.

When I am enabling the following security options, I am getting a 'Reference validation error'.

'authnRequestsSigned' => true,
'wantAssertionsSigned' => true,

local.ERROR: Saml2 error ["invalid_response"]

I am receiving the following in the laravel log after the SAML is returned from the IDP. In chrome using the SAML inspector tool everything looks fine.

No login event is fired within laravel.

Any suggestions?

Thank you

Saml2LoginEvent doesn't fire in Laravel 5.3

I have this in my EventServiceProvider:

public function boot() 
{
    parent::boot();

    Event::listen('Aacotroneo\Saml2\Events\Saml2LoginEvent', function (Saml2LoginEvent $event) {
        Log::info('Saml2LoginEvent');
    });
…
}

In my controller I have something like this:

public function acs(Request $request) {
    $samldata = $request->get('SAMLResponse');
…
}

My config settings look like this:

$idp_host = 'http://localhost/simplesaml';

return $settings = array(
    /*****
     * Cosmetic settings - controller routes
     **/
    'useRoutes' => true, //include library routes and controllers


    'routesPrefix' => '/saml2',

    /**
     * which middleware group to use for the saml routes
     * Laravel 5.2 will need a group which includes StartSession
     */
    'routesMiddleware' => ['web'],

… the rest is default

I have added the Saml routes to my web routes:
// Login lands here
Route::post('saml/acs', 'TestController@acs');
// Single Logout Services
Route::get('saml/sls', 'TestController@sls');

I do see the SAMLResponse coming in at TestController@acs and I can parse it with DOMXPath.
So it looks like it's working. But I would expect the event being fired too…

Am I missing something or is this a bug?

Suggestion: Remove input related functions from Saml2User

Just a suggestion, but I think that the User object shouldn't really be responsible for dealing with input from the request.

I'm thinking of making an MR which moves this responsibility out, so that the controller does the getIntendedUrl logic internally, and moving the getRawSamlAssertation onto the Saml2LoginEvent so it can still be accessed by the parent application.

My only worry is that this would be a breaking change to the previous versions, but if you are happy with that I think it sticks to the Single Responsibility Principle a bit more.

Support for Lumen

Quick question, are you planning on supporting Lumen anytime in the near future? There are only a few small issues to be ironed out I believe.

Saml2 with laravel 5 Logout issue with google SLO

Hi,

When i am trying to logout using the Saml2Auth::logout(); with google its showing the following error

Error parsing the request, malformed_request: The SAML request is malformed

can help me about this what i am missing in settings

Disable SingleLogoutService for SP

Hi,

I don't want to expose a single-logout service, so I expected to do something like this in the "config/saml2_settings.php":

'sp' => array(
    ...
    'singleLogoutService' => false,
),

But this still sets up the service in the Saml2ServiceProvider@register. When I remove/comment out this part it is working:

if (empty($config['sp']['singleLogoutService']['url'])) {
    $config['sp']['singleLogoutService']['url'] = URL::route('saml_sls');
}

Why isn't this supported? Maybe it's better to check if the singleLogoutService even exists and if it does if the value isn't equal to false before inserting it.

@aacotroneo what do you think about it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.