Skip to content

Commit fe600c7

Browse files
authored
Drop deprecated auth helpers from Connection. (lostisland#1308)
Merge Authentication middleware. Add possibility of passing a proc. Update documentation.
1 parent 7d727f4 commit fe600c7

File tree

8 files changed

+58
-229
lines changed

8 files changed

+58
-229
lines changed

docs/middleware/request/authentication.md

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,37 +10,30 @@ top_link: ./list
1010
---
1111

1212
The `Faraday::Request::Authorization` middleware allows you to automatically add an `Authorization` header
13-
to your requests. It also features 2 specialised sub-classes that provide useful extra features for Basic Authentication
14-
and Token Authentication requests.
15-
16-
### Any Authentication
17-
18-
The generic `Authorization` middleware allows you to add any type of Authorization header.
13+
to your requests. It also features a handy helper to manage Basic authentication.
1914

2015
```ruby
2116
Faraday.new(...) do |conn|
2217
conn.request :authorization, 'Bearer', 'authentication-token'
2318
end
2419
```
2520

26-
### Basic Authentication
21+
### With a proc
2722

28-
`BasicAuthentication` adds a 'Basic' type Authorization header to a Faraday request.
23+
You can also provide a proc, which will be evaluated on each request:
2924

3025
```ruby
3126
Faraday.new(...) do |conn|
32-
conn.request :basic_auth, 'username', 'password'
27+
conn.request :authorization, 'Bearer', -> { MyAuthStorage.get_auth_token }
3328
end
3429
```
3530

36-
### Token Authentication
31+
### Basic Authentication
3732

38-
`TokenAuthentication` adds a 'Token' type Authorization header to a Faraday request.
39-
You can optionally provide a hash of `options` that will be appended to the token.
40-
This is not used anymore in modern web and have been replaced by Bearer tokens.
33+
The middleware will automatically Base64 encode your Basic username and password:
4134

4235
```ruby
4336
Faraday.new(...) do |conn|
44-
conn.request :token_auth, 'authentication-token', **options
37+
conn.request :authorization, :basic, 'username', 'password'
4538
end
4639
```

lib/faraday/connection.rb

Lines changed: 0 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -283,77 +283,6 @@ def #{method}(url = nil, body = nil, headers = nil, &block)
283283
RUBY
284284
end
285285

286-
# Sets up the Authorization header with these credentials, encoded
287-
# with base64.
288-
#
289-
# @param login [String] The authentication login.
290-
# @param pass [String] The authentication password.
291-
#
292-
# @example
293-
#
294-
# conn.basic_auth 'Aladdin', 'open sesame'
295-
# conn.headers['Authorization']
296-
# # => "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
297-
#
298-
# @return [void]
299-
def basic_auth(login, pass)
300-
warn <<~TEXT
301-
WARNING: `Faraday::Connection#basic_auth` is deprecated; it will be removed in version 2.0.
302-
While initializing your connection, use `#request(:basic_auth, ...)` instead.
303-
See https://lostisland.github.io/faraday/middleware/authentication for more usage info.
304-
TEXT
305-
set_authorization_header(:basic_auth, login, pass)
306-
end
307-
308-
# Sets up the Authorization header with the given token.
309-
#
310-
# @param token [String]
311-
# @param options [Hash] extra token options.
312-
#
313-
# @example
314-
#
315-
# conn.token_auth 'abcdef', foo: 'bar'
316-
# conn.headers['Authorization']
317-
# # => "Token token=\"abcdef\",
318-
# foo=\"bar\""
319-
#
320-
# @return [void]
321-
def token_auth(token, options = nil)
322-
warn <<~TEXT
323-
WARNING: `Faraday::Connection#token_auth` is deprecated; it will be removed in version 2.0.
324-
While initializing your connection, use `#request(:token_auth, ...)` instead.
325-
See https://lostisland.github.io/faraday/middleware/authentication for more usage info.
326-
TEXT
327-
set_authorization_header(:token_auth, token, options)
328-
end
329-
330-
# Sets up a custom Authorization header.
331-
#
332-
# @param type [String] authorization type
333-
# @param token [String, Hash] token. A String value is taken literally, and
334-
# a Hash is encoded into comma-separated key/value pairs.
335-
#
336-
# @example
337-
#
338-
# conn.authorization :Bearer, 'mF_9.B5f-4.1JqM'
339-
# conn.headers['Authorization']
340-
# # => "Bearer mF_9.B5f-4.1JqM"
341-
#
342-
# conn.authorization :Token, token: 'abcdef', foo: 'bar'
343-
# conn.headers['Authorization']
344-
# # => "Token token=\"abcdef\",
345-
# foo=\"bar\""
346-
#
347-
# @return [void]
348-
def authorization(type, token)
349-
warn <<~TEXT
350-
WARNING: `Faraday::Connection#authorization` is deprecated; it will be removed in version 2.0.
351-
While initializing your connection, use `#request(:authorization, ...)` instead.
352-
See https://lostisland.github.io/faraday/middleware/authentication for more usage info.
353-
TEXT
354-
set_authorization_header(:authorization, type, token)
355-
end
356-
357286
# Check if the adapter is parallel-capable.
358287
#
359288
# @yield if the adapter isn't parallel-capable, or if no adapter is set yet.
@@ -579,14 +508,6 @@ def with_uri_credentials(uri)
579508
yield(Utils.unescape(uri.user), Utils.unescape(uri.password))
580509
end
581510

582-
def set_authorization_header(header_type, *args)
583-
header = Faraday::Request
584-
.lookup_middleware(header_type)
585-
.header(*args)
586-
587-
headers[Faraday::Request::Authorization::KEY] = header
588-
end
589-
590511
def proxy_from_env(url)
591512
return if Faraday.ignore_env_proxy
592513

lib/faraday/request.rb

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,9 +131,7 @@ def to_env(connection)
131131
end
132132

133133
require 'faraday/request/authorization'
134-
require 'faraday/request/basic_authentication'
135134
require 'faraday/request/instrumentation'
136135
require 'faraday/request/multipart'
137136
require 'faraday/request/retry'
138-
require 'faraday/request/token_authentication'
139137
require 'faraday/request/url_encoded'

lib/faraday/request/authorization.rb

Lines changed: 36 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,53 @@
11
# frozen_string_literal: true
22

3+
require 'base64'
4+
35
module Faraday
46
class Request
57
# Request middleware for the Authorization HTTP header
68
class Authorization < Faraday::Middleware
79
KEY = 'Authorization'
810

9-
# @param type [String, Symbol]
10-
# @param token [String, Symbol, Hash]
11-
# @return [String] a header value
12-
def self.header(type, token)
13-
case token
14-
when String, Symbol
15-
"#{type} #{token}"
16-
when Hash
17-
build_hash(type.to_s, token)
18-
else
19-
raise ArgumentError,
20-
"Can't build an Authorization #{type}" \
21-
"header from #{token.inspect}"
22-
end
23-
end
24-
25-
# @param type [String]
26-
# @param hash [Hash]
27-
# @return [String] type followed by comma-separated key=value pairs
28-
# @api private
29-
def self.build_hash(type, hash)
30-
comma = ', '
31-
values = []
32-
hash.each do |key, value|
33-
values << "#{key}=#{value.to_s.inspect}"
34-
end
35-
"#{type} #{values * comma}"
36-
end
37-
3811
# @param app [#call]
3912
# @param type [String, Symbol] Type of Authorization
40-
# @param token [String, Symbol, Hash] Token value for the Authorization
41-
def initialize(app, type, token)
42-
@header_value = self.class.header(type, token)
13+
# @param params [Array<String, Proc>] parameters to build the Authorization header.
14+
# If the type is `:basic`, then these can be a login and password pair.
15+
# Otherwise, a single value is expected that will be appended after the type.
16+
# This value can be a proc, in which case it will be invoked on each request.
17+
def initialize(app, type, *params)
18+
@type = type
19+
@params = params
4320
super(app)
4421
end
4522

4623
# @param env [Faraday::Env]
47-
def call(env)
48-
env.request_headers[KEY] = @header_value unless env.request_headers[KEY]
49-
@app.call(env)
24+
def on_request(env)
25+
return if env.request_headers[KEY]
26+
27+
env.request_headers[KEY] = header_from(@type, *@params)
28+
end
29+
30+
private
31+
32+
# @param type [String, Symbol]
33+
# @param params [Array]
34+
# @return [String] a header value
35+
def header_from(type, *params)
36+
if type.to_s.casecmp('basic').zero? && params.size == 2
37+
basic_header_from(*params)
38+
elsif params.size != 1
39+
raise ArgumentError, "Unexpected params received (got #{params.size} instead of 1)"
40+
else
41+
value = params.first
42+
value = value.call if value.is_a?(Proc)
43+
"#{type} #{value}"
44+
end
45+
end
46+
47+
def basic_header_from(login, pass)
48+
value = Base64.encode64("#{login}:#{pass}")
49+
value.delete!("\n")
50+
"Basic #{value}"
5051
end
5152
end
5253
end

lib/faraday/request/basic_authentication.rb

Lines changed: 0 additions & 23 deletions
This file was deleted.

lib/faraday/request/token_authentication.rb

Lines changed: 0 additions & 24 deletions
This file was deleted.

spec/faraday/connection_spec.rb

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -141,28 +141,6 @@
141141
end
142142
end
143143

144-
describe 'basic_auth' do
145-
subject { conn }
146-
147-
context 'calling the #basic_auth method' do
148-
before { subject.basic_auth 'Aladdin', 'open sesame' }
149-
150-
it { expect(subject.headers['Authorization']).to eq('Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==') }
151-
end
152-
153-
context 'adding basic auth info to url' do
154-
let(:url) { 'http://Aladdin:open%20sesame@sushi.com/fish' }
155-
156-
it { expect(subject.headers['Authorization']).to eq('Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==') }
157-
end
158-
end
159-
160-
describe '#token_auth' do
161-
before { subject.token_auth('abcdef', nonce: 'abc') }
162-
163-
it { expect(subject.headers['Authorization']).to eq('Token nonce="abc", token="abcdef"') }
164-
end
165-
166144
describe '#build_exclusive_url' do
167145
context 'with relative path' do
168146
subject { conn.build_exclusive_url('sake.html') }
@@ -605,7 +583,6 @@
605583

606584
context 'after manual changes' do
607585
before do
608-
subject.basic_auth('', '')
609586
subject.headers['content-length'] = 12
610587
subject.params['b'] = '2'
611588
subject.options[:open_timeout] = 10

0 commit comments

Comments
 (0)