Caused by simplesaml module saml error responder

Exception and error handling in SimpleSAMLphp This document describes the way errors and exceptions are handled in authentication sources and authentication processing filters. The basic goal is to be able to throw an exception during authentication, and then have that exception transported back to the SP in a way that the SP understands. This […]

Содержание

  1. Exception and error handling in SimpleSAMLphp
  2. Throwing exceptions
  3. Returning specific SAML 2 errors
  4. Converting SAML 2 errors to normal exceptions
  5. Other protocols
  6. Technical details
  7. SimpleSAMLErrorException
  8. SimpleSAMLAuthState
  9. throwException
  10. loadException
  11. SimpleSAMLAuthProcessingChain
  12. Custom error show function
  13. SimpleSAML_Error_Error: UNHANDLEDEXCEPTION #541
  14. Comments
  15. Footer
  16. Session problems! #365
  17. Comments

Exception and error handling in SimpleSAMLphp

This document describes the way errors and exceptions are handled in authentication sources and authentication processing filters. The basic goal is to be able to throw an exception during authentication, and then have that exception transported back to the SP in a way that the SP understands.

This means that internal SimpleSAMLphp exceptions must be mapped to transport specific error codes for the various transports that are supported by SimpleSAMLphp. E.g.: When a SimpleSAMLErrorNoPassive error is thrown by an authentication processing filter in a SAML 2.0 IdP, we want to map that exception to the urn:oasis:names:tc:SAML:2.0:status:NoPassive status code. That status code should then be returned to the SP.

Throwing exceptions

How you throw an exception depends on where you want to throw it from. The simplest case is if you want to throw it during the authenticate() -method in an authentication module or during the process() -method in a processing filter. In those methods, you can just throw an exception:

Exceptions thrown at this stage will be caught and delivered to the appropriate error handler.

If you want to throw an exception outside of those methods, i.e. after you have done a redirect, you need to use the SimpleSAMLAuthState::throwException() function:

The SimpleSAMLAuthState::throwException function will then transfer your exception to the appropriate error handler.

Note that we use the SimpleSAMLErrorException class in both cases. This is because the delivery of the exception may require a redirect to a different web page. In those cases, the exception needs to be serialized. The normal Exception class in PHP isn’t always serializable.

If you throw an exception that isn’t a subclass of the SimpleSAMLErrorException class, your exception will be converted to an instance of SimpleSAMLErrorUnserializableException . The SimpleSAMLAuthState::throwException function does not accept any exceptions that does not subclass the SimpleSAMLErrorException class.

Returning specific SAML 2 errors

By default, all thrown exceptions will be converted to a generic SAML 2 error. In some cases, you may want to convert the exception to a specific SAML 2 status code. For example, the SimpleSAMLErrorNoPassive exception should be converted to a SAML 2 status code with the following properties:

  • The top-level status code should be urn:oasis:names:tc:SAML:2.0:status:Responder .
  • The second-level status code should be urn:oasis:names:tc:SAML:2.0:status:NoPassive .
  • The status message should contain the cause of the exception.

The SimpleSAMLModulesamlError class represents SAML 2 errors. It represents a SAML 2 status code with three elements: the top-level status code, the second-level status code and the status message. The second-level status code and the status message is optional, and can be NULL .

The SimpleSAMLModulesamlError class contains a helper function named fromException . The fromException() function is used by www/saml2/idp/SSOService.php to return SAML 2 errors to the SP. The function contains a list which maps various exceptions to specific SAML 2 errors. If it is unable to convert the exception, it will return a generic SAML 2 error describing the original exception in its status message.

To return a specific SAML 2 error, you should:

  • Create a new exception class for your error. This exception class must subclass SimpleSAMLErrorException .
  • Add that exception to the list in fromException() .
  • Consider adding the exception to toException() in the same file. (See the next section.)

While it is possible to throw SAML 2 errors directly from within authentication sources and processing filters, this practice is discouraged. Throwing SAML 2 errors will tie your code directly to the SAML 2 protocol, and it may be more difficult to use with other protocols.

Converting SAML 2 errors to normal exceptions

On the SP side, we want to convert SAML 2 errors to SimpleSAMLphp exceptions again. This is handled by the toException() method in SimpleSAMLModulesamlError . The assertion consumer script of the SAML 2 authentication source ( modules/saml2/sp/acs.php ) uses this method. The result is that generic exceptions are thrown from that authentication source.

For example, NoPassive errors will be converted back to instances of SimpleSAMLErrorNoPassive .

Other protocols

The error handling code has not yet been added to other protocols, but the framework should be easy to adapt for other protocols. To eventually support other protocols was a goal when designing this framework.

Technical details

This section attempts to describe the internals of the error handling framework.

SimpleSAMLErrorException

The SimpleSAMLErrorException class extends the normal PHP Exception class. It makes the exceptions serializable by overriding the __sleep() method. The __sleep() method returns all variables in the class which should be serialized when saving the class.

To make sure that the class is serializable, we remove the $trace variable from the serialization. The $trace variable contains the full stack trace to the point where the exception was instantiated. This can be a problem, since the stack trace also contains the parameters to the function calls. If one of the parameters in unserializable, serialization of the exception will fail.

Since preserving the stack trace can be useful for debugging, we save a variant of the stack trace in the $backtrace variable. This variable can be accessed through the getBacktrace() method. It returns an array with one line of text for each function call in the stack, ending on the point where the exception was created.

Since we lose the original $trace variable during serialization, PHP will fill it with a new stack trace when the exception is unserialized. This may be confusing since the new stack trace leads into the unserialize() function. It is therefore recommended to use the getBacktrace() method.

SimpleSAMLAuthState

There are two methods in this class that deals with exceptions:

  • throwException($state, $exception) , which throws an exception.
  • loadExceptionState($id) , which restores a state containing an exception.

throwException

This method delivers the exception to the code that initialized the exception handling in the authentication state. That would be www/saml2/idp/SSOService.php for processing filters. To configure how and where the exception should be delivered, there are two fields in the state-array which can be set:

  • SimpleSAMLAuthState::EXCEPTION_HANDLER_FUNC , in which case the exception will be delivered by a function call to the function specified in that field.
  • SimpleSAMLAuthState::EXCEPTION_HANDLER_URL , in which case the exception will be delivered by a redirect to the URL specified in that field.

If the exception is delivered by a function call, the function will be called with two parameters: The exception and the state array.

If the exception is delivered by a redirect, SimpleSAMLAuthState will save the exception in a field in the state array, pass a parameter with the id of the state array to the URL. The SimpleSAMLAuthState::EXCEPTION_PARAM constant contains the name of that parameter, while the SimpleSAMLAuthState::EXCEPTION_DATA constant holds the name of the field where the exception is saved.

loadException

To retrieve the exception, the application should check for the state parameter in the request, and then retrieve the state array by calling SimpleSAMLAuthState::loadExceptionState() . The exception can be located in a field named SimpleSAMLAuthState::EXCEPTION_DATA . The following code illustrates this behaviour:

SimpleSAMLAuthProcessingChain

This class requires the caller to add the error handler to the state array before calling the processState() function. Exceptions thrown by the processing filters will be delivered directly to the caller of processState() if possible. However, if one of the filters in the processing chain redirected the user away from the caller, exceptions will be delivered through the error handler saved in the state array.

This is the same behaviour as normal processing filters. The result will be delivered directly if it is possible, but if not, it will be delivered through a redirect.

The code for handling this becomes something like:

An exception which isn’t a subclass of SimpleSAMLErrorException will be converted to the SimpleSAMLErrorUnserializedException class. This happens regardless of whether the exception is delivered directly or through the error handler. This is done to be consistent in what the application receives — now it will always receive the same exception, regardless of whether it is delivered directly or through a redirect.

Custom error show function

Optional custom error show function, called from SimpleSAMLErrorError::show, is defined with ‘errors.show_function’ in config.php.

