Skip to content

Commit 9e69374

Browse files
committed
Add BearerAuth middleware
1 parent 691dbf7 commit 9e69374

File tree

4 files changed

+56
-0
lines changed

4 files changed

+56
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@ This is very similar to how [Plug Router](https://github.com/elixir-plug/plug#th
127127
### Auth
128128

129129
- [`Tesla.Middleware.BasicAuth`](https://hexdocs.pm/tesla/Tesla.Middleware.BasicAuth.html) - HTTP Basic Auth
130+
- [`Tesla.Middleware.BearerAuth`](https://hexdocs.pm/tesla/Tesla.Middleware.BearerAuth.html) - HTTP Bearer Auth
130131
- [`Tesla.Middleware.DigestAuth`](https://hexdocs.pm/tesla/Tesla.Middleware.DigestAuth.html) - Digest access authentication
131132

132133
### Error handling

lib/tesla/middleware/bearer_auth.ex

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
defmodule Tesla.Middleware.BearerAuth do
2+
@moduledoc """
3+
Bearer authentication middleware.
4+
5+
Adds a `{"authorization", "Bearer <token>"}` header.
6+
7+
## Examples
8+
9+
```
10+
defmodule MyClient do
11+
use Tesla
12+
13+
# static configuration
14+
plug Tesla.Middleware.BearerAuth, token: "token"
15+
16+
# dynamic token
17+
def new(token) do
18+
Tesla.client [
19+
{Tesla.Middleware.BearerAuth, token: token)}
20+
]
21+
end
22+
end
23+
```
24+
25+
## Options
26+
27+
- `:token` - token (defaults to `""`)
28+
"""
29+
30+
@behaviour Tesla.Middleware
31+
32+
@impl Tesla.Middleware
33+
def call(env, next, opts \\ []) do
34+
token = Keyword.get(opts, :token, "")
35+
36+
env
37+
|> Tesla.put_headers([{"authorization", "Bearer #{token}"}])
38+
|> Tesla.run(next)
39+
end
40+
end

mix.exs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ defmodule Tesla.Mixfile do
102102
Middlewares: [
103103
Tesla.Middleware.BaseUrl,
104104
Tesla.Middleware.BasicAuth,
105+
Tesla.Middleware.BearerAuth,
105106
Tesla.Middleware.Compression,
106107
Tesla.Middleware.CompressRequest,
107108
Tesla.Middleware.DecodeFormUrlencoded,
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
defmodule Tesla.Middleware.BearerAuthTest do
2+
use ExUnit.Case
3+
alias Tesla.Env
4+
5+
@middleware Tesla.Middleware.BearerAuth
6+
7+
test "adds expected headers" do
8+
assert {:ok, env} = @middleware.call(%Env{}, [], [])
9+
assert env.headers == [{"authorization", "Bearer "}]
10+
11+
assert {:ok, env} = @middleware.call(%Env{}, [], token: "token")
12+
assert env.headers == [{"authorization", "Bearer token"}]
13+
end
14+
end

0 commit comments

Comments
 (0)