Skip to content

Commit

Permalink
fix requesting tokens from refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
Hanspagh committed Mar 7, 2023
1 parent 02f06e5 commit 9d04592
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
2 changes: 1 addition & 1 deletion lib/k8s/client/mint_http_provider.ex
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ defmodule K8s.Client.MintHTTPProvider do
@spec get_content_type(keyword()) :: binary | nil
defp get_content_type(headers) do
case List.keyfind(headers, "content-type", 0) do
{_key, content_type} -> content_type
{_key, content_type} -> content_type |> String.split(";") |> List.first()
_ -> nil
end
end
Expand Down
43 changes: 36 additions & 7 deletions lib/k8s/conn/auth/azure.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ defmodule K8s.Conn.Auth.Azure do
@moduledoc """
`auth-provider` for azure
"""
alias K8s.Conn.RequestOptions
alias K8s.Conn.Error
alias K8s.Conn.RequestOptions

require Logger
@behaviour K8s.Conn.Auth

defstruct [:token]
Expand All @@ -19,19 +21,23 @@ defmodule K8s.Conn.Auth.Azure do
"auth-provider" => %{
"config" => %{
"access-token" => token,
"tenant-id" => _tenant,
"tenant-id" => tenant,
"expires-on" => expires_on,
"refresh-token" => _refresh_token,
"client-id" => _client_id,
"apiserver-id" => _apiserver_id
"refresh-token" => refresh_token,
"client-id" => client_id,
"apiserver-id" => apiserver_id
},
"name" => "azure"
}
},
_
) do
if parse_expires(expires_on) <= DateTime.utc_now() do
{:error, %Error{message: "Azure token expired please refresh manually"}}
if DateTime.diff(DateTime.utc_now(), parse_expires(expires_on)) >= 0 do
Logger.info(
"Azure token expired, using refresh token get new access, this will stop working when refresh token expires"
)

{:ok, %__MODULE__{token: refresh_token(tenant, refresh_token, client_id, apiserver_id)}}
else
{:ok, %__MODULE__{token: token}}
end
Expand All @@ -47,6 +53,29 @@ defmodule K8s.Conn.Auth.Azure do
end
end

@spec refresh_token(String.t(), String.t(), String.t(), String.t()) :: String.t()
defp refresh_token(tenant, refresh_token, client_id, _apiserver_id) do
payload =
URI.encode_query(%{
"client_id" => client_id,
"grant_type" => "refresh_token",
"refresh_token" => refresh_token
})

{:ok, res} =
K8s.Client.MintHTTPProvider.request(
:post,
URI.new!("https://login.microsoftonline.com/#{tenant}/oauth2/v2.0/token"),
payload,
%{
"Content-Type" => "application/x-www-form-urlencoded"
},
ssl: []
)

res["access_token"]
end

defimpl RequestOptions, for: __MODULE__ do
@spec generate(K8s.Conn.Auth.Azure.t()) :: RequestOptions.generate_t()
def generate(%K8s.Conn.Auth.Azure{token: token}) do
Expand Down

0 comments on commit 9d04592

Please sign in to comment.