Example code for this function, which implements the same functionality as SimpleSAMLErrorError::show, looks something like:

Источник

SimpleSAML_Error_Error: UNHANDLEDEXCEPTION #541

We have deployed simplesamlphp plugin into one of our production application and have started facing an issue, when a user tries to login he gets to see a page

I have enabled the debug log and this is the piece from the logs

Jan 09 09:15:11 simplesamlphp DEBUG [b2cdbc1457] Loading state: ‘_bae4dbe6d54c01f939321b1652c48c3d859f2b1aab’
Jan 09 09:15:11 simplesamlphp DEBUG [b2cdbc1457] Received SAML2 Response from ‘https://xyz.abc.com:443/pqr’.
Jan 09 09:15:11 simplesamlphp ERROR [b2cdbc1457] SimpleSAML_Error_Error: UNHANDLEDEXCEPTION
Jan 09 09:15:11 simplesamlphp ERROR [b2cdbc1457] Backtrace:
Jan 09 09:15:11 simplesamlphp ERROR [b2cdbc1457] 0 E:wampwwwAuthSPwwwmodule.php:180 (N/A)
Jan 09 09:15:11 simplesamlphp ERROR [b2cdbc1457] Caused by: sspmod_saml_Error: Responder
Jan 09 09:15:11 simplesamlphp ERROR [b2cdbc1457] Backtrace:
Jan 09 09:15:11 simplesamlphp ERROR [b2cdbc1457] 3 E:wampwwwAuthSPmodulessamllibMessage.php:392 (sspmod_saml_Message::getResponseError)
Jan 09 09:15:11 simplesamlphp ERROR [b2cdbc1457] 2 E:wampwwwAuthSPmodulessamllibMessage.php:499 (sspmod_saml_Message::processResponse)
Jan 09 09:15:11 simplesamlphp ERROR [b2cdbc1457] 1 E:wampwwwAuthSPmodulessamlwwwspsaml2-acs.php:120 (require)
Jan 09 09:15:11 simplesamlphp ERROR [b2cdbc1457] 0 E:wampwwwAuthSPwwwmodule.php:137 (N/A)
Jan 09 09:15:11 simplesamlphp ERROR [b2cdbc1457] Error report with id bdbd09a1 generated.
Jan 09 09:15:11 simplesamlphp DEBUG [b2cdbc1457] Template: Reading [E:wampwwwAuthSPdictionaries/errors]
Jan 09 09:15:11 simplesamlphp DEBUG [b2cdbc1457] Received message:
Jan 09 09:15:11 simplesamlphp DEBUG [b2cdbc1457]
Jan 09 09:15:11 simplesamlphp DEBUG [b2cdbc1457] https://xyz.abc.com:443/openam
Jan 09 09:15:11 simplesamlphp DEBUG [b2cdbc1457]
Jan 09 09:15:11 simplesamlphp DEBUG [b2cdbc1457]
Jan 09 09:15:11 simplesamlphp DEBUG [b2cdbc1457]
Jan 09 09:15:11 simplesamlphp DEBUG [b2cdbc1457]

The text was updated successfully, but these errors were encountered:

This is an issue tracker, not a support forum. I don’t see any issue in SimpleSAMLphp here, but just an error message being sent back to you from the IdP, so I recommend you to ask in the mailing list.

In any case, I doubt anybody can help you out with such small amount of information. You really need to get in touch with the IdP to figure out what’s going on.

@jaimeperez Thanks for the information. Do you know someone who can help me out with this. Being it a production server, its really important that I should get to the roor cause or atleast find a fix to avoid these errors

The IdP is sending an error message. You should look in the logs of the IdP to find out why it does that.

@jaimeperez this is the error at iDP end

libPlugins:01/09/2017 09:17:30:563 AM EST: Thread[http-nio-149.25.153.123-443-exec-10,5,main]
FMSessionProvider.getSession: Could not get the session from the HTTP request: Invalid session ID.

That software is not simpleSAMLphp. So you’re not in the right place to ask questions about it.

@thijskh the iDP is a product of openAM but the SP is simplesamlphp

@SalilLambe as I just told you in the mailing list, the error is in the IdP, not in the SP. Therefore, there’s no relation at all with SimpleSAMLphp.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Session problems! #365

I am very new to SAML so I might be doing things wrong. I have described my problem at SO: http://stackoverflow.com/questions/36655953/simplesamlphp-unable-to-find-the-current-binding. (I have a local copy in case it gets closed. )

All the above errors seem to appear randomly due to faulty state of some sort. I am using (and modifying) $_SESSION in my application and I have noticed that it is getting changed/replaced by SSP. If I remove all the code that changes session (including _start() / _destroy() ), login and logout works without crashing. Is there a specific way I should be handling the session?

I have tried to set the store.type to sql , in which case, an sqlite file is created but SSP always comes back with «NO STATE» error. Also note that I can see apache segfaulting in the logs

My site login logic:

and the SSP authentication:

Any help would be appreciated

Working on:
RHEL 7
PHP 5.4.16
Apache 2.4
simplesamlphp 1.14.2

The text was updated successfully, but these errors were encountered:

This is a duplicate of #224 and #349. It has been already fixed and the fix will be available in the next release (about to come out). Check the related issues for more information on how to use PHP sessions in both your application and SimpleSAMLphp at the same time from now on.

@jaimeperez Do I have to apply the mentioned patch? Is master stable enough to use?

No, the patch was unfortunately not enough to solve all the issues with the PHP session handler. However, we just released 1.14.3 today, including the fix for this issue 😉

Master is usually pretty stable (we try hard at least), but of course that doesn’t mean we don’t make mistakes sometimes and break things, so I’d recommend you to stick to stable releases unless you really need something.

Cool, thanks for the quick reply. I will upgrade and let you know

Hey, unfortunately I am still getting the same error(s) and apache keeps on segfaulting. I checked the new code and session_write_close() is being called but the the session ID remains the same. I do call $session->cleanup(); but the session still shows «SimpleSAMLphp_SESSION» entry:

Also, tried to shift the store.type to sql but as before, I get a «no state» error every time. I will try to debug this but I am kinda lost atm.

The segfaults might be related to #293. If you are experiencing them often, those could lead to the sessions not being properly saved to the backend ( sql in this case) and causing a NO_STATE error. The only way to fix that is to upgrade PHP to some version more up to date, as the segfaults are due to a bug in PHP itself.

Regarding the PHP session not being recovered, can you provide the entire script you are using to test? What’s its output? Did you try the script provided in #224? Did it work?

I run the script from #224. If I do not set the name of/rename the session I get:

Note that empty attributes is correct (no claims). Now, if I do set the session name I get:

The whole script:

Is there any particular settings I should have to rename session? (Either in php.ini or config.php).

[PS: It is getting «beer o’clock» so most probably I will be on this tomorrow again. ]

Yes, you should give your SimpleSAMLphp cookie its own name. If you don’t have one configured, it will take the default, which could lead to trouble. Did you set the session.phpsession.cookiename in config/config.php ? In that case, to what value?

In any case, if you are using the defaults in SimpleSAMLphp and setting a session name in the script, that should definitely not lead to a NO_STATE error. I’ll have to look into that.

Enjoy the beers! 🍻

This works. It would have taken me a million years to sort it out :). Note that both the application session_name and the session.phpsession.cookiename must be set to non-default values in order to work on my setup.

I am happy with how it works now but I have two more questions:

I sometimes get the following error.I assume it is because I login and out too fast and the IdP says «no» at some point:

Which would be the correct way to implement logout:

works and I can see the redirect to the IdP. However, in the test script we used the session:

which also works, but I do not see the redirection. I assume it cleans the SSP session data but it does not logout from the IdP — which I am not sure if it is needed. The session works a lot better for me since the first one leads to ACSPARAMS and SLOSERVICEPARAMS errors with the following steps:

  1. Starting with «This page can’t be displayed»
  2. Refresh (F5)
  3. May produce a PHP Notice: Undefined property: DOMDocument::$x�j5� in �d�5� on line 352 which I think is the PHP bug we talked about (this is actually refering to lib/SimpleSAML/Session.php line 352)
  4. SSP error page

