Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions lib/AlternativeLogin/AlternativeLogin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\User_SAML\AlternativeLogin;

use OCP\Authentication\IAlternativeLogin;

class AlternativeLogin implements IAlternativeLogin {
public function __construct(
private readonly string $name,
private readonly string $href,
) {
}

#[\Override]
public function getLabel(): string {
return $this->name;
}

#[\Override]
public function getLink(): string {
return $this->href;
}

#[\Override]
public function getClass(): string {
return '';
}

#[\Override]
public function load(): void {
}
}
43 changes: 43 additions & 0 deletions lib/AlternativeLogin/AlternativeLoginProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\User_SAML\AlternativeLogin;

use OCA\User_SAML\Service\ProviderListingService;
use OCP\AppFramework\Services\IAppConfig;
use OCP\Authentication\IAlternativeLoginProvider;
use OCP\IRequest;
use OCP\IURLGenerator;

/**
* @psalm-suppress UndefinedClass IAlternativeLoginProvider is only defined in NC >= 34
*/
class AlternativeLoginProvider implements IAlternativeLoginProvider {
public function __construct(
private readonly IRequest $request,
private readonly IUrlGenerator $urlGenerator,
private readonly ProviderListingService $providerListingService,
private readonly IAppConfig $appConfig,
) {
}

#[\Override]
public function getAlternativeLogins(): array {
$type = $this->appConfig->getAppValueString('type');

if ($type !== 'saml') {
return [];
}

$redirectUrl = $this->request->getParam('redirect_url') ?? '';
$absoluteRedirectUrl = $this->urlGenerator->getAbsoluteURL($redirectUrl);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this code path, which leads to a later call to getIdps() then getSSOUrl() results in the absolute version of the redirecturl being duplicated. Symptoms reported on the community help forum: https://help.nextcloud.com/t/double-url-with-saml-app-azure-loginpage-wrong-redirect/247252

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in #1196

return array_map(fn (array $idp): AlternativeLogin
=> new AlternativeLogin($idp['display-name'], $idp['url']), $this->providerListingService->getIdps($absoluteRedirectUrl));
}
}
9 changes: 9 additions & 0 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use OC\User\LoginException;
use OC_User;
use OCA\DAV\Events\SabrePluginAddEvent;
use OCA\User_SAML\AlternativeLogin\AlternativeLoginProvider;
use OCA\User_SAML\DavPlugin;
use OCA\User_SAML\GroupBackend;
use OCA\User_SAML\Listener\CookieLoginEventListener;
Expand Down Expand Up @@ -68,6 +69,14 @@ public function register(IRegistrationContext $context): void {
$c->get(SAMLSettings::class),
$c->get(SessionService::class),
));

if (method_exists($context, 'registerAlternativeLoginProvider')) {
/**
* @psalm-suppress UndefinedInterfaceMethod
* @psalm-suppress MissingDependency
*/
$context->registerAlternativeLoginProvider(AlternativeLoginProvider::class);
}
}

#[\Override]
Expand Down
63 changes: 3 additions & 60 deletions lib/Controller/SAMLController.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
use Firebase\JWT\Key;
use OC\Core\Controller\ClientFlowLoginController;
use OC\Core\Controller\ClientFlowLoginV2Controller;
use OC\Security\CSRF\CsrfTokenManager;
use OCA\User_SAML\Attributes\OnlyUnauthenticatedUsers;
use OCA\User_SAML\Exceptions\NoUserFoundException;
use OCA\User_SAML\Exceptions\UserFilterViolationException;
use OCA\User_SAML\Helper\TXmlHelper;
use OCA\User_SAML\SAMLSettings;
use OCA\User_SAML\Service\ProviderListingService;
use OCA\User_SAML\Service\SessionService;
use OCA\User_SAML\UserBackend;
use OCA\User_SAML\UserData;
Expand All @@ -42,8 +42,6 @@
use OneLogin\Saml2\Error;
use OneLogin\Saml2\Settings;
use OneLogin\Saml2\ValidationError;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;

class SAMLController extends Controller {
Expand All @@ -66,6 +64,7 @@ public function __construct(
private ICrypto $crypto,
private ITrustedDomainHelper $trustedDomainHelper,
private SessionService $sessionService,
private ProviderListingService $providerListingService,
) {
parent::__construct($appName, $request);
}
Expand Down Expand Up @@ -591,68 +590,12 @@ public function selectUserBackEnd(string $redirectUrl = ''): Http\TemplateRespon
];
}

$attributes['loginUrls']['ssoLogin'] = $this->getIdps($redirectUrl);
$attributes['loginUrls']['ssoLogin'] = $this->providerListingService->getIdps($redirectUrl);
$attributes['useCombobox'] = count($attributes['loginUrls']['ssoLogin']) > 4;

return new Http\TemplateResponse($this->appName, 'selectUserBackEnd', $attributes, 'guest');
}

/**
* get the IdPs showed at the login page
*/
private function getIdps(string $redirectUrl): array {
$result = [];
$idps = $this->samlSettings->getListOfIdps();
foreach ($idps as $idpId => $displayName) {
$result[] = [
'url' => $this->getSSOUrl($redirectUrl, (string)$idpId),
'display-name' => $this->getSSODisplayName($displayName),
];
}

return $result;
}

/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws \OCP\DB\Exception
*/
private function getSSOUrl(string $redirectUrl, string $idp): string {
$originalUrl = '';
if (!empty($redirectUrl)) {
$originalUrl = $this->urlGenerator->getAbsoluteURL($redirectUrl);
}

/** @var CsrfTokenManager $csrfTokenManager */
$csrfTokenManager = Server::get(CsrfTokenManager::class);
$csrfToken = $csrfTokenManager->getToken();

$settings = $this->samlSettings->get((int)$idp);
$method = $settings['general-is_saml_request_using_post'] ?? 'get';

return $this->urlGenerator->linkToRouteAbsolute(
'user_saml.SAML.login',
[
'requesttoken' => $csrfToken->getEncryptedValue(),
'originalUrl' => $originalUrl,
'idp' => $idp,
'method' => $method,
]
);
}

