0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【フロントエンド防衛】特定のIPアドレスを about:blank に飛ばす簡易アクセスコントロールのjavasript

0
Posted at

Gemini_Generated_Image_w5ldmkw5ldmkw5ld.png

フロントエンド(JavaScript)で特定のIPアドレスからのアクセスを検知し、即座に遷移(about:blank へのリダイレクト)させるアプローチについて紹介します。

通常、IP制限はWAFやCDN、Webサーバー(Nginx / Apache)などの「インフラ層」で行うのが定石ですが、フロントエンド(JavaScript)に数行のコードを仕込むだけで、驚くほどスピーディかつ手軽に同様の挙動を実現できます。

今回は、以下のJavaScriptコードを例に、フロントエンドでIP制限を行い about:blank(空白ページ)へリダイレクトさせるメリット解決できる課題について解説します。

対象となるコード

<script>
(function() {
  // ① 外部APIを使って、アクセスした人のIPアドレスを取得する
  fetch('[https://api.ipify.org?format=json](https://api.ipify.org?format=json)')
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      var clientIp = data.ip; 
      
      // デバッグ用:取得したIPをコンソールに表示
      console.log("取得されたIPアドレスは: " + clientIp);
      
      // ② ブロックしたいIPアドレスを設定
      var blockIp = 'xxx.xxx.xxx.xxx'; 

      // ③ 一致したらアクセス拒否(ページを真っ白にする)
      if (clientIp === blockIp) {
        window.location.replace('about:blank');
      }
    })
    .catch(function(error) {
      console.error('IPアドレスの取得に失敗しました:', error);
    });
})();
</script>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?