I suspect that the last problem is related to #293 and has nothing to do with SSP.

Anyway, thank you very very much for your help! Let me know if you want me to run any other tests

Glad you got it to work! Did you try calling session_name() in your app, and let SimpleSAMLphp using the default session, and the other way around? Of course, the application and SimpleSAMLphp need to use different session names, since that’s what determines the name of the cookie set. Different cookies mean different session IDs, and therefore different sessions overall. But the name you use (whether that’s the default or not) should be irrelevant, provided both use different names.

Now, regarding your two questions:

  1. I sometimes get the following error.I assume it is because I login and out too fast and the IdP says «no» at some point:

That’s an error you are getting from the IdP. Aren’t you getting any more information in the error page or in the log files? You could also try to replicate the error while monitoring the SAML exchange with SAML tracer so that you can see the SAML response you are getting posted.

Which would be the correct way to implement logout:

works and I can see the redirect to the IdP. However, in the test script we used the session:

The first one. As you have noticed, that’s the way to trigger a single logout. The latter does only log out the local session, not informing the IdP (nor any other service providers you might be logged into). I only added that in the test script to make sure that if we try to use SimpleSAMLphp’s session after cleaning up, the session gets loaded again, but you should never mess directly with the session.

The session works a lot better for me since the first one leads to ACSPARAMS and SLOSERVICEPARAMS errors with the following steps:

That could happen if you access the endpoints directly, which you shouldn’t do.

How do you reach there?

  1. Refresh (F5)
  2. May produce a PHP Notice: Undefined property: DOMDocument::$x�j5� in �d�5� on line 352 which I think is the PHP bug we talked about (this is actually refering to lib/SimpleSAML/Session.php line 352)

That sounds really weird. Binary data as the name of property? 😟

What does the error say? Any logs?

I suspect that the last problem is related to #293 and has nothing to do with SSP.

No, I don’t think so. That problem was causing segfaults when PHP finishes its execution and SimpleSAMLphp tries to save the session if it was modified. If that was the case, you should be seeing segfaults in your server’s log when this error appears. And in any case, it’s not something related to logout itself, but to session handling, so if this was the issue you would be experiencing errors all over the place, not only when trying to perform a single logout.

I am testing by login/out fast. The logout completes successfully but the next login might fail. On failure there are few different cases:

last test got stuck on the url . /saml/module.php/saml/sp/saml2-acs.php/sar-dev-sp with no error in the logs. A refresh leads to ACSPARAMS error.

Sometimes the logout seems to be called twice:

the code in my logout.php

There are cases that produce a weird error. Logs with corrupted file names or meaningless filename:

  • Trying to get property of non-object .
  • PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 1852399989 bytes) in Unknown on line 0 refresh leads to NOSTATE )
  • PHP Warning: Unknown: Could not call the sapi_header_callback in Unknown on line 0

Now, in order not to waste your time I ‘d suggest I debug this and come back to you when I have something more specific/solid. the above is all over the place 🙂

Thanks for the feedback @urban-1!

The last errors you are mentioning are indeed related to the PHP bug we were talking about. I’d recommend to start by upgrading PHP itself.

The ACSPARAMS error is normal if you reload that page without posting the data again (i.e. selecting the URL and hitting enter ), as you cannot access that endpoint without proper parameters. The error page should be clear about this: «No SAML response provided». The details may vary a bit between the latest stable and master, though.

The best advice I can give you is to use SAML tracer as much as possible. It will help you see what’s actually happening under the hood between the IdP and the SP. Besides, check also the error.log of your webserver, as it might contain information about uncaught exceptions that did not make it to the SimpleSAMLphp log.

Let me know what you find out, any help is very much appreciated! 😉

I have installed this SAML tracer for Chrome. I tested login and logout over and over again. The only anomaly I can see is that the tracer reports a GET with status 0 which points to a «socket closed» or ERR_EMPTY_RESPONSE! Looking at the server’s logs at the same time (usually error_log , ssl_error_log and my app’s log), all I can see is more SegFaults. as opposed to the usual single segfault per request (It is scary how naturally this comes out 😄 !). Therefore, I am pretty sure that all the problems/errors arise from the fact that PHP segfaults in a random way and leaves SSP in a broken state. I don’t think that any of the above is related to SSP.

I am reading that this SegFault has been fixed in PHP 5.4.20 and 5.5.2, so I ‘ll ask tomorrow the sysadmins to update the host. Till this is done I am afraid I cannot provide much more info. However, once the update is rolled out, I can post here to let you know.

Once again, thanks a lot for you time and effort

PS:I will close/answer the SO question and point it there

Источник

Exception and error handling in SimpleSAMLphp

This document describes the way errors and exceptions are handled in authentication sources and authentication processing filters.
The basic goal is to be able to throw an exception during authentication, and then have that exception transported back to the SP in a way that the SP understands.

This means that internal SimpleSAMLphp exceptions must be mapped to transport specific error codes for the various transports that are supported by SimpleSAMLphp.
E.g.: When a

SimpleSAMLErrorNoPassive

error is thrown by an authentication processing filter in a SAML 2.0 IdP, we want to map that exception to the

urn:oasis:names:tc:SAML:2.0:status:NoPassive

status code.
That status code should then be returned to the SP.

Throwing exceptions

How you throw an exception depends on where you want to throw it from.
The simplest case is if you want to throw it during the

authenticate()

-method in an authentication module or during the

process()

-method in a processing filter.
In those methods, you can just throw an exception:

  public function process(&$state) {
      if ($state['something'] === false) {
          throw new SimpleSAMLErrorException('Something is wrong...');
      }
  }

Exceptions thrown at this stage will be caught and delivered to the appropriate error handler.

If you want to throw an exception outside of those methods, i.e. after you have done a redirect, you need to use the

SimpleSAMLAuthState::throwException()

function:

  <?php
  $id = $_REQUEST['StateId'];
  $state = SimpleSAMLAuthState::loadState($id, 'somestage...');
  SimpleSAMLAuthState::throwException($state,
      new SimpleSAMLErrorException('Something is wrong...'));
  ?>

The

SimpleSAMLAuthState::throwException

function will then transfer your exception to the appropriate error handler.

Note

Note that we use the

SimpleSAMLErrorException

class in both cases.
This is because the delivery of the exception may require a redirect to a different web page.
In those cases, the exception needs to be serialized.
The normal

Exception

class in PHP isn’t always serializable.

If you throw an exception that isn’t a subclass of the

SimpleSAMLErrorException

class, your exception will be converted to an instance of

SimpleSAMLErrorUnserializableException

.
The

SimpleSAMLAuthState::throwException

function does not accept any exceptions that does not subclass the

SimpleSAMLErrorException

class.

Returning specific SAML 2 errors

By default, all thrown exceptions will be converted to a generic SAML 2 error.
In some cases, you may want to convert the exception to a specific SAML 2 status code.
For example, the

SimpleSAMLErrorNoPassive

exception should be converted to a SAML 2 status code with the following properties:

  • The top-level status code should be

    urn:oasis:names:tc:SAML:2.0:status:Responder

    .
  • The second-level status code should be

    urn:oasis:names:tc:SAML:2.0:status:NoPassive

    .
  • The status message should contain the cause of the exception.

The

SimpleSAMLModulesamlError

class represents SAML 2 errors.
It represents a SAML 2 status code with three elements: the top-level status code, the second-level status code and the status message.
The second-level status code and the status message is optional, and can be

NULL

.

The

SimpleSAMLModulesamlError

class contains a helper function named

fromException

.
The

fromException()

function is used by

www/saml2/idp/SSOService.php

to return SAML 2 errors to the SP.
The function contains a list which maps various exceptions to specific SAML 2 errors.
If it is unable to convert the exception, it will return a generic SAML 2 error describing the original exception in its status message.

