-
Notifications
You must be signed in to change notification settings - Fork 64
/
jwt.ex
63 lines (47 loc) · 1.63 KB
/
jwt.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
defmodule RigInboundGateway.ApiProxy.Auth.Jwt do
@moduledoc """
JWT based authentication check for proxied requests.
"""
import Plug.Conn, only: [get_req_header: 2]
alias RIG.JWT
alias RigInboundGateway.ApiProxy.Api
# ---
def check(conn, api) do
valid_tokens =
tokens_from_query_params(conn, api) ++
tokens_from_req_header(conn, api)
case valid_tokens do
[] -> {:error, :authentication_failed}
_ -> :ok
end
end
# ---
# Find and parse JWTs in request query params.
@spec tokens_from_query_params(Plug.Conn.t(), Api.t()) :: [JWT.claims()]
defp tokens_from_query_params(conn, %{"auth" => %{"use_query" => true}} = api) do
selected_param = get_in(api, ["auth", "query_name"])
tokens_string = Map.get(conn.query_params, selected_param, "")
tokens_string
|> String.split(",", trim: true)
|> Enum.map(&JWT.parse_token/1)
|> Result.filter_and_unwrap()
end
defp tokens_from_query_params(_conn, _), do: []
# --
# Find and parse JWTs in request headers.
@spec tokens_from_req_header(Plug.Conn.t(), Api.t()) :: [JWT.claims()]
defp tokens_from_req_header(conn, %{"auth" => %{"use_header" => true}} = api) do
selected_auth_header = get_in(api, ["auth", "header_name"]) |> String.downcase()
case selected_auth_header do
"authorization" ->
JWT.parse_http_header(conn.req_headers)
|> Result.filter_and_unwrap()
"x-" <> _ = custom_header ->
conn
|> get_req_header(custom_header)
|> Enum.map(&JWT.parse_token/1)
|> Result.filter_and_unwrap()
end
end
defp tokens_from_req_header(_conn, _), do: []
end