Current section
Files
Jump to
Current section
Files
lib/okta_elixir.ex
defmodule OktaElixir do
alias OktaElixir.Randomizer
@okta_domain_url "https://#{Application.get_env(:okta_auth, :domain)}"
@okta_post_url "#{@okta_domain_url}/oauth2/default/v1/token"
@okta_verify_url "#{@okta_domain_url}/oauth2/default/v1/introspect"
def short_token_url do
redirect_uri = URI.encode(Application.get_env(:okta_auth, :redirect_uri))
client_id = Application.get_env(:okta_auth, :client_id)
"#{@okta_domain_url}/oauth2/default/v1/authorize?client_id=#{client_id}&response_type=code&state=#{
Randomizer.randomizer(10)
}&scope=openid&redirect_uri=#{redirect_uri}"
end
@spec exchange_short_token(any) :: {:error, HTTPoison.Error.t()} | {:ok, any}
def exchange_short_token(token) do
headers = [
Accept: "application/json",
Authorization: "Basic #{get_basic_header()}",
"Content-Type": "application/x-www-form-urlencoded"
]
HTTPoison.post(@okta_post_url, short_token_post_body(token), headers)
|> handle_response
end
@spec verify_token(any, any) :: {:error, HTTPoison.Error.t()} | {:ok, any}
def verify_token(token, type \\ "id_token") do
headers = [
Accept: "application/json",
Authorization: "Basic #{get_basic_header()}",
"Content-Type": "application/x-www-form-urlencoded"
]
HTTPoison.post(@okta_verify_url, generate_verify_key_body(token, type), headers)
|> handle_response
end
defp short_token_post_body(short_code) do
redirect_uri = Application.get_env(:okta_auth, :redirect_uri)
"grant_type=authorization_code&redirect_uri=#{redirect_uri}&code=#{short_code}"
end
defp generate_verify_key_body(token, token_type) do
"token=#{token}&token_type=#{token_type}"
end
defp get_basic_header do
client_id = Application.get_env(:okta_auth, :client_id)
client_secret = Application.get_env(:okta_auth, :client_secret)
Base.encode64("#{client_id}:#{client_secret}")
end
defp handle_response(response) do
case response do
{:ok, %HTTPoison.Response{body: body}} ->
{:ok, Jason.decode!(body)}
{:error, error} ->
{:error, error}
end
end
end