To return a specific SAML 2 error, you should:

  • Create a new exception class for your error. This exception class must subclass

    SimpleSAMLErrorException

    .
  • Add that exception to the list in

    fromException()

    .
  • Consider adding the exception to

    toException()

    in the same file. (See the next section.)

Note

While it is possible to throw SAML 2 errors directly from within authentication sources and processing filters, this practice is discouraged.
Throwing SAML 2 errors will tie your code directly to the SAML 2 protocol, and it may be more difficult to use with other protocols.

Converting SAML 2 errors to normal exceptions

On the SP side, we want to convert SAML 2 errors to SimpleSAMLphp exceptions again.
This is handled by the

toException()

method in

SimpleSAMLModulesamlError

.
The assertion consumer script of the SAML 2 authentication source (

modules/saml2/sp/acs.php

) uses this method.
The result is that generic exceptions are thrown from that authentication source.

For example,

NoPassive

errors will be converted back to instances of

SimpleSAMLErrorNoPassive

.

Other protocols

The error handling code has not yet been added to other protocols, but the framework should be easy to adapt for other protocols.
To eventually support other protocols was a goal when designing this framework.

Technical details

This section attempts to describe the internals of the error handling framework.


SimpleSAMLErrorException

The

SimpleSAMLErrorException

class extends the normal PHP

Exception

class.
It makes the exceptions serializable by overriding the

__sleep()

method.
The

__sleep()

method returns all variables in the class which should be serialized when saving the class.

To make sure that the class is serializable, we remove the

$trace

variable from the serialization.
The

$trace

variable contains the full stack trace to the point where the exception was instantiated.
This can be a problem, since the stack trace also contains the parameters to the function calls.
If one of the parameters in unserializable, serialization of the exception will fail.

Since preserving the stack trace can be useful for debugging, we save a variant of the stack trace in the

$backtrace

variable.
This variable can be accessed through the

getBacktrace()

method.
It returns an array with one line of text for each function call in the stack, ending on the point where the exception was created.

Note

Since we lose the original

$trace

variable during serialization, PHP will fill it with a new stack trace when the exception is unserialized.
This may be confusing since the new stack trace leads into the

unserialize()

function.
It is therefore recommended to use the getBacktrace() method.


SimpleSAMLAuthState

There are two methods in this class that deals with exceptions:


  • throwException($state, $exception)

    , which throws an exception.

  • loadExceptionState($id)

    , which restores a state containing an exception.


throwException

This method delivers the exception to the code that initialized the exception handling in the authentication state.
That would be

www/saml2/idp/SSOService.php

for processing filters.
To configure how and where the exception should be delivered, there are two fields in the state-array which can be set:


  • SimpleSAMLAuthState::EXCEPTION_HANDLER_FUNC

    , in which case the exception will be delivered by a function call to the function specified in that field.

  • SimpleSAMLAuthState::EXCEPTION_HANDLER_URL

    , in which case the exception will be delivered by a redirect to the URL specified in that field.

If the exception is delivered by a function call, the function will be called with two parameters: The exception and the state array.

If the exception is delivered by a redirect, SimpleSAMLAuthState will save the exception in a field in the state array, pass a parameter with the id of the state array to the URL.
The

SimpleSAMLAuthState::EXCEPTION_PARAM

constant contains the name of that parameter, while the

SimpleSAMLAuthState::EXCEPTION_DATA

constant holds the name of the field where the exception is saved.


loadException

To retrieve the exception, the application should check for the state parameter in the request, and then retrieve the state array by calling

SimpleSAMLAuthState::loadExceptionState()

.
The exception can be located in a field named

SimpleSAMLAuthState::EXCEPTION_DATA

.
The following code illustrates this behaviour:

  if (array_key_exists(SimpleSAMLAuthState::EXCEPTION_PARAM, $_REQUEST)) {
      $state = SimpleSAMLAuthState::loadExceptionState();
      $exception = $state[SimpleSAMLAuthState::EXCEPTION_DATA];

      /* Process exception. */
  }


SimpleSAMLAuthProcessingChain

This class requires the caller to add the error handler to the state array before calling the

processState()

function.
Exceptions thrown by the processing filters will be delivered directly to the caller of

processState()

if possible.
However, if one of the filters in the processing chain redirected the user away from the caller, exceptions will be delivered through the error handler saved in the state array.

This is the same behaviour as normal processing filters.
The result will be delivered directly if it is possible, but if not, it will be delivered through a redirect.

The code for handling this becomes something like:

  if (array_key_exists(SimpleSAMLAuthState::EXCEPTION_PARAM, $_REQUEST)) {
      $state = SimpleSAMLAuthState::loadExceptionState();
      $exception = $state[SimpleSAMLAuthState::EXCEPTION_DATA];

      /* Handle exception... */
      [...]
  }

  $procChain = [...];

  $state = [
      'ReturnURL' => SimpleSAMLUtilsHTTP::getSelfURLNoQuery(),
      SimpleSAMLAuthState::EXCEPTION_HANDLER_URL => SimpleSAMLUtilsHTTP::getSelfURLNoQuery(),
      [...],
  ]

  try {
      $procChain->processState($state);
  } catch (SimpleSAMLErrorException $e) {
      /* Handle exception. */
      [...];
  }

Note

An exception which isn’t a subclass of

SimpleSAMLErrorException

will be converted to the

SimpleSAMLErrorUnserializedException

class.
This happens regardless of whether the exception is delivered directly or through the error handler.
This is done to be consistent in what the application receives — now it will always receive the same exception, regardless of whether it is delivered directly or through a redirect.

Custom error show function

Optional custom error show function, called from SimpleSAMLErrorError::show, is defined with ‘errors.show_function’ in config.php.

Example code for this function, which implements the same functionality as SimpleSAMLErrorError::show, looks something like:

  public static function show(SimpleSAMLConfiguration $config, array $data) {
      $t = new SimpleSAMLXHTMLTemplate($config, 'error.php', 'errors');
      $t->data = array_merge($t->data, $data);
      $t->show();
      exit;
  }
  • Remove From My Forums
  • Вопрос

  • I am integrating a php application with ADFS using simplesamlphp. I am getting the following error when i try to login. Somebody please help. your help is much appreciated.

    SimpleSAML_Error_Error: UNHANDLEDEXCEPTION

    Backtrace:
    0 /var/simplesamlphp/www/module.php:180 (N/A)
    Caused by: sspmod_saml_Error: Responder
    Backtrace:
    3 /var/simplesamlphp/modules/saml/lib/Message.php:392 (sspmod_saml_Message::getResponseError)
    2 /var/simplesamlphp/modules/saml/lib/Message.php:499 (sspmod_saml_Message::processResponse)
    1 /var/simplesamlphp/modules/saml/www/sp/saml2-acs.php:120 (require)
    0 /var/simplesamlphp/www/module.php:137 (N/A)
    • Перемещено

      21 сентября 2016 г. 10:48

Ответы

    • Предложено в качестве ответа
      Dave PatrickMVP
      14 октября 2016 г. 23:09
    • Помечено в качестве ответа
      Dave PatrickMVP
      15 октября 2016 г. 16:39

Пробую настроить SimpleSAMLphp, для авторизации через WSO2 IS.
в authsources.php

'wso2-sp' => array(
      'saml:SP',
      'entityID' => 'localhost',
     'idp' => 'localhost',
     'discoURL' => NULL,
         'certificate' => 'cert.pem',
         'privatekey' => 'cert.pem',
         'privatekey_pass' => 'xxxx' 
     )

в saml20-idp-remote.php

$metadata['localhost'] = array(
    'name' => array(
    'en' =>  'WSO2 IS',
    'no' =>  'WSO2 IS',
),
    'description'   =>  'Login with WSO2 IS SAML2 IdP.',
    'SingleSignOnService'  =>  'https://localhost:9443/samlsso',
    'SingleLogoutService'  => 'https://localhost:9443/samlsso',
    'certFingerprint'      => '76794061128B742441515DA53F09138E65415422'
);

