first commit

This commit is contained in:
2025-07-18 16:20:14 +07:00
commit 98af45c018
16382 changed files with 3148096 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
---
exampleauth-authpage:
path: /authpage
defaults: {
_controller: 'SimpleSAML\Module\exampleauth\Controller\ExampleAuth::authpage'
}
methods: [GET, POST]
exampleauth-redirecttest:
path: /redirecttest
defaults: {
_controller: 'SimpleSAML\Module\exampleauth\Controller\ExampleAuth::redirecttest'
}
methods: [GET]
exampleauth-resume:
path: /resume
defaults: {
_controller: 'SimpleSAML\Module\exampleauth\Controller\ExampleAuth::resume'
}
methods: [GET]

View File

@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\exampleauth\Auth\Process;
use SimpleSAML\Assert\Assert;
use SimpleSAML\Auth;
use SimpleSAML\Module;
use SimpleSAML\Utils;
/**
* A simple processing filter for testing that redirection works as it should.
*
*/
class RedirectTest extends Auth\ProcessingFilter
{
/**
* Initialize processing of the redirect test.
*
* @param array &$state The state we should update.
*/
public function process(array &$state): void
{
Assert::keyExists($state, 'Attributes');
// To check whether the state is saved correctly
$state['Attributes']['RedirectTest1'] = ['OK'];
// Save state and redirect
$id = Auth\State::saveState($state, 'exampleauth:redirectfilter-test');
$url = Module::getModuleURL('exampleauth/redirecttest');
$httpUtils = new Utils\HTTP();
$httpUtils->redirectTrustedURL($url, ['StateId' => $id]);
}
}

View File

