라라벨 미들웨어란 무엇입니까?

青灯夜游
풀어 주다: 2023-01-13 00:40:23
원래의
3169명이 탐색했습니다.

미들웨어에는 1. 인증, 2. EncryptCookies, 4. RedirectIfAuthenticated, 6. TrustProxies 등이 포함됩니다.

라라벨 미들웨어란 무엇입니까?

이 튜토리얼의 운영 환경: Windows 7 시스템, Laravel 6 버전, Dell G3 컴퓨터.

Laravel 자체 미들웨어

Laravel에는 인증, CSRF 보호 등을 포함한 일부 미들웨어가 함께 제공됩니다. Laravel이 특별히 활성화한 미들웨어는 appHttpKernel.php 파일을 통해 확인할 수 있습니다. AppHttpMiddleware(app/Http/Middleware 디렉토리에 있음)로 시작하는 미들웨어의 경우 해당 동작을 사용자 정의할 수 있습니다.

미들웨어 인증

소스 파일: appHttpMiddlewareHttpMiddlewareAuthenticate.phpappHttpMiddlewareHttpMiddlewareAuthenticate.php

<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route(&#39;login&#39;);
        }
    }
}
로그인 후 복사

作用:

用户身份验证。可修改 redirectTo 方法,返回未经身份验证的用户应该重定向到的路径。

CheckForMaintenanceMode 中间件

源文件 :appHttpMiddlewareCheckForMaintenanceMode.php

<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
class CheckForMaintenanceMode extends Middleware
{
    /**
     * The URIs that should be reachable while maintenance mode is enabled.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}
로그인 후 복사

作用:

检测项目是否处于 维护模式。可通过 $except 数组属性设置在维护模式下仍能访问的网址。

EncryptCookies 中间件

源文件:appHttpMiddlewareEncryptCookies.php

<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
    /**
     * The names of the cookies that should not be encrypted.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}
로그인 후 복사

作用

对 Cookie 进行加解密处理与验证。可通过 $except 数组属性设置不做加密处理的 cookie。

RedirectIfAuthenticated 中间件

源文件:appHttpMiddlewareRedirectIfAuthenticated.php

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect(&#39;/home&#39;);
        }
        return $next($request);
    }
}
로그인 후 복사

作用:

当请求页是 注册、登录、忘记密码 时,检测用户是否已经登录,如果已经登录,那么就重定向到首页,如果没有就打开相应界面。可以在 handle 方法中定制重定向到的路径。

TrimStrings 中间件

源文件:appHttpMiddlewareTrimStrings.php

<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
    /**
     * The names of the attributes that should not be trimmed.
     *
     * @var array
     */
    protected $except = [
        &#39;password&#39;,
        &#39;password_confirmation&#39;,
    ];
}
로그인 후 복사

作用:

对请求参数内容进行 前后空白字符清理。可通过 $except 数组属性设置不做处理的参数。

TrustProxies 中间件

源文件:appHttpMiddlewareTrustProxies.php

<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array|string
     */
    protected $proxies;
    /**
     * The headers that should be used to detect proxies.
     *
     * @var int
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
로그인 후 복사

作用:

配置可信代理。可通过 $proxies 属性设置可信代理列表,$headers 属性设置用来检测代理的 HTTP 头字段。

VerifyCsrfToken 中间件

源文件:appHttpMiddlewareVerifyCsrfToken.php

<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
    /**
     * Indicates whether the XSRF-TOKEN cookie should be set on the response.
     *
     * @var bool
     */
    protected $addHttpCookie = true;
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}
로그인 후 복사
기능:

사용자 인증. 인증되지 않은 사용자를 리디렉션해야 하는 경로를 반환하도록 리디렉션To 메서드를 수정할 수 있습니다.

CheckForMaintenanceMode 미들웨어

소스 파일: appHttpMiddlewareCheckForMaintenanceMode.php

rrreee
기능: 🎜🎜프로젝트가 유지 관리 모드인지 감지합니다. 유지 관리 모드에서 계속 액세스할 수 있는 URL은 $just 배열 속성을 통해 설정할 수 있습니다. 🎜🎜🎜EncryptCookies 미들웨어🎜🎜🎜소스 파일: appHttpMiddlewareEncryptCookies.php🎜rrreee🎜Function🎜🎜쿠키를 암호화, 해독 및 확인합니다. 암호화되지 않은 쿠키는 $just 배열 속성을 통해 설정할 수 있습니다. 🎜🎜🎜RedirectIfAuthenticated 미들웨어🎜🎜🎜소스 파일: appHttpMiddlewareRedirectIfAuthenticated.php🎜rrreee🎜기능: 🎜🎜요청 페이지가 등록, 로그인, 비밀번호 분실인 경우 사용자가 로그인했는지 여부를 감지합니다. 사용자가 이미 로그인되어 있으면 홈페이지로 리디렉션하고, 그렇지 않은 경우 해당 인터페이스를 엽니다. 핸들 메소드에서 리디렉션 경로를 사용자 정의할 수 있습니다. 🎜🎜🎜TrimStrings middleware🎜🎜🎜소스 파일: appHttpMiddlewareTrimStrings.php🎜rrreee🎜Function: 🎜🎜요청 매개변수 콘텐츠의 공백 문자를 정리합니다. 처리되지 않는 매개변수는 $just 배열 속성을 통해 설정할 수 있습니다. 🎜🎜🎜TrustProxies 미들웨어🎜🎜🎜소스 파일: appHttpMiddlewareTrustProxies.php🎜rrreee🎜기능: 🎜🎜신뢰할 수 있는 프록시를 구성합니다. 신뢰할 수 있는 프록시 목록은 $proxies 속성을 통해 설정할 수 있으며 $headers 속성은 프록시를 감지하는 데 사용되는 HTTP 헤더 필드를 설정합니다. 🎜🎜🎜VerifyCsrfToken 미들웨어🎜🎜🎜소스 파일: appHttpMiddlewareVerifyCsrfToken.php🎜rrreee🎜Function: 🎜🎜요청의 토큰이 세션에 저장된 토큰과 일치하는지 확인하세요. CSRF 검증을 수행하지 않는 URL은 $just 배열 속성을 통해 설정할 수 있습니다. 🎜🎜🎜관련 추천: 🎜최신 5개의 Laravel 비디오 튜토리얼🎜🎜🎜

위 내용은 라라벨 미들웨어란 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!