Сертификаты создаю так

openssl genrsa -out rootCA.key 2048
openssl req -x509 -new -key rootCA.key -days 10000 -out rootCA.crt
openssl genrsa -des3 -out private.key 2048
openssl req -new -key cert.key -out cert.csr
openssl x509 -req -in cert.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -out cert.crt -days 5000
cat cert.key cert.crt > cert.pem

certFingerprint получал так:
cat cert.crt | openssl x509 -fingerprint | grep SHA1 | sed «s/^[^=]*=//g» | sed «s/://g»

Пробовал с self signed сертификатами — ошибка такая же..

В процессе настройки смотрел по этим ссылкам
https://simplesamlphp.org/docs/1.5/simplesamlphp-i…
www.zeitoun.net/articles/configure-simplesaml-1.3-…
https://docs.wso2.com/display/IS530/Configuring+Si…

Mar 17 13:24:41 localhost simplesamlphp[12687]:
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] Failed to decrypt symmetric key: Failure decrypting Dataarray (#012)
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] Decryption failed: Failed to parse decrypted XML. Maybe the wrong sharedkey was used?array (#012)
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] SimpleSAML_Error_Error: UNHANDLEDEXCEPTION
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] Backtrace:
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] 0 /var/www/simplesamlphp/www/module.php:182 (N/A)
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] Caused by: Exception: Failed to decrypt XML element.
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] Backtrace:
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] 6 /var/www/simplesamlphp/vendor/simplesamlphp/saml2/src/SAML2/Utils.php:536 (SAML2_Utils::decryptElement)
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] 5 /var/www/simplesamlphp/vendor/simplesamlphp/saml2/src/SAML2/EncryptedAssertion.php:88 (SAML2_EncryptedAssertion::getAssertion)
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] 4 /var/www/simplesamlphp/modules/saml/lib/Message.php:371 (sspmod_saml_Message::decryptAssertion)
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] 3 /var/www/simplesamlphp/modules/saml/lib/Message.php:550 (sspmod_saml_Message::processAssertion)
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] 2 /var/www/simplesamlphp/modules/saml/lib/Message.php:524 (sspmod_saml_Message::processResponse)
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] 1 /var/www/simplesamlphp/modules/saml/www/sp/saml2-acs.php:120 (require)
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] 0 /var/www/simplesamlphp/www/module.php:139 (N/A)
Mar 17 13:24:41 localhost simplesamlphp[12687]: 3 [559911597e] Error report with id bd46e6bf generated.

Подскажите куда копать?

KAWAII BAAAKA
(talkcontribs)

HeyHelloThere

Similar problem like this one.

I configured SimpleSAMLphp with ADFS and it seemed to work. Then I installed the SimpleSAMLphp and PluggableAuth Addons on my Bluespice/Mediawiki installation.

I click the login button and get redirected to the adfs login site where I type in my credentials. Everything seemed to be working fine. There was a pop-up saying «Confirm Form Resubmission» which I accepted. When I input any incorrect credentials, nothing happens and I can type in the credentials again, but when I input my correct credentials, the problem occurs.

— The Problem

After I input my correct credentials I get redirected around 5x to something similar like the following Link…

https://adfs.domain.tld/adfs/ls/wia?SAMLRequest=(longString)RelayState=https:%3A%2F%2Fmywiki.domain.tld%2Fbluespice%2Findex.php%3Ftitle%3DSpezial%3APluggableAuthLogin&client-request-id=(id)&RedirectToIdentityProvider=AD+AUTHORITY

and end up on the wiki.domain.tld/simplesaml/module.php/saml/sp/saml2-acs.php/simpleSamlWiki site, which has the title «Unhandled exception» and this debug information.

Backtrace:

1 www_include.php:17 (SimpleSAML_exception_handler)

0 [builtin] (N/A)

Caused by: SimpleSAMLModulesamlError: Responder

Backtrace:

4 modulessamllibMessage.php:484 (SimpleSAMLModulesamlMessage::getResponseError)

3 modulessamllibMessage.php:616 (SimpleSAMLModulesamlMessage::processResponse)

2 modulessamlwwwspsaml2-acs.php:141 (require)

1 libSimpleSAMLModule.php:254 (SimpleSAMLModule::process)

0 wwwmodule.php:10 (N/A)

— Debugging

I did use the debugging feature like mentioned in the other post and found this ~5x when searching for «[PluggableAuth]» in the log:

[PluggableAuth] In execute()

[PluggableAuth] Getting PluggableAuth singleton

[PluggableAuth] Class name: SimpleSAMLphp

[DBQuery] DATABASE SELECT /* SqlBagOStuff::getMulti  */  keyname,value,exptime  FROM `objectcache`    WHERE keyname = ‘DATABASE:MWSession:47655a8898255aa47db42d8f46c545’  

[session] SessionBackend «47655a886e98255aa47db42d46c545» is unsaved, marking dirty in constructor


and when I searched for «SimpleSAML» found this ~5x:

Echo does not expose its version, but BlueSpiceEchoConnector mentions it with constraint ‘*’. Assume it’s ok so.

IP: <server IP>

Start request GET /bluespice/index.php?title=Spezial:PluggableAuthLogin

HTTP HEADERS:

CONTENT-TYPE:

CONTENT-LENGTH: 0

SEC-FETCH-MODE: navigate

SEC-FETCH-SITE: same-site

UPGRADE-INSECURE-REQUESTS: 1

USER-AGENT: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36

REFERER: https:://adfs.domain.tld/adfs/ls/?SAMLRequest=…(same as above)

HOST: wiki.domain.tld

COOKIE: restorewikidbnotificationFlag=1; restorewikidbCalumma_desktop-view=true; restorewikidb_session=70gt6u30ps58s7ddn28tc951igh42va; SimpleSAML=ef929c6ddcc726778505cef0265d14b; SimpleSAMLAuthToken=_da39836fffb36e83d278160a65c79da06dae2ed0a

ACCEPT-LANGUAGE: en-US,en;q=0.9

ACCEPT-ENCODING: gzip, deflate, br

ACCEPT: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9

CONNECTION: keep-alive

CACHE-CONTROL: max-age=0

[caches] cluster: EmptyBagOStuff, WAN: mediawiki-main-default, stash: db-replicated, message: SqlBagOStuff, session: SqlBagOStuff

[DBConnection] WikimediaRdbmsLoadBalancer::openConnection: calling initLB() before first connection.

[DBReplication] Cannot use ChronologyProtector with EmptyBagOStuff.


General info:

  • MediaWiki 1.31.5 (On Windows Server 2019)
  • Bluespice 3.1.1
  • PHP 7.4.0
  • SimpleSAMLphp 1.18.3
  • PluggableAuth Addon 5.4
  • SimpleSAMLphp Addon 4.1

Any help would be greatly appreciated!

Thank you

Osnard
(talkcontribs)

Hi! Have you set up a dedicated session storage for the «SimpleSAMLphp»-ServiceProvider-Application as described here: Extension:SimpleSAMLphp#Known_bugs?

KAWAII BAAAKA
(talkcontribs)

Hey!

Thanks for your reply. I have now set the session storage to sql and configured it accordingly.

The loop is now gone (hooray!), but I get the error «Could not find username attribute: uid».


Any ideas on how to fix this issue?


My LocalSettings config

wfLoadExtension( ‘PluggableAuth’ );

$wgPluggableAuth_EnableAutoLogin = false;

$wgPluggableAuth_EnableLocalLogin = false;

$wgPluggableAuth_EnableLocalProperties = true;

$wgPluggableAuth_Class = «SimpleSAMLphp»;


wfLoadExtension(‘SimpleSAMLphp’);

$wgSimpleSAMLphp_InstallDir = «C:inetpubsimplesamlphp»;