/**
* Return the display name of the SSO identity provider.
*/
protected function getSSODisplayName(?string $displayName): string {
if ($displayName === null || $displayName === '') {
$displayName = $this->l->t('SSO & SAML log in');
}

return $displayName;
}

/**
* get Nextcloud login URL
*/
Expand Down
83 changes: 83 additions & 0 deletions lib/Service/ProviderListingService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\User_SAML\Service;

use OC\Security\CSRF\CsrfTokenManager;
use OCA\User_SAML\SAMLSettings;
use OCP\IL10N;
use OCP\IURLGenerator;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ProviderListingService {
public function __construct(
private readonly IL10N $l10n,
private readonly IUrlGenerator $urlGenerator,
private readonly SAMLSettings $samlSettings,
private readonly CsrfTokenManager $csrfTokenManager,
) {
}

/**
* Return the display name of the SSO identity provider.
*/
protected function getSSODisplayName(?string $displayName): string {
if ($displayName === null || $displayName === '') {
$displayName = $this->l10n->t('SSO & SAML log in');
}

return $displayName;
}

/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws \OCP\DB\Exception
*/
private function getSSOUrl(string $redirectUrl, int $idp): string {
$originalUrl = '';
if (!empty($redirectUrl)) {
$originalUrl = $this->urlGenerator->getAbsoluteURL($redirectUrl);
}

$csrfToken = $this->csrfTokenManager->getToken();

$settings = $this->samlSettings->get($idp);
$method = $settings['general-is_saml_request_using_post'] ?? 'get';

return $this->urlGenerator->linkToRouteAbsolute(
'user_saml.SAML.login',
[
'requesttoken' => $csrfToken->getEncryptedValue(),
'originalUrl' => $originalUrl,
'idp' => (string)$idp,
'method' => $method,
]
);
}

/**
* Get the IdPs showed at the login page
*
* @return list<array{url: string, display-name: string}>
*/
public function getIdps(string $redirectUrl): array {
$result = [];
$idps = $this->samlSettings->getListOfIdps();
foreach ($idps as $idpId => $displayName) {
$result[] = [
'url' => $this->getSSOUrl($redirectUrl, $idpId),
'display-name' => $this->getSSODisplayName($displayName),
];
}

return $result;
}
}
2 changes: 1 addition & 1 deletion psalm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
errorBaseline="tests/psalm-baseline.xml"
findUnusedBaselineEntry="true"
findUnusedBaselineEntry="false"
findUnusedCode="false"
phpVersion="8.1"
>
Expand Down
5 changes: 5 additions & 0 deletions tests/psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
- SPDX-License-Identifier: AGPL-3.0-or-later
-->
<files psalm-version="6.16.1@f1f5de594dc76faf8784e02d3dc4716c91c6f6ac">
<file src="lib/AlternativeLogin/AlternativeLoginProvider.php">
<UndefinedClass>
<code><![CDATA[IAlternativeLoginProvider]]></code>
</UndefinedClass>
</file>
<file src="lib/UserBackend.php">
<DeprecatedInterface>
<code><![CDATA[UserBackend]]></code>
Expand Down
18 changes: 5 additions & 13 deletions tests/unit/Controller/SAMLControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use OCA\User_SAML\Exceptions\NoUserFoundException;
use OCA\User_SAML\Exceptions\UserFilterViolationException;
use OCA\User_SAML\SAMLSettings;
use OCA\User_SAML\Service\ProviderListingService;
use OCA\User_SAML\Service\SessionService;
use OCA\User_SAML\UserBackend;
use OCA\User_SAML\UserData;
Expand Down Expand Up @@ -51,6 +52,7 @@ class SAMLControllerTest extends TestCase {
private SAMLController $samlController;
private ITrustedDomainHelper|MockObject $trustedDomainController;
private SessionService|MockObject $sessionService;
private ProviderListingService|MockObject $providerListingService;

#[Override]
protected function setUp(): void {
Expand All @@ -71,6 +73,7 @@ protected function setUp(): void {
$this->crypto = $this->createMock(ICrypto::class);
$this->trustedDomainController = $this->createMock(ITrustedDomainHelper::class);
$this->sessionService = $this->createMock(SessionService::class);
$this->providerListingService = $this->createMock(ProviderListingService::class);

$this->l->expects($this->any())->method('t')->willReturnCallback(
static fn (string $param): string => $param
Expand All @@ -95,7 +98,8 @@ protected function setUp(): void {
$this->userData,
$this->crypto,
$this->trustedDomainController,
$this->sessionService
$this->sessionService,
$this->providerListingService,
);
}

Expand Down Expand Up @@ -331,18 +335,6 @@ public static function dataTestGenericError(): \Generator {
yield ['messageSend' => 'authFailed', 'messageExpected' => 'Authentication failed.'];
}

#[DataProvider('dataTestGetSSODisplayName')]
public function testGetSSODisplayName(string $configuredDisplayName, string $expected): void {
$result = $this->invokePrivate($this->samlController, 'getSSODisplayName', [$configuredDisplayName]);

$this->assertSame($expected, $result);
}

public static function dataTestGetSSODisplayName(): \Generator {
yield ['My identity provider', 'My identity provider'];
yield ['', 'SSO & SAML log in'];
}

public static function userFilterDataProvider(): array {
return [
[ // 0 - test rejection by membership
Expand Down
Loading
Loading