Laravel의 IP 주소에서 사용자 액세스를 제한하는 방법

이 튜토리얼은 Laravel에서 IP 주소를 기반으로 사용자 액세스를 제한하는 방법을 보여줍니다. IP 주소의 기초와 Laravel의 내장 미들웨어를 사용하여 IP 주소를 기반으로 특정 사용자에 대한 액세스를 차단하거나 허용하는 방법을 배우게 됩니다. 미들웨어 설정 프로세스, 특정 요구 사항에 맞게 구성하는 방법 및 테스트 방법을 안내합니다. 자습서가 끝나면 IP 주소를 기반으로 사용자 액세스를 효과적으로 제한하는 방법을 완전히 이해하여 웹 응용 프로그램에 추가 보안 계층을 추가할 수 있습니다.

이 튜토리얼에서는 하나의 미들웨어를 로 생성하고 BlockIpMiddleware모든 보안 API 및 URL에서 해당 미들웨어를 사용합니다. 따라서 이 작업을 완료하는 방법에 대한 단계는 아래를 참조하십시오.

  • 1단계: Laravel 10 설치
  • 2단계: 데이터베이스에 연결
  • 3단계: 미들웨어 생성
  • 4단계: 미들웨어 등록
  • 5단계: 미들웨어 사용

1단계: Laravel 10 설치

먼저 터미널에서 새로운 Laravel 10 설정을 다운로드하거나 설치하십시오. 다음 명령을 실행합니다.

composer create-project --prefer-dist laravel/laravel <Your App Name>

2단계: 데이터베이스에 연결

이 단계에서는 프로젝트 루트 디렉터리로 이동하여 .env파일을 찾고 다음과 같이 데이터베이스 자격 증명을 설정합니다.

DB_CONNECTION=mysql 
DB_HOST=127.0.0.1 
DB_PORT=3306 
DB_DATABASE=<Database Name>
DB_USERNAME=<Database Username>
DB_PASSWORD=<Database Password>

3단계: 미들웨어 생성

다음 단계에서는 class 라는 미들웨어를 만듭니다  BlockIpMiddleware. 다음 명령을 실행합니다.

php artisan make:middleware BlockIpMiddleware

폴더 로 이동하여 파일을  엽니다  . 그런 다음 다음 코드를   파일로 업데이트합니다. app/Http/Middleware BlockIpMiddleware.phpBlockIpMiddleware.php

<?php
namespace App\Http\Middleware;
use Closure;
class BlockIpMiddleware
{
    // set IP addresses
    public $blockIps = ['ip-addr-1', 'ip-addr-2', '127.0.0.1'];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (in_array($request->ip(), $this->blockIps)) {
            return response()->json([
              'message' => "You don't have permission to access this website."
            ], 401);
        }

        return $next($request);
    }
}

4단계: 미들웨어 등록

다음 단계는 미들웨어를 등록해야 하므로  해당 파일로 이동하여 app/Http/ 엽니다  . 그리고 다음과 같이 미들웨어를 등록합니다.  Kernel.php

<?php
  
namespace App\Http;
  
use Illuminate\Foundation\Http\Kernel as HttpKernel;
  
class Kernel extends HttpKernel
{
    ....
  
    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        ....
        'blockIP' => \App\Http\Middleware\BlockIpMiddleware::class,
    ];
}

5단계: 미들웨어 사용

이 단계에서는 하나의 경로를 생성하고 경로 파일에서 미들웨어를 사용하는 방법을 보여줍니다. 파일을 열고  routes/web.php다음 코드를 업데이트합니다.

<?php
  
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\UserController;
   
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
    
Route::middleware(['blockIP'])->group(function () {
    Route::resource('users', UserController::class);
});

행복한 코딩!!!

2.20 GEEK