@@ -0,0 +1,281 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\exampleauth\Auth\Source;
use SimpleSAML\Assert\Assert;
use SimpleSAML\Auth;
use SimpleSAML\Error;
use SimpleSAML\Module;
use SimpleSAML\Utils;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session as SymfonySession;
/**
* Example external authentication source.
*
* This class is an example authentication source which is designed to
* hook into an external authentication system.
*
* To adapt this to your own web site, you should:
* 1. Create your own module directory.
* 2. Enable to module in the config by adding '<module-dir>' => true to the $config['module.enable'] array.
* 3. Copy this file to its corresponding location in the new module.
* 4. Replace all occurrences of "exampleauth" in this file with the name of your module.
* 5. Adapt the getUser()-function, the authenticate()-function and the logout()-function to your site.
* 6. Add an entry in config/authsources.php referencing your module. E.g.:
* 'myauth' => [
* '<mymodule>:External',
* ],
*
* @package SimpleSAMLphp
*/
class External extends Auth\Source
{
/**
* The key of the AuthId field in the state.
*/
public const AUTHID = 'SimpleSAML\Module\exampleauth\Auth\Source\External.AuthId';
/**
* Constructor for this authentication source.
*
* @param array $info Information about this authentication source.
* @param array $config Configuration.
*/
public function __construct(array $info, array $config)
{
// Call the parent constructor first, as required by the interface
parent::__construct($info, $config);
// Do any other configuration we need here
}
/**
* Retrieve attributes for the user.
*
* @return array|null The user's attributes, or NULL if the user isn't authenticated.
*/
private function getUser(): ?array
{
/*
* In this example we assume that the attributes are
* stored in the users PHP session, but this could be replaced
* with anything.
*/
$session = new SymfonySession();
if (!$session->getId()) {
$session->start();
}
if (!$session->has('uid')) {
// The user isn't authenticated
return null;
}
/*
* Find the attributes for the user.
* Note that all attributes in SimpleSAMLphp are multivalued, so we need
* to store them as arrays.
*/
$attributes = [
'uid' => [$session->get('uid')],
'displayName' => [$session->get('name')],
'mail' => [$session->get('mail')],
];
// Here we generate a multivalued attribute based on the account type
$attributes['eduPersonAffiliation'] = [
$session->get('type'), /* In this example, either 'student' or 'employee'. */
'member',
];
return $attributes;
}
/**
* Log in using an external authentication helper.
*
* @param array &$state Information about the current authentication.
*/
public function authenticate(array &$state): void
{
$attributes = $this->getUser();
if ($attributes !== null) {
/*
* The user is already authenticated.
*
* Add the users attributes to the $state-array, and return control
* to the authentication process.
*/
$state['Attributes'] = $attributes;
return;
}
/*
* The user isn't authenticated. We therefore need to
* send the user to the login page.
*/
/*
* First we add the identifier of this authentication source
* to the state array, so that we know where to resume.
*/
$state['exampleauth:AuthID'] = $this->authId;
/*
* We need to save the $state-array, so that we can resume the
* login process after authentication.
*
* Note the second parameter to the saveState-function. This is a
* unique identifier for where the state was saved, and must be used
* again when we retrieve the state.
*
* The reason for it is to prevent
* attacks where the user takes a $state-array saved in one location
* and restores it in another location, and thus bypasses steps in
* the authentication process.
*/
$stateId = Auth\State::saveState($state, 'exampleauth:External');
/*
* Now we generate a URL the user should return to after authentication.
* We assume that whatever authentication page we send the user to has an
* option to return the user to a specific page afterwards.
*/
$returnTo = Module::getModuleURL('exampleauth/resume', [
'State' => $stateId,
]);
/*
* Get the URL of the authentication page.
*
* Here we use the getModuleURL function again, since the authentication page
* is also part of this module, but in a real example, this would likely be
* the absolute URL of the login page for the site.
*/
$authPage = Module::getModuleURL('exampleauth/authpage');
/*
* The redirect to the authentication page.
*
* Note the 'ReturnTo' parameter. This must most likely be replaced with
* the real name of the parameter for the login page.
*/
$httpUtils = new Utils\HTTP();
$httpUtils->redirectTrustedURL($authPage, [
'ReturnTo' => $returnTo,
]);
/*
* The redirect function never returns, so we never get this far.
*/
Assert::true(false);
}
/**
* Resume authentication process.
*
* This function resumes the authentication process after the user has
* entered his or her credentials.
*
* @param \Symfony\Component\HttpFoundation\Request $request
*
* @throws \SimpleSAML\Error\BadRequest
* @throws \SimpleSAML\Error\Exception
*/
public static function resume(Request $request): void
{
/*
* First we need to restore the $state-array. We should have the identifier for
* it in the 'State' request parameter.
*/
if (!$request->query->has('State')) {
throw new Error\BadRequest('Missing "State" parameter.');
}
/*
* Once again, note the second parameter to the loadState function. This must
* match the string we used in the saveState-call above.
*/
$state = Auth\State::loadState($request->query->get('State'), 'exampleauth:External');
/*
* Now we have the $state-array, and can use it to locate the authentication
* source.
*/
$source = Auth\Source::getById($state['exampleauth:AuthID']);
if ($source === null) {
/*
* The only way this should fail is if we remove or rename the authentication source
* while the user is at the login page.
*/
throw new Error\Exception('Could not find authentication source with id ' . $state[self::AUTHID]);
}
/*
* Make sure that we haven't switched the source type while the
* user was at the authentication page. This can only happen if we
* change config/authsources.php while an user is logging in.
*/
if (!($source instanceof self)) {
throw new Error\Exception('Authentication source type changed.');
}
/*
* OK, now we know that our current state is sane. Time to actually log the user in.
*
* First we check that the user is actually logged in, and didn't simply skip the login page.
*/
$attributes = $source->getUser();
if ($attributes === null) {
/*
* The user isn't authenticated.
*
* Here we simply throw an exception, but we could also redirect the user back to the
* login page.
*/
throw new Error\Exception('User not authenticated after login page.');
}
/*
* So, we have a valid user. Time to resume the authentication process where we
* paused it in the authenticate()-function above.
*/
$state['Attributes'] = $attributes;
Auth\Source::completeAuth($state);
/*
* The completeAuth-function never returns, so we never get this far.
*/
Assert::true(false);
}
/**
* This function is called when the user start a logout operation, for example
* by logging out of a SP that supports single logout.
*
* @param array &$state The logout state array.
*/
public function logout(array &$state): void
{
$session = new SymfonySession();
if (!$session->getId()) {
$session->start();
}
$session->clear();
/*
* If we need to do a redirect to a different page, we could do this
* here, but in this example we don't need to do this.
*/
}
}

View File

@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\exampleauth\Auth\Source;
use Exception;
use SimpleSAML\Auth;
use SimpleSAML\Utils;
/**
* Example authentication source.
*
* This class is an example authentication source which will always return a user with
* a static set of attributes.
*
* @package SimpleSAMLphp
*/
class StaticSource extends Auth\Source
{
/**
* The attributes we return.
* @var array
*/
private array $attributes;
/**
* Constructor for this authentication source.
*
* @param array $info Information about this authentication source.
* @param array $config Configuration.
*/
public function __construct(array $info, array $config)
{
// Call the parent constructor first, as required by the interface
parent::__construct($info, $config);
$attrUtils = new Utils\Attributes();
// Parse attributes
try {
$this->attributes = $attrUtils->normalizeAttributesArray($config);
} catch (Exception $e) {
throw new Exception('Invalid attributes for authentication source ' .
$this->authId . ': ' . $e->getMessage());
}
}
/**
* Log in using static attributes.
*
* @param array &$state Information about the current authentication.
*/
public function authenticate(array &$state): void
{
$state['Attributes'] = $this->attributes;
}
}