$wgSimpleSAMLphp_AuthSourceId = «simpleSamlWiki»;

$wgSimpleSAMLphp_RealNameAttribute = «givenName»;

$wgSimpleSAMLphp_EmailAttribute = «mail»;

$wgSimpleSAMLphp_UsernameAttribute = «uid»;


Errorlog

[PluggableAuth] In execute()

[PluggableAuth] Getting PluggableAuth singleton

[PluggableAuth] Class name: SimpleSAMLphp

[SimpleSAMLphp] Could not find username attribute: uid

[PluggableAuth] Authentication failure.

[PluggableAuth] ERROR: Could not find username attribute: uid

Osnard
(talkcontribs)

You can use the «admin» area of your SimpleSAMLphp Service Provider application to «test» the authentication process. After a successful authentication it will show all the attributes that were provided by the IdP. You need to find the name of the attribute that contains your username and configure it in $wgSimpleSAMLphp_UsernameAttribute.

KAWAII BAAAKA
(talkcontribs)

It’s working now, thank you so much for your help!  :)

In my previous two posts, I’ve discussed two solutions for using Azure Active Directory authentication from a bespoke PHP web application.

In the first post I essentially re-wrote an article that originally was written on the Azure website which unfortunately no longer seems valid (EDIT 07/2016: Has since been completely removed!). The solution written there used SimpleSAMLphp and libraries written by Microsoft to implement WS-Federation for authenticating custom PHP applications with Azure AD. My first post clears up some issues and demonstrates a more logical method of configuring SimpleSAMLphp on IIS.

In my second post, I showed a more elegant solution that did away with the Microsoft WS-Federation libraries and used only SimpleSAMLphp and SAML2 to authenticate a custom PHP application with Azure Active Directory. I also showed how you can configure an Azure application to pass through groups claims in the token.

In this third (and hopefully final) post, I’ll combine components of the two previous posts and demonstrate how you can use SimpleSAMLphp to integrate directly with ADFS 2012R2.

Pre-requisites

  • A working ADFS 2012R2 implementation.
    Apologies but this isn’t something I’ve blogged about yet (I will, soon). For now, there are plenty of fantastic articles on setting up ADFS out there but when you do it, make sure you’re setting up ADFS 2012R2 (It’s on Windows Server 2012R2 of course). Why am I telling you to set it up on Windows Server 2012R2? Simple, Alternate Login ID.
  • Access to a Linux box with an updated version of OpenSSL.
    OK, so strictly you don’t need a Linux box – it’s just easier if you have access to one. We need to generate a certificate and key for token signing purposes and fiddling with installations of OpenSSL on Windows isn’t something I want to document. Spin one up in Azure and bin it once you’re done with it!

Configure SimpleSAMLphp to use ADFS 2012R2 as an IdP

The first thing to do is configure SimpleSAMLphp with our ADFS server’s federation metadata. To do this, we must download the FederationMetadata.xml file from our ADFS server and use SimpleSAMLphp to convert it in to a format that it can understand.

  1. Firstly, I know my Federation Service is located at https://fs.transishun.co.uk/ but where’s the FederationMetadata.xml file? To get the location of the FederationMetadata.xml file: on your ADFS server open the ADFS Management console, expand Service and select the Endpoints node. The Metadata section shows us that the FederationMetadata.xml file is located at /FederationMetadata/2007-06/FederationMetadata.xml.
    This is actually the same location for all ADFS services but I wanted to show you where it was from.
  2. Open a browser and navigate to the FederationMetadata.xml location: https://fs.transishun.co.uk/FederationMetadata/2007-06/FederationMetadata.xml where you’ll be prompted to save the file to disk.
  3. Open the file and copy its contents to the clipboard.
  4. Browse to our web application’s installation of SimpleSAMLphp. Navigate to the Federation tab and click XML to simpleSAMLphp metadata converter
    NB: If you have no clue what I’m talking about, it would be a good idea to read through the two posts preceding this one where I explain how to install and configure SimpleSAMLphp

  5. Paste the contents of the FederationMetadata.xml file in to the XML metadata field and click the Parse button.
  6. The page will return two sets of data. For our purposes, the first: saml20-sp-remote can be ignored since we are not using SimpleSAMLphp as an identity provider, that’s ADFS’ job. Scroll to saml20-idp-remote and copy the contents of this field to the clipboard.
  7. Browse to the installation of SimpleSAMLphp on the IIS server and open the metadata folder.
    NB: Don’t know what I’m talking about or where this is? Please read the two posts preceding this one!
  8. Open the saml20-idp-remote.php file in your favourite text editor.
    Note: Did you notice the pattern? We copied the data from the saml20-idp-remote field of the converted metadata page and that is now going to be copied in to the PHP file of the same name.
  9. Paste the converted metadata at the bottom of the file then save it.

Create a service provider configuration in SimpleSAMLphp

  1. Navigate to your SimpleSAMLphp installation folder on the IIS server and open the config folder.
  2. Open authsources.php in your favourite text editor.
  3. I’m not going to repeat much of what I wrote in the post preceding this one where I added a Service Provider for Azure AD. Here, we will create a service provider configuration that uses our ADFS server. There are some differences in the configuration between Azure AD and ADFS 2012R2. The name of your SP is your choice, mine is called transishun-sp.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

        // An authentication source which can authenticate against both SAML 2.0

        // and Shibboleth 1.3 IdPs. If you make any configuration changes, you will need

    // to update the RPT at the IdP.

        ‘transishun-sp’ => array(

            ‘saml:SP’,

            // The entity ID of this SP.

            // Can be NULL/unset, in which case an entity ID is generated based on the metadata URL.

            ‘entityID’ => null,

            // The entity ID of the IdP this should SP should contact.

            // Can be NULL/unset, in which case the user will be shown a list of available IdPs.

    ‘idp’ => ‘http://fs.transishun.co.uk/adfs/services/trust’,

            // The URL to the discovery service.

            // Can be NULL/unset, in which case a builtin discovery service will be used.

            ‘discoURL’ => null,

    // ADFS 2012R2 requires signing of the logout — the others are optional (may be overhead you don’t want.)

    ‘sign.logout’ => TRUE,

    ‘redirect.sign’ => TRUE,

    ‘assertion.encryption’ => TRUE,

    // We now need a certificate and key. The following command (executed on Linux usually)

    // creates a self-signed cert and key, using SHA256, valid for 2 years.

    // openssl req -x509 -nodes -sha256 -days 730 -newkey rsa:2048 -keyout my.key -out my.pem

    ‘privatekey’ => ‘my.key’,

    ‘certificate’ => ‘my.pem’,

    // Enforce the use of SHA-256 by default.

    ‘signature.algorithm’ => ‘http://www.w3.org/2001/04/xmldsig-more#rsa-sha256’

        ),

  4. Here is how the code looks inside my authsources.php file.
  5. You will notice that the SP code defines that we must sign.logout, redirect.sign and assertion.encryption. All of these declarations mean we need a certificate and key to sign and encrypt these communications. We’ll create the certificate and key in the next section.
  6. The final declaration enforces the use of SHA-256 which is best practice.

Creating a certificate and key file for signing and encryption

I mentioned in the requirements that you would need a Linux machine. Again, if you need one, just spin one up on Azure, I did.

  1. Log on to your Linux machine. Use Putty to log on via SSH.
  2. Create a directory called cert and change in to it.
  3. If you recall from the SP definition code at the end of previous section, I provided an example command for generating a two year certificate and key:
    openssl req -x509 -nodes -sha256 -days 730 -newkey rsa:2048 -keyout my.key -out my.pem
    I extrapolated this from the documentation on the SimpleSAMLphp website in section 1.1. If you’re using this in a production environment, generate a key and cert that will last. The SimpleSAMLphp documentation suggests 10 years.
  4. Run the command to create the key and certificate. You will be asked a number of questions, answer these however you like, this cert and key is only used for signing and encrypting on the SP. My run through is shown below.
  5. Now you need to download the my.key and my.pem files. There’s a number of ways but since they’re just text, I usually just cat them to screen and copy/paste from the Putty console in to a file on my local machine.

    NB: Don’t get too excited, this is an example key, I don’t use this one myself.
  6. Navigate to the SimpleSAMLphp installation folder and create a folder called cert.
  7. Copy the my.key and my.pem files in to the cert folder. These are the two files that we declared when we created the Service Provider configuration in authsources.php. The cert folder is the default location for certs and keys in SimpleSAMLphp as mentioned in the documentation.

