Home > Backend Development > PHP Tutorial > Zend Framework middleware: Adds OAuth and OpenID login support to applications

Zend Framework middleware: Adds OAuth and OpenID login support to applications

WBOY
Release: 2023-07-28 13:40:01
Original
953 people have browsed it

Zend Framework Middleware: Add OAuth and OpenID login support to applications

User authentication is a critical feature in today's Internet applications. In order to provide better user experience and security, many applications choose to integrate third-party login services, such as OAuth and OpenID. In Zend Framework, we can easily add OAuth and OpenID login support to applications through middleware.

First, we need to install the OAuth and OpenID modules of Zend Framework. They can be installed through Composer:

composer require zendframework/zend-oauth
composer require zendframework/zend-openid
Copy after login

After completing the installation, we can start writing middleware to handle user authentication.

First, we create a middleware class named AuthMiddleware:

use PsrHttpMessageRequestInterface;
use PsrHttpMessageResponseInterface;
use ZendDiactorosResponseRedirectResponse;
use ZendStratigilityMiddlewareInterface;
use ZendAuthenticationAuthenticationService;

class AuthMiddleware implements MiddlewareInterface
{
    private $authService;
    
    public function __construct(AuthenticationService $authService)
    {
        $this->authService = $authService;
    }
    
    public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next = null) : ResponseInterface
    {
        // 检查用户是否已认证
        if ($this->authService->hasIdentity()) {
            // 用户已认证,继续请求处理
            return $next($request, $response);
        }
        
        // 用户未认证,重定向到登录页面
        return new RedirectResponse('/login');
    }
}
Copy after login

In this middleware class, we use the AuthenticationService component of Zend Framework to check whether the user has been authenticated. If the user has been authenticated, we continue request processing; otherwise, jump to the login page.

Next step, we create a middleware class called LoginMiddleware to handle user login logic:

use PsrHttpMessageRequestInterface;
use PsrHttpMessageResponseInterface;
use ZendDiactorosResponseHtmlResponse;
use ZendStratigilityMiddlewareInterface;
use ZendAuthenticationAuthenticationService;
use ZendAuthenticationAdapterOpenId as OpenIdAdapter;

class LoginMiddleware implements MiddlewareInterface
{
    private $authService;
    
    public function __construct(AuthenticationService $authService)
    {
        $this->authService = $authService;
    }
    
    public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next = null) : ResponseInterface
    {
        if ($request->getMethod() === 'POST') {
            // 处理登录表单提交
            $identity = $request->getParsedBody()['identity'];
            $credential = $request->getParsedBody()['credential'];
            
            // 使用OpenID适配器进行认证
            $adapter = new OpenIdAdapter();
            $adapter->setIdentity($identity);
            $adapter->setCredential($credential);
            
            // 进行认证
            $result = $this->authService->authenticate($adapter);
            
            if ($result->isValid()) {
                // 认证成功,存储用户身份信息
                $this->authService->getStorage()->write($result->getIdentity());
                
                // 记录用户登录成功的日志
                // ...
                
                // 重定向到首页
                return new RedirectResponse('/');
            }
            
            // 认证失败,返回登录页面并显示错误信息
            return new HtmlResponse($this->renderLoginForm(['error' => '用户名或密码错误']));
        }
        
        // 显示登录页面
        return new HtmlResponse($this->renderLoginForm());
    }
    
    private function renderLoginForm(array $params = []) : string
    {
        // 渲染登录表单模板,可使用Twig等模板引擎
        // ...
    }
}
Copy after login

In this middleware class, we use Zend Framework’s OpenIdAdapter. User Authentication. After successful authentication, we store the user identity information and can perform some additional operations, such as recording a log of successful user login.

Finally, we add these middlewares to the Zend Framework application:

use ZendStratigilityMiddlewarePipe;
use ZendAuthenticationAuthenticationService;
use ZendDiactorosServerRequestFactory;

// 创建Zend Framework应用程序实例
$app = new MiddlewarePipe();

// 创建AuthenticationService实例
$authService = new AuthenticationService();

// 添加OAuth和OpenID登录中间件
$app->pipe(new AuthMiddleware($authService));
$app->pipe(new LoginMiddleware($authService));

// 处理请求
$response = $app(ServerRequestFactory::fromGlobals(), new Response());

// 发送响应
$responseEmitter = new ResponseSapiEmitter();
$responseEmitter->emit($response);
Copy after login

In the above code, we create a MiddlewarePipe instance and add the AuthMiddleware and LoginMiddleware middleware. We then use Zend Framework's ServerRequestFactory to create a request instance and run the application by processing the request and sending a response.

Through the above steps, we successfully added OAuth and OpenID login support to the application. Users can now use third-party login services to authenticate and gain better user experience and security.

The above example is just a simple demonstration, and there may be more customization and integration operations in actual use. However, with the flexibility and ease of use of Zend Framework middleware, we can easily accomplish these operations and add various features to the application.

Middleware is one of the powerful features in Zend Framework, which provides a concise and extensible way to handle HTTP requests and responses. Whether it is authentication, authorization, logging or other functions, middleware can help us handle it quickly and flexibly. If your application requires user authentication, try using middleware to add OAuth and OpenID login support!

The above is the detailed content of Zend Framework middleware: Adds OAuth and OpenID login support to applications. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template