mirror of
https://github.com/lostisland/faraday.git
synced 2025-10-03 00:02:48 -04:00
1.9 KiB
1.9 KiB
layout | title | permalink | hide | next_name | next_link | top_name | top_link |
---|---|---|---|---|---|---|---|
documentation | Authentication Middleware | /middleware/authentication | true | UrlEncoded Middleware | ./url-encoded | Back to Middleware | ./list |
The Faraday::Request::Authorization
middleware allows you to automatically add an Authorization
header
to your requests. It also features a handy helper to manage Basic authentication.
Please note the way you use this middleware in Faraday 1.x is different,
examples are available at the bottom of this page.
Faraday.new(...) do |conn|
conn.request :authorization, 'Bearer', 'authentication-token'
end
With a proc
You can also provide a proc, which will be evaluated on each request:
Faraday.new(...) do |conn|
conn.request :authorization, 'Bearer', -> { MyAuthStorage.get_auth_token }
end
If the proc takes an argument, it will receive the forwarded env
Faraday.new(...) do |conn|
conn.request :authorization, 'Bearer', ->(env) { MyAuthStorage.get_auth_token(env) }
end
Basic Authentication
The middleware will automatically Base64 encode your Basic username and password:
Faraday.new(...) do |conn|
conn.request :authorization, :basic, 'username', 'password'
end
Faraday 1.x usage
In Faraday 1.x, the way you use this middleware is slightly different:
# Basic Auth request
# Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Faraday.new(...) do |conn|
conn.request :basic_auth, 'username', 'password'
end
# Token Auth request
# `options` are automatically converted into `key=value` format
# Authorization: Token authentication-token <options>
Faraday.new(...) do |conn|
conn.request :token_auth, 'authentication-token', **options
end
# Generic Auth Request
# Authorization: Bearer authentication-token
Faraday.new(...) do |conn|
conn.request :authorization, 'Bearer', 'authentication-token'
end