View File

@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\exampleauth\Auth\Source;
use Exception;
use SimpleSAML\Error;
use SimpleSAML\Logger;
use SimpleSAML\Module\core\Auth\UserPassBase;
use SimpleSAML\Utils;
/**
* Example authentication source - username & password.
*
* This class is an example authentication source which stores all username/passwords in an array,
* and authenticates users against this array.
*
* @package SimpleSAMLphp
*/
class UserPass extends UserPassBase
{
/**
* Our users, stored in an associative array. The key of the array is "<username>:<password>",
* while the value of each element is a new array with the attributes for each user.
*
* @var array
*/
private array $users;
/**
* Constructor for this authentication source.
*
* @param array $info Information about this authentication source.
* @param array $config Configuration.
*/
public function __construct(array $info, array $config)
{
// Call the parent constructor first, as required by the interface
parent::__construct($info, $config);
$this->users = [];
// Old version of SimpleSAMLphp had the username:password just be a list in the top level
// configuration. We now have them under the "users" key, so that exampleauth can be used
// for testing things like core:loginpage_links, etc. that require top level configuration.
if (array_key_exists('users', $config)) {
$config_users = $config['users'];
} else {
Logger::warning("Module exampleauth:UserPass configured in legacy mode. Please put your " .
"username:password entries under the \"users\" key in your authsource.");
$config_users = $config;
}
// Validate and parse our configuration
foreach ($config_users as $userpass => $attributes) {
if (!is_string($userpass)) {
throw new Exception(
'Invalid <username>:<password> for authentication source ' . $this->authId . ': ' . $userpass,
);
}
$userpass = explode(':', $userpass, 2);
if (count($userpass) !== 2) {
throw new Exception(
'Invalid <username>:<password> for authentication source ' . $this->authId . ': ' . $userpass[0],
);
}
$username = $userpass[0];
$password = $userpass[1];
$attrUtils = new Utils\Attributes();
try {
$attributes = $attrUtils->normalizeAttributesArray($attributes);
} catch (Exception $e) {
throw new Exception('Invalid attributes for user ' . $username .
' in authentication source ' . $this->authId . ': ' . $e->getMessage());
}
$this->users[$username . ':' . $password] = $attributes;
}
}
/**
* Attempt to log in using the given username and password.
*
* On a successful login, this function should return the users attributes. On failure,
* it should throw an exception. If the error was caused by the user entering the wrong
* username or password, a \SimpleSAML\Error\Error(\SimpleSAML\Error\ErrorCodes::WRONGUSERPASS) should be thrown.
*
* Note that both the username and the password are UTF-8 encoded.
*
* @param string $username The username the user wrote.
* @param string $password The password the user wrote.
* @return array Associative array with the users attributes.
*/
protected function login(string $username, string $password): array
{
$userpass = $username . ':' . $password;
if (!array_key_exists($userpass, $this->users)) {
throw new Error\Error(Error\ErrorCodes::WRONGUSERPASS);
}
return $this->users[$userpass];
}
}

View File

