Typo3:通过POST请求对接外部应用服务器实现前端登录
Hey there! Let's break down how to hook up your felogin with the app's API for authentication and data display—here's a step-by-step approach tailored to your TYPO3 setup:
felogin uses TYPO3's native FE user authentication by default, so we need to create a custom authentication service to talk to the app's API instead. Start by building a small custom extension (let's call it custom_app_auth for this example):
Register the Authentication Service
Add this to your extension's ext_localconf.php to register your custom auth provider:
$GLOBALS['TYPO3_CONF_VARS']['FE']['authServices'][1500] = [ 'name' => 'App API Authentication', 'provider' => \Vendor\CustomAppAuth\Authentication\AppApiAuthProvider::class, 'sorting' => 10, 'before' => [100], // Run this before TYPO3's default auth service ];
Build the Auth Provider Class
Create the AppApiAuthProvider.php file in your extension's Classes/Authentication directory. This class will handle sending credentials to the app's API and validating the response:
<?php namespace Vendor\CustomAppAuth\Authentication; use TYPO3\CMS\Core\Authentication\AbstractAuthenticationService; use TYPO3\CMS\Core\Http\RequestFactory; use TYPO3\CMS\Core\Utility\GeneralUtility; use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerAwareTrait; class AppApiAuthProvider extends AbstractAuthenticationService implements LoggerAwareInterface { use LoggerAwareTrait; public function authenticate(array $user): array { // Grab credentials from the felogin form $username = $this->login['uname'] ?? ''; $password = $this->login['uident'] ?? ''; if (empty($username) || empty($password)) { return ['status' => self::STATUS_NO_AUTH]; } // Call the app's POST API endpoint $requestFactory = GeneralUtility::makeInstance(RequestFactory::class); $apiUrl = 'https://domain.at/api/queryMediaItems'; $requestOptions = [ 'headers' => ['Content-Type' => 'application/json'], 'body' => json_encode([ 'user' => $username, 'pwd' => $password, 'language' => 'de-at' // Adjust to pull from FE language if needed ]), ]; try { $response = $requestFactory->request($apiUrl, 'POST', $requestOptions); $responseData = json_decode((string)$response->getBody(), true); // Validate API response (adjust this to match the app's actual success criteria) if ($response->getStatusCode() === 200 && isset($responseData['mediaItems'])) { // Create a dummy FE user record to persist the session $authenticatedUser = [ 'uid' => 9999 + crc32($username), // Unique ID for the session 'username' => $username, 'name' => $username, 'tx_customappauth_api_data' => json_encode($responseData), // Store API data in session ]; return [ 'status' => self::STATUS_AUTH_SUCCESS, 'user' => $authenticatedUser, ]; } } catch (\Exception $e) { $this->logger->error('App API authentication failed: ' . $e->getMessage()); } return ['status' => self::STATUS_AUTH_FAILURE]; } }
Now that we're storing the API response in the FE user session, we can pull it into your page template.
Add TypoScript to Fetch Session Data
Add this to your site package's setup.typoscript to make the API data available in Fluid:
lib.appMediaData = TEXT lib.appMediaData { data = TSFE:fe_user|user|tx_customappauth_api_data stdWrap.jsonDecode = 1 # Optional: Filter or sort data here if needed }
Update Your Page Template
Use Fluid to render the data in your restricted page's template:
<f:if condition="{f:cObject(typoscriptObjectPath: 'lib.appMediaData')}"> <div class="media-items-container"> <h2>Your Media Items</h2> <f:for each="{f:cObject(typoscriptObjectPath: 'lib.appMediaData').mediaItems}" as="item"> <div class="media-item"> <h3>{item.title}</h3> <p>{item.description}</p> <!-- Render other fields from the API response here --> </div> </f:for> </div> </f:if>
Ensure only authenticated users can access your page:
- Go to the page's properties → Access tab → Set "Page access" to Registered users
- Optional: Add this TypoScript to block unauthenticated users explicitly:
[loginUser = guest] page.config.additionalHeaders = HTTP/1.1 403 Forbidden page.config.sendCacheHeaders = 0 [global]
Felogin's default logout will destroy the session, but if you want to explicitly clear the stored API data, add a logout hook:
Register the Hook in ext_localconf.php
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'][] = \Vendor\CustomAppAuth\Hooks\LogoutHook::class . '::postProcessLogout';
Create the Logout Hook Class
<?php namespace Vendor\CustomAppAuth\Hooks; use TYPO3\CMS\Core\Authentication\AbstractUserAuthentication; class LogoutHook { public function postProcessLogout(AbstractUserAuthentication $userAuth): void { $userAuth->setAndSaveSessionData('tx_customappauth_api_data', null); } }
A quick note: Make sure to adjust the API response validation logic in the auth provider to match the actual success structure returned by the app's API—you might need to tweak checks like isset($responseData['success']) based on what the app sends back.
内容的提问来源于stack exchange,提问作者p.ott_plaspack

