What is the laravel way of storing API keys?

江枫思渺然 提交于 2019-12-23 23:08:16

问题


Is there a specific file or directory that is recommended for storing API keys? I'd like to take my keys out of my codebase but I'm not sure where to put them.


回答1:


You can make your API keys environment variables and then access them that way. Read more about protecting sensitive configuration from the docs.

You simply create a .env.php file in the root of your project that returns an array of environment variables.

<?php

return array(
    'SECRET_API_KEY' => 'PUT YOUR API KEY HERE'
);

Then you can access it in your app like so.

getenv('SECRET_API_KEY');



回答2:


This is an updated answer for newer versions of Laravel.

First, set the credentials in your .env file. Generally you'll want to prefix it with the name of the service, so in this example I'll use Google Maps.

GOOGLE_KEY=secret_api_key

Then, take a look in config/services.php - it's where we can map environment variables into the app configuration. You'll see some existing examples out of the box. You can add additional configuration under the service name and point it to the environment variable.

'google' => [
    'key' => env('GOOGLE_KEY'),
],

Then when you need to access this key within your app you can get it through the app configuration instead.

// Through a facade
Config::get('services.google.key');

// Through a helper
config('services.google.key');

Be sure not to just use env('GOOGLE_KEY) through your app - it's more performant to go through the app configuration as it's cached - especially if you call php artisan config:cache as part of your deployment process.



来源:https://stackoverflow.com/questions/25310088/what-is-the-laravel-way-of-storing-api-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!