How it works
When you use Keychain.authorize
or Keychain.authorize_url
, you provide two things: a human-readable description of your app (so users can know what the entries are if they manually inspect their keychain), and a URL that uniquely identifies the resource you are storing credentials for.
- The provided URL is used to search for stored credentials in the system keychain.
- If no credentials are found, the user is asked to enter them.
- The provided block is executed with the credentials.
- If your block raises a
StandardError
, the credentials will be removed from the keychain and the user is asked to enter credentials again. - If your block completes successfully, the return value of your block is returned.
gem install system_keychain
Usage
system_keychain
supports three basic scenarios:
- Creating a connection object
- Running code that needs the username/password
- Using "scheme://user:password@hostname/..." URLs
Creating a connection object
This is most commonly used when you need to create a database connection, but can be used in any other case where you create some kind of connection object that needs a username/password to initialize.
require 'system_keychain'
@db = Keychain.authorize("My Cool App", "myapp") do |user, pass|
MyDatabaseEngine.connect(user, pass)
end
Running code that needs the username/password
Any code that needs a username/password can be executed in the Keychain.authorize
block:
require 'system_keychain'
Keychain.authorize("My Cool App", "myapp") do |user, pass|
puts `curl -u "#{user}:#{pass}" http://secure.example.com`
end
Using "scheme://user:password@hostname/..." URLs
Keychain.authorize_url
can be used to insert the username/password into a give URL:
require 'system_keychain'
@db = Keychain.authorize_url("My Cool App", "https://myapp.iriscouch.com/mydb") do |auth_url|
CouchRest.database!(auth_url)
end
This will work with any URL scheme (not just http:
and https:
):
require 'system_keychain'
@db = Keychain.authorize_url("My Cool App", "postgres://localhost:5432/mydb") do |auth_url|
Sequel.connect(auth_url)
end