@@ -0,0 +1,201 @@
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\exampleauth\Controller;
use SimpleSAML\Auth;
use SimpleSAML\Configuration;
use SimpleSAML\Error;
use SimpleSAML\HTTP\RunnableResponse;
use SimpleSAML\Module\exampleauth\Auth\Source\External;
use SimpleSAML\Session;
use SimpleSAML\Utils;
use SimpleSAML\XHTML\Template;
use Symfony\Component\HttpFoundation\{Request, Response};
use Symfony\Component\HttpFoundation\Session\Session as SymfonySession;
use function preg_match;
use function urldecode;
/**
* Controller class for the exampleauth module.
*
* This class serves the different views available in the module.
*
* @package simplesamlphp/simplesamlphp
*/
class ExampleAuth
{
/**
* @var \SimpleSAML\Auth\State|string
* @psalm-var \SimpleSAML\Auth\State|class-string
*/
protected $authState = Auth\State::class;
/**
* Controller constructor.
*
* It initializes the global configuration and session for the controllers implemented here.
*
* @param \SimpleSAML\Configuration $config The configuration to use by the controllers.
* @param \SimpleSAML\Session $session The session to use by the controllers.
*
* @throws \Exception
*/
public function __construct(
protected Configuration $config,
protected Session $session,
) {
}
/**
* Inject the \SimpleSAML\Auth\State dependency.
*
* @param \SimpleSAML\Auth\State $authState
*/
public function setAuthState(Auth\State $authState): void
{
$this->authState = $authState;
}
/**
* Auth testpage.
*
* @param \Symfony\Component\HttpFoundation\Request $request The current request.
*
* @return \SimpleSAML\XHTML\Template|\SimpleSAML\HTTP\RunnableResponse
*/
public function authpage(Request $request): Response
{
/**
* This page serves as a dummy login page.
*
* Note that we don't actually validate the user in this example. This page
* just serves to make the example work out of the box.
*/
$returnTo = $request->get('ReturnTo');
if ($returnTo === null) {
throw new Error\Exception('Missing ReturnTo parameter.');
}
$httpUtils = new Utils\HTTP();
$returnTo = $httpUtils->checkURLAllowed($returnTo);
/**
* The following piece of code would never be found in a real authentication page. Its
* purpose in this example is to make this example safer in the case where the
* administrator of the IdP leaves the exampleauth-module enabled in a production
* environment.
*
* What we do here is to extract the $state-array identifier, and check that it belongs to
* the exampleauth:External process.
*/
if (!preg_match('@State=(.*)@', $returnTo, $matches)) {
throw new Error\Exception('Invalid ReturnTo URL for this example.');
}
/**
* The loadState-function will not return if the second parameter does not
* match the parameter passed to saveState, so by now we know that we arrived here
* through the exampleauth:External authentication page.
*/
$this->authState::loadState(urldecode($matches[1]), 'exampleauth:External');
// our list of users.
$users = [
'student' => [
'password' => 'student',
'uid' => 'student',
'name' => 'Student Name',
'mail' => 'somestudent@example.org',
'type' => 'student',
],
'admin' => [
'password' => 'admin',
'uid' => 'admin',
'name' => 'Admin Name',
'mail' => 'someadmin@example.org',
'type' => 'employee',
],
];
// time to handle login responses; since this is a dummy example, we accept any data
$badUserPass = false;
if ($request->getMethod() === 'POST') {
$username = $request->request->get('username');
$password = $request->request->get('password');
if (!isset($users[$username]) || $users[$username]['password'] !== $password) {
$badUserPass = true;
} else {
$user = $users[$username];
$session = new SymfonySession();
if (!$session->getId()) {
$session->start();
}
$session->set('uid', $user['uid']);
$session->set('name', $user['name']);
$session->set('mail', $user['mail']);
$session->set('type', $user['type']);
return new RunnableResponse([$httpUtils, 'redirectTrustedURL'], [$returnTo]);
}
}
// if we get this far, we need to show the login page to the user
$t = new Template($this->config, 'exampleauth:authenticate.twig');
$t->data['badUserPass'] = $badUserPass;
$t->data['returnTo'] = $returnTo;
return $t;
}
/**
* Redirect testpage.
*
* @param \Symfony\Component\HttpFoundation\Request $request The current request.
*
* @return \SimpleSAML\HTTP\RunnableResponse
*/
public function redirecttest(Request $request): RunnableResponse
{
/**
* Request handler for redirect filter test.
*/
$stateId = $request->query->get('StateId');
if ($stateId === null) {
throw new Error\BadRequest('Missing required StateId query parameter.');
}
$state = $this->authState::loadState($stateId, 'exampleauth:redirectfilter-test');
$state['Attributes']['RedirectTest2'] = ['OK'];
return new RunnableResponse([Auth\ProcessingChain::class, 'resumeProcessing'], [$state]);
}
/**
* Resume testpage.
*
* @param \Symfony\Component\HttpFoundation\Request $request The current request.
*
* @return \SimpleSAML\HTTP\RunnableResponse
*/
public function resume(Request $request): RunnableResponse
{
/**
* This page serves as the point where the user's authentication
* process is resumed after the login page.
*
* It simply passes control back to the class.
*/
return new RunnableResponse([External::class, 'resume'], [$request]);
}
}

View File

@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>exampleauth login page</title>
</head>
<body>
<h1>exampleauth login page</h1>
<p>
In this example you can log in with two accounts: <code>student</code> and <code>admin</code>.
In both cases, the password is the same as the username.
</p>
<form method="post" action="?">
<p>
Username:
<input type="text" name="username">
</p>
<p>
Password:
<input type="text" name="password">
</p>
<input type="hidden" name="ReturnTo" value="{{ returnTo|escape('html') }}">
<p><input type="submit" value="Log in"></p>
</form>
{% if badUserPass == true %}
<p>!!! Bad username or password !!!</p>
{% endif %}
</body>
</html>