APIキーの暗号化
今回はAPIキーを暗号化してAPIを保存する方法を記録したいと思います。
バージョン
- バックエンド Ruby on Rails 6.0.0
- フロントエンド JQuery 3.6.0
- データベース MySQL 5.6.51
- mac Monterey 12.5.1
実装内容
- maps/index.html.erb
<script src="https://maps.googleapis.com/maps/api/js?key=(個人のAPIキー)&callback=initMap" async defer></script>
今回はgoogle mapのAPIキーを暗号化する方法です。 Basic認証と同じ方法を用いります。
まずは暗号化のためのターミナル操作です。
% vim ~/.zshrc
export GOOGLE_API='APIキー'
を入力します。 その後にescキーを押してキーボードの :wqをクリックして、
% source ~/.zshrc
を入力します。
次に実装するための動作です。
- application_controller.rb
class ApplicationController < ActionController::Base private def url @url = ENV["GOOGLE_API"] end end
@urlを定義することで、APIキーをインスタンス変数で扱える様になるます。
次にマップのurlを使用するため、 before_actionを定義します。
class MapsController < ApplicationController before_action :url, only: :index def index end end
これでindex.html.erbでも@urlが変数として使える様になっています。 最後に
- maps/index.html.erb
<script src="https://maps.googleapis.com/maps/api/js?key=<%= @url %>&callback=initMap" async defer></script>
で完成です。