Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 103 additions & 38 deletions lib/ex_force/oauth.ex
Original file line number Diff line number Diff line change
Expand Up @@ -96,21 +96,73 @@ defmodule ExForce.OAuth do
refresh_token: "refresh_token"
)
```

### `jwt_token`

```elixir
ExForce.OAuth.get_token(
"https://login.salesforce.com",
grant_type: "jwt",
username: "username",
client_id: "client_id",
jwt_key: "jwt_key"
)
```

"""

@spec get_token(ExForce.Client.t() | String.t(), list) ::
{:ok, OAuthResponse.t()} | {:error, :invalid_signature | term}

def get_token(url, payload) when is_binary(url), do: url |> build_client() |> get_token(payload)
def get_token(url, payload) when is_binary(url),
do: url |> build_client() |> get_token(payload ++ [url: url])

def get_token(client, opts) do
grant_type = Keyword.fetch!(opts, :grant_type)

client
|> Client.request(%Request{
method: :post,
url: "/services/oauth2/token",
body: build_payload(grant_type, opts)
})
|> verify_signature(grant_type, opts)
end

defp verify_signature(response, "jwt", _) do
case response do
{:ok,
%Response{
status: 200,
body: %{
"token_type" => token_type,
"instance_url" => instance_url,
"id" => id,
"access_token" => access_token,
"scope" => scope
}
}} ->
{:ok,
%OAuthResponse{
token_type: token_type,
instance_url: instance_url,
id: id,
access_token: access_token,
scope: scope
}}

{:ok, %Response{body: body}} ->
{:error, body}

{:error, _} = other ->
other
end
end

def get_token(client, payload) do
client_secret = Keyword.fetch!(payload, :client_secret)
defp verify_signature(response, _, opts) do
client_secret = Keyword.fetch!(opts, :client_secret)

case Client.request(client, %Request{
method: :post,
url: "/services/oauth2/token",
body: payload
}) do
case response do
{:ok,
%Response{
status: 200,
Expand All @@ -124,19 +176,21 @@ defmodule ExForce.OAuth do
"access_token" => access_token
}
}} ->
verify_signature(
%OAuthResponse{
token_type: token_type,
instance_url: instance_url,
id: id,
issued_at: issued_at |> String.to_integer() |> DateTime.from_unix!(:millisecond),
signature: signature,
access_token: access_token,
refresh_token: Map.get(map, "refresh_token"),
scope: Map.get(map, "scope")
},
client_secret
)
if signature == calculate_signature(id, issued_at, client_secret) do
{:ok,
%OAuthResponse{
token_type: token_type,
instance_url: instance_url,
id: id,
issued_at: issued_at |> String.to_integer() |> DateTime.from_unix!(:millisecond),
signature: signature,
access_token: access_token,
refresh_token: Map.get(map, "refresh_token"),
scope: Map.get(map, "scope")
}}
else
{:error, :invalid_signature}
end

{:ok, %Response{body: body}} ->
{:error, body}
Expand All @@ -146,24 +200,8 @@ defmodule ExForce.OAuth do
end
end

defp verify_signature(
%OAuthResponse{id: id, issued_at: issued_at, signature: signature} = resp,
client_secret
) do
if signature == calculate_signature(id, issued_at, client_secret) do
{:ok, resp}
else
{:error, :invalid_signature}
end
end

defp calculate_signature(id, issued_at, client_secret) do
issued_at_raw =
issued_at
|> DateTime.to_unix(:millisecond)
|> Integer.to_string()

hmac_fun(client_secret, id <> issued_at_raw)
hmac_fun(client_secret, id <> issued_at)
|> Base.encode64()
end

Expand All @@ -174,4 +212,31 @@ defmodule ExForce.OAuth do
else
defp hmac_fun(key, data), do: :crypto.hmac(:sha256, key, data)
end

defp build_payload("jwt", opts) do
{url, payload} = Keyword.pop(opts, :url)

key = %{"pem" => Keyword.fetch!(payload, :jwt_key)}
signer = Joken.Signer.create("RS256", key)
Comment on lines +219 to +220
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This assume that jwt_key is in the PEM format. Hm.. what about taking signer?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite understand your suggestion about "taking signer" - can you please clarify? Are you saying that instead of the user passing in the private key to get_token via jwt_key in the payload, they should instead create a Joken.Signer struct like signer themselves (presumeably via Joken.Signer.create) , and then pass that instead?

If so, are we then tied to Joken? If you want to internally use a different approach to JWT in the future, would that impact our interface, which would be expecting a Joken.Signer struct? Also, are we then complicating the user experience by asking them to work with Joken to create the struct, when before the use of Joken was transparent to them?

In some ways here I am adopting the behavior of the restforce ruby gem for Salesforce , which I am familiar with. It also takes the private key as a parameter to support JWT authentication.

I am happy to change what I have done here, if you can just help me understand a bit more clearly what you are suggesting. Thanks!

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First of all, if I were to use this feature, I'm going to keep signer struct instead of PEM format to avoid extra decoding work on each request.

We may introduce an adapter for Joken - like it does with Tesla for http. That Joken adopter will tak any params Joken.Signer.create/2 would take.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you mean "extra decoding work on each request"? In my experience, you call authenticate (e.g. via get_token) once to get an access token from Salesforce, which you would then use on all subsequent calls to the API for authentication. So you only really use the pem string once, to get the access_token. The access_token you get after JWT auth is the same as the access_token you get from any other oauth flow..

Sorry that I am having trouble following your concerns here.


claims = %{
"iss" => Keyword.fetch!(payload, :client_id),
"aud" => url,
"sub" => Keyword.fetch!(payload, :username),
"iat" => System.os_time(:second),
"exp" => System.os_time(:second) + 180
}

{:ok, token, _claims} = Joken.encode_and_sign(claims, signer)

[
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
assertion: token
]
end

defp build_payload(_, opts) do
{_, payload} = Keyword.pop(opts, :url)
payload
end
end
1 change: 1 addition & 0 deletions mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ defmodule ExForce.Mixfile do
[
{:tesla, "~> 1.3"},
{:jason, "~> 1.0"},
{:joken, "~> 2.4"},
{:bypass, "~> 2.1", only: :test},
{:credo, "~> 1.5", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 1.1", only: :dev, runtime: false},
Expand Down
2 changes: 2 additions & 0 deletions mix.lock
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
"idna": {:hex, :idna, "6.1.1", "8a63070e9f7d0c62eb9d9fcb360a7de382448200fbbd1b106cc96d3d8099df8d", [:rebar3], [{:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "92376eb7894412ed19ac475e4a86f7b413c1b9fbb5bd16dccd57934157944cea"},
"inch_ex": {:hex, :inch_ex, "2.0.0", "24268a9284a1751f2ceda569cd978e1fa394c977c45c331bb52a405de544f4de", [:mix], [{:bunt, "~> 0.2", [hex: :bunt, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "96d0ec5ecac8cf63142d02f16b7ab7152cf0f0f1a185a80161b758383c9399a8"},
"jason": {:hex, :jason, "1.2.2", "ba43e3f2709fd1aa1dce90aaabfd039d000469c05c56f0b8e31978e03fa39052", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "18a228f5f0058ee183f29f9eae0805c6e59d61c3b006760668d8d18ff0d12179"},
"joken": {:hex, :joken, "2.4.1", "63a6e47aaf735637879f31babfad93c936d63b8b7d01c5ef44c7f37689e71ab4", [:mix], [{:jose, "~> 1.11.2", [hex: :jose, repo: "hexpm", optional: false]}], "hexpm", "d4fc7c703112b2dedc4f9ec214856c3a07108c4835f0f174a369521f289c98d1"},
"jose": {:hex, :jose, "1.11.2", "f4c018ccf4fdce22c71e44d471f15f723cb3efab5d909ab2ba202b5bf35557b3", [:mix, :rebar3], [], "hexpm", "98143fbc48d55f3a18daba82d34fe48959d44538e9697c08f34200fa5f0947d2"},
"makeup": {:hex, :makeup, "1.0.5", "d5a830bc42c9800ce07dd97fa94669dfb93d3bf5fcf6ea7a0c67b2e0e4a7f26c", [:mix], [{:nimble_parsec, "~> 0.5 or ~> 1.0", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "cfa158c02d3f5c0c665d0af11512fed3fba0144cf1aadee0f2ce17747fba2ca9"},
"makeup_elixir": {:hex, :makeup_elixir, "0.15.1", "b5888c880d17d1cc3e598f05cdb5b5a91b7b17ac4eaf5f297cb697663a1094dd", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.1", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "db68c173234b07ab2a07f645a5acdc117b9f99d69ebf521821d89690ae6c6ec8"},
"makeup_erlang": {:hex, :makeup_erlang, "0.1.1", "3fcb7f09eb9d98dc4d208f49cc955a34218fc41ff6b84df7c75b3e6e533cc65f", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "174d0809e98a4ef0b3309256cbf97101c6ec01c4ab0b23e926a9e17df2077cbb"},
Expand Down
106 changes: 106 additions & 0 deletions test/ex_force/oauth_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ defmodule ExForce.OAuthTest do
conn
end

defp assert_form_body_jwt(conn) do
["application/x-www-form-urlencoded" <> _] = Conn.get_req_header(conn, "content-type")
{:ok, raw, conn} = Conn.read_body(conn)

assert %{"assertion" => _, "grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer"} =
URI.decode_query(raw)

conn
end

defp to_issued_at(string) do
{:ok, issued_at, 0} = DateTime.from_iso8601(string)
issued_at
Expand Down Expand Up @@ -288,6 +298,102 @@ defmodule ExForce.OAuthTest do
}}
end

test "get_token/2 - jwt - success", %{bypass: bypass, client: client} do
Bypass.expect_once(bypass, "POST", "/services/oauth2/token", fn conn ->
conn
|> assert_form_body_jwt()
|> Conn.put_resp_content_type("application/json")
|> Conn.resp(200, """
{
"access_token": "access_token_foo",
"id": "https://example.com/id/fakeid",
"instance_url": "https://example.com",
"token_type": "Bearer",
"scope":"full"
}
""")
end)

assert OAuth.get_token(
client,
url: "https://example.com/id/fakeid",
grant_type: "jwt",
client_id: "client_id_foo",
username: "u@example.com",
jwt_key: """
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCzr8JYWco0zKTH61qBu+5b9cRp2eBuDwLXYvvNqO6GoJUsNZpl
9cp7NzNZafM2akyH+88ygr4GmSejzGuCatqMskJZXDYnT8WT47a8RpOXUR96xqQa
Q37a22QVb+97sj8yLBgIkGn3I0bysVXjwlrENCosy2Y0Fck5sOIvxmnjKQIDAQAB
AoGAOrvivNpsvCGAY1DM/scdPLXzA96R+6eweBME1862WQ84c4D5/QYAr5H1mO6G
72yDo5dtvMb7slBxopr5MWIYGYUbrAMn7jEo3l1GUigpEnBecXkkSTMnk/DwnNW+
3gal2rFFIo4CR2c2pCFhfJYfxKspyEdah7qChUSDdjZg9LkCQQDYEnbwuct1e3yk
Dym38gWzGqxfQy5mIDrvYHY5Za1LYy+t6RUTccCLI66iI241mLAlIL4ugZ3miNhQ
CjMC/9OLAkEA1OQIxUHhtRA7pcw+LpuDyRPFHIZMQ0XTnOV2RFUhxenthMIV8HKX
eED1VI+4Tx0zvWkjErzHdI94Z/s1UHAqmwJAbH75Em945okXURn8DM2OZxzhqQQG
7GkKruB0/OU9Wzl225DKcHUSBcvpCKlZ0bfV2w7R8HBNZVEZrTcx3jOveQJATtu5
M/hXdw5wSdYCIpmQk2czWIGWtkSjQjbtPBqczAb+6HJMVijcWrsVJSGnkAatJ7hO
OZ6b811BqKKw+P7TiQJASGctccNhTmtm9o81RJWPRayBZHKYEVjnOjYlJM63KWQf
MO5oLcaGvZJrOcmOlsRVPby/liZgX+NJ8m5BFaNZgQ==
-----END RSA PRIVATE KEY-----
"""
) ==
{:ok,
%OAuthResponse{
access_token: "access_token_foo",
id: "https://example.com/id/fakeid",
instance_url: "https://example.com",
issued_at: nil,
refresh_token: nil,
scope: "full",
signature: nil,
token_type: "Bearer"
}}
end

test "get_token/2 - jwt - failure", %{bypass: bypass, client: client} do
Bypass.expect_once(bypass, "POST", "/services/oauth2/token", fn conn ->
conn
|> Conn.put_resp_content_type("application/json")
|> Conn.resp(400, """
{
"error": "invalid_grant",
"error_description": "incorrect assertion"
}
""")
end)

assert OAuth.get_token(
client,
url: "https://example.com/id/fakeid",
grant_type: "jwt",
client_id: "client_id_foo",
username: "u@example.com",
jwt_key: """
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCzr8JYWco0zKTH61qBu+5b9cRp2eBuDwLXYvvNqO6GoJUsNZpl
9cp7NzNZafM2akyH+88ygr4GmSejzGuCatqMskJZXDYnT8WT47a8RpOXUR96xqQa
Q37a22QVb+97sj8yLBgIkGn3I0bysVXjwlrENCosy2Y0Fck5sOIvxmnjKQIDAQAB
AoGAOrvivNpsvCGAY1DM/scdPLXzA96R+6eweBME1862WQ84c4D5/QYAr5H1mO6G
72yDo5dtvMb7slBxopr5MWIYGYUbrAMn7jEo3l1GUigpEnBecXkkSTMnk/DwnNW+
3gal2rFFIo4CR2c2pCFhfJYfxKspyEdah7qChUSDdjZg9LkCQQDYEnbwuct1e3yk
Dym38gWzGqxfQy5mIDrvYHY5Za1LYy+t6RUTccCLI66iI241mLAlIL4ugZ3miNhQ
CjMC/9OLAkEA1OQIxUHhtRA7pcw+LpuDyRPFHIZMQ0XTnOV2RFUhxenthMIV8HKX
eED1VI+4Tx0zvWkjErzHdI94Z/s1UHAqmwJAbH75Em945okXURn8DM2OZxzhqQQG
7GkKruB0/OU9Wzl225DKcHUSBcvpCKlZ0bfV2w7R8HBNZVEZrTcx3jOveQJATtu5
M/hXdw5wSdYCIpmQk2czWIGWtkSjQjbtPBqczAb+6HJMVijcWrsVJSGnkAatJ7hO
OZ6b811BqKKw+P7TiQJASGctccNhTmtm9o81RJWPRayBZHKYEVjnOjYlJM63KWQf
MO5oLcaGvZJrOcmOlsRVPby/liZgX+NJ8m5BFaNZgQ==
-----END RSA PRIVATE KEY-----
"""
) ==
{:error,
%{
"error" => "invalid_grant",
"error_description" => "incorrect assertion"
}}
end

test "get_token/2 with url", %{bypass: bypass} do
Bypass.expect_once(bypass, "POST", "/services/oauth2/token", fn conn ->
conn
Expand Down