Create the Relying Party Trust in ADFS 2012R2

Now that the Service Provider configuration is complete, SimpleSAMLphp creates the SAML 2.0 SP metadata that we can use to import in to ADFS.

  1. Navigate to the web application’s /simplesaml application and click the Federation tab. As you can see, our previous default-sp configuration (the one we configured for use with Azure AD) is here, but now so is the one I’ve called transishun-sp. If you’re wondering where the heck that URL came from, it’s because we left the
    entityID  value
    null  when we specified the SP configuration.

    // The entity ID of this SP.

    // Can be NULL/unset, in which case an entity ID is generated based on the metadata URL.

    ‘entityID’ => null,

  2. If you wish, click the Show metadata link to see the metadata but before you do, copy the Entity ID: url. We need to give this to ADFS when we configure the Relying Party Trust.
  3. On your ADFS server, open the ADFS Management console, expand Trust Relationships and select the Relying Party Trusts node. In the Actions pane, click Add Relying Party Trust…
  4. Click Start then paste the Entity ID url in to the Federation Metadata address field and click Next.
  5. Accept the warning.
  6. Next your way through the wizard until you reach the Ready To Add Trust page. Here you’ll want to review the numerous tabs – check the Encryption and Signature tabs have certificates associated with them. Even if they don’t and you’ve not completed the previous section to create the certificates, the RPT can be updated whenever you like.
  7. Click Next and the sso.lewisroberts.com Relying Party Trust is added.
  8. Select the Relying Party Trust we’ve just added and then click Edit Claim Rules…
  9. Add an Issuance Transform Rule based on the Send LDAP Attributes as Claims template. Select at least UPN, whatever else you choose here is your choice but add another such as mail or uid.
  10. Add another Issuance Transform Rule but this time based on the Transform an Incoming Claim template. This one is important and is required to allow SimpleSAMLphp to talk with ADFS.
  11. Once configured, you should have two Issuance Transform Rules that look as follows:

Testing Authentication

Now that we have configured SimpleSAMLphp as the service provider, ADFS as the IdP, exchanged metadata between the two and configured some basic claims rules. We are now able to test authentication.

  1. Navigate to the simplesaml web application for our site https://sso.lewisroberts.com/simplesaml then select the Authentication tab and click Test configured authentication sources.
  2. Select transishun-sp from the list.
  3. You will be immediately sent off to the ADFS server (or Web Application Proxy depending on how your ADFS farm is configured). Enter your user ID in the format “domainuser” or “user@domain”.
    NB: Now, I’ve cheated slightly, I have enabled Alternate Login ID so I can sign in with my email address. If you see the article I’ve linked to, Microsoft strongly recommend using the mail attribute for sign in. As they say;
    One of the benefits of this feature is that it enables you to adopt SaaS providers, such as Office 365 with AAD without modifying your on-premise UPNs. It also enables you to support line-of-business service applications with consumer-provisioned identities.
  4. Once signed in, you’ll be bounced back to SimpleSAMLphp and shown your claims. If it all went a bit wobbly, double-check everything and then check the Event Viewer for hints as to what could have gone wrong.
  5. Click Logout to test this works as expected – this is where the sign.logout declaration in the Service Provider configuration becomes relevant. ADFS requires the logout to be signed.

    That looks as though it’s working.
  6. Let’s add another claim using the Send Group Membership as a Claim template just to get a little more understanding of what’s happening.
  7. After re-authenticating, we can see the group claim is sent through as well.

What about our custom PHP application?

Good job you asked, I nearly forgot.

In the previous blog post, I provided some code that I took from the SimpleSAMLphp website. On line 3 of that code when we created a new object, we specified the service provider we wanted to use. It looked like this:

$as = new SimpleSAML_Auth_Simple(‘default-sp’);

Not to be too cheeky but basically, we would simply change the service provider to, you guessed it, transishun-sp. After doing so, the whole file looks like this:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<?php

require_once (dirname(__FILE__) . ‘/../simplesamlphp/lib/_autoload.php’);

$as = new SimpleSAML_Auth_Simple(‘transishun-sp’);

$as>requireAuth();

$attributes = $as>getAttributes();

?>

<!DOCTYPE html>

<html>

<head>

    <meta httpequiv=«Content-Type» content=«text/html; charset=ISO-8859-1»>

    <title>Index Page</title>

</head>

<body>

    <h2>Index Page</h2>

    <h3>Welcome <strong>Authenticated User</strong>!</h3>

    <h4>Claim list:</h4>

<?php

echo ‘<pre>’;

print_r($attributes);

echo ‘</pre>’;

echo ‘<a href=»/logout.php»>Logout</a>’;

?>

</body>

</html>

After changing that, you can test your application and instead of being sent off to Azure AD for authentication, you’ll be sent to the federation service where, after logging on and being sent back to your application, you’ll see something like this – obviously changing depending on the claims you configured.

Hang on, I noticed in the index.php file that the logout link is different than the preceding post’s example. You’re right, it is – why? Well, if you left that Logout link in place, you will indeed be logged out but then you’ll be sent straight back to the application which will need you to log back in again and you’ll be sent off to sign in – not a great user experience.

To overcome this, we can send our user to a different page. It can be done using the
getLogoutURL()  function but if we wish to be certain the user was logged out, as per the SimpleSAMLphp documentation section 5.3, I would create two files: logout.php and logged_out.php with the following contents. What each file does should be pretty clear.

logout.php

<?php

require_once (dirname(__FILE__) . ‘/../simplesamlphp/lib/_autoload.php’);

$as = new SimpleSAML_Auth_Simple(‘transishun-sp’);

$as>logout(array(

    ‘ReturnTo’ => ‘https://sso.lewisroberts.com/logged_out.php’,

    ‘ReturnStateParam’ => ‘LogoutState’,

    ‘ReturnStateStage’ => ‘MyLogoutState’,

));

?>

logged_out.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

<?php

require_once (dirname(__FILE__) . ‘/../simplesamlphp/lib/_autoload.php’);

try {

if ($_REQUEST[‘LogoutState’]) {

$state = SimpleSAML_Auth_State::loadState((string)$_REQUEST[‘LogoutState’], ‘MyLogoutState’);

}

else {

echo «Were you logged in?»;

exit;

}

}

catch (Exception $e) {

echo ‘Caught exception: ‘,  $e>getMessage(), «n»;

exit;

}

$ls = $state[‘saml:sp:LogoutStatus’]; // Only works for SAML SP

if ($ls[‘Code’] === ‘urn:oasis:names:tc:SAML:2.0:status:Success’ && !isset($ls[‘SubCode’])) {

    // Successful logout.

    echo(«You have been logged out.»);

} else {

    // Logout failed. Tell the user to close the browser.

    echo(«We were unable to log you out of all your sessions. To be completely sure that you are logged out, you need to close your web browser.»);

}

?>

Well, that about wraps it up for another large post but hopefully there’s some useful information in there for you. If you’ve found the article helpful, you can say a quick thanks by clicking an advert. Don’t forget to read the two posts preceding this one to discover why I went down this rabbit hole and decided to take you all with me.

-Lewis

После просмотра всего Интернета, особенно

  • ADFS 2.0 InvalidNameIDPolcy
  • Использование SimpleSAMLphp для аутентификации против ADFS 2.0 IdP
  • Requester / InvalidNameIDPolicy

Я перепробовал все предложенные модификации в authsource.php и метаданных php. Ничего не получалось.

Вот мой authsource.php

'default-sp' => array(
'saml:SP',
'privatekey' => 'saml.pem',
'certificate' => 'saml.crt',
'idp' => 'http://domain.com/adfs/services/trust',

Я использовал XML to simpleSAMLphp metadata converter генерировать saml20-idp-remote.php

Поэтому, когда я захожу на страницу, SimpleSAMLPHP правильно перенаправляет меня на страницу входа в систему IDP. Я расшифровал запрос SAML:

<samlp:AuthnRequest
xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"ID="_4e03333c7aa76314d965e05f8fcdd3e1f4c5be96c8"Version="2.0"IssueInstant="2014-12-11T19:41:50Z"Destination="https://domain.com/adfs/ls/"AssertionConsumerServiceURL="https://sub.domain.com/simplesaml/module.php/saml/sp/saml2-acs.php/default-sp"ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST">

<saml:Issuer>
https://su.bdomain.com/simplesaml/module.php/saml/sp/metadata.php/default-sp
</saml:Issuer>
<samlp:NameIDPolicy Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient" AllowCreate="true"/>

</samlp:AuthnRequest>

После входа в систему с действительной тестовой учетной записью, я возвращаюсь на свой сайт с ошибкой.

SimpleSAML_Error_Error: UNHANDLEDEXCEPTION
Backtrace:
0 /var/www/html/igt_s3k/web/simplesamlphp/www/module.php:179 (N/A)
Caused by: sspmod_saml_Error: Requester/InvalidNameIDPolicy
Backtrace:
3 /var/www/html/igt_s3k/web/simplesamlphp/modules/saml/lib/Message.php:385 (sspmod_saml_Message::getResponseError)
2 /var/www/html/igt_s3k/web/simplesamlphp/modules/saml/lib/Message.php:495 (sspmod_saml_Message::processResponse)
1 /var/www/html/igt_s3k/web/simplesamlphp/modules/saml/www/sp/saml2-acs.php:96 (require)
0 /var/www/html/igt_s3k/web/simplesamlphp/www/module.php:134 (N/A)

Я пытался установить разные NameIDPolicy, но ни один из них не работал.

    //'NameIDFormat' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress',
//'NameIDPolicy' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient',
//'NameIDPolicy' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent',
//'NameIDPolicy' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified',

Спасибо!

8

Решение

Да уж. В порыве гнева и разочарования. Я установил NameIDPolicy на ноль, и все работает. FML

'default-sp' => array(
'saml:SP',
'privatekey' => 'saml.pem',
'certificate' => 'saml.crt',
'idp' => 'http://comain.com/adfs/services/trust',
'NameIDPolicy' => null,

18

Другие решения

Начиная с SimpleSAML v1.15.0, принятый ответ не поддерживается, и установка NameIDPolicy на ноль приведет к ошибке.

Если вы не установите NameIDPolicy, запрос SAML по умолчанию будет: urn:oasis:names:tc:SAML:2.0:nameid-format:transient, что может вызвать проблемы интеграции.

Чтобы явно не отправлять NameIDPolicy в запросе на аутентификацию, примените найденный патч Вот, и установите для NameIDPolicy значение false.

'NameIDPolicy' => false

3

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.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • 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.

  • Visualization

    Some thing interesting about visualization, use data art

  • 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.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Обновление:
В следующем абзаце предполагается, что при изменении кода, чтобы избежать циклического перенаправления, вы обязательно:

Настройка модуля аутентификации :**

В unix это можно сделать, выполнив (из
каталога установки SimpleSAMLphp):

touch modules/exampleauth/enable

Следующим шагом является создание источника аутентификации с помощью этого модуля.
Источник аутентификации — это модуль аутентификации с определенным
конфигурация. У каждого источника аутентификации есть имя, которое используется для
ссылки на эту конкретную конфигурацию в конфигурации IdP.
Конфигурацию источников аутентификации можно найти в
config/authsources.php .

В этой настройке этот файл должен содержать одну запись:

<?php
$config = array(
    'example-userpass' => array(
        'exampleauth:UserPass',
        'student:studentpass' => array(
            'uid' => array('student'),
            'eduPersonAffiliation' => array('member', 'student'),
        ),
        'employee:employeepass' => array(
            'uid' => array('employee'),
            'eduPersonAffiliation' => array('member', 'employee'),
        ),
    ),
);

Эта конфигурация создает двух пользователей — студента и сотрудника, с
паролями studentpass и employeepass. Имя пользователя и пароль
хранятся в индексе массива (студент: студенческий билет для студента-пользователя.
Атрибуты для каждого пользователя настраиваются в массиве, на который ссылается
индекс. Для пользователя-студента это:

array(
    'uid' => array('student'),
    'eduPersonAffiliation' => array('member', 'student'),
),

Атрибуты будут возвращены IdP при входе пользователя в систему.

Несоответствие между настройками сеанса PHP для приложения и SimpleSAMLphp

Если и приложение, в которое вы пытаетесь добавить поддержку SAML 2.0, и
SimpleSAMLphp используют сеанс PHP для хранения сеансов, и они не
согласны со всеми параметрами, вы можете столкнуться с этой ошибкой. По
умолчанию SimpleSAMLphp использует настройки из php.ini, но их можно
переопределить в config/config.php .

Если это является причиной вашей ошибки, у вас есть два варианта:

Затем No authentication source with id произошла ошибка из-за конфликта при обработке сеанса между SimpleSAMLphp и CodeIgniter.

Решение 1. измените SimpleSAMLphp, чтобы использовать другой метод хранения сеансов

В решение состоит в том, чтобы настроить SimpleSAMLphp на использование чего-то другого, кроме phpsession, так как существует проблема с Memcached. лучший способ — установить для него значение «sql». Вы делаете это в simplesamlphp/config/config.php :

/*
 * Configure the datastore for simpleSAMLphp.
 *
 * - 'phpsession': Limited datastore, which uses the PHP session.
 * - 'memcache': Key-value datastore, based on memcache.
 * - 'sql': SQL datastore, using PDO.
 *
 * The default datastore is 'phpsession'.
 *
 * (This option replaces the old 'session.handler'-option.)
 */
'store.type'                    => 'sql',

Решение 2. Измените настройки сеанса, чтобы они соответствовали приложению и SimpleSAMLphp:

Если вы решите привести настройки сеанса в соответствие, вам следует изменить настройки в php.ini. Это делается для того, чтобы убедиться, что настройки применяются ко всему, что использует настройки по умолчанию. Следующие параметры в php.ini должны соответствовать настройкам, используемым приложением:

  • session.save_handler: Это метод, который используется для хранения сеанса. Значение по умолчанию — «файлы».
  • session.save_path: Это расположение, в котором сохраняются файлы сеанса. Значение по умолчанию зависит от вашей установки PHP.
  • session.name : Это имя файла cookie сеанса. Значение по умолчанию — «PHPSESSID».
  • session.cookie_path: путь, которым ограничен файл cookie сеанса. По умолчанию используется «/», что означает, что он доступен для всех
    страниц вашего домена.
  • session.cookie_domain: Это домен, в котором ограничен файл cookie сеанса. Значение по умолчанию не установлено, что делает файл cookie доступным
    только для текущего домена.

Пожалуйста, ознакомьтесь с документами для получения дополнительной информации

Если это все еще не сработало, в качестве последнего средства : попробуйте отключить кэширование лаком

Источники:
https://github.com/zl4bv/CakePHP-simpleSAMLphp-Plugin/issues/7
https://www.drupal.org/project/simplesamlphp_auth

Понравилась статья? Поделить с друзьями:
  • Caused by org gradle api gradleexception compilation error see log for more details
  • Caused by java lang illegalargumentexception error at 0 formal unbound in pointcut
  • Caused by java io ioexception createprocess error 193 1 не является приложением win32
  • Cause error invalid source release 17
  • Cause error 86 bad cpu type in executable