Oauth2 Server for Phoenix Framework
If available in Hex, the package can be installed as:
-
Add oauth2_server to your list of dependencies in
mix.exs
:def deps do [{:oauth2_server, "~> 0.1.1"}] end
-
Ensure oauth2_server is started before your application:
def application do [applications: [:oauth2_server]] end
NOTE : Postgres & MongoDB are not yet supported
You must have a table named users
with the following fields:
id
bigint(20)email
stringpassword
string
Use comeonin for password hashing
-
Add these lines on your config.exs
config :oauth2_server, Oauth2Server.Repo, adapter: Ecto.Adapters.MySQL, username: "yourdbusername", password: "yourdbpassword", database: "yourdbname", hostname: "yourdbhostname"
config :oauth2_server, Oauth2Server.Settings, access_token_expiration: 3600, refresh_token_expiration: 3600
-
Sample setup for endpoints that needs an access_token
pipeline :secured_api do plug :fetch_session plug :accepts, ["json"] plug Oauth2Server.Secured end
scope "/api", Phoenixtrial do pipe_through :api scope "/v1", v1, as: :v1 do post "/login", UserApiController, :login scope "/auth", auth, as: :auth do pipe_through :secured_api post "/get-details", UserApiAuthController, :get_details end end end
$ mix ecto.migrate
$ mix deps.get
$ mix deps.compile
$ mix compile
To create oauth tables execute the command :
$ mix oauth2_server.init
To create an Oauth client execute :
$ mix oauth2_server.clientcreate --password --refresh-token
NOTE : Available grant_types as of now are password, refresh_token, client_credentials
$ mix oauth2_server.clientcreate --password --refresh-token --client-credentials
client_id : string
secret : string
grant_type : password
email : email
password : password
client_id : string
secret : string
grant_type : refresh_token
refresh_token : refresh_token
client_id : string
secret : string
grant_type : client_credentials
defmodule Phoenixtrial.v1.auth.UserApiController do
use Phoenixtrial.Web, :controller
alias Oauth2Server.Authenticator
def login(conn, params) do
res = Authenticator.validate(params)
case res.code do
200 ->
json conn, %{access_token: res.access_token, refresh_token: res.refresh_token, expiration: res.expires_at}
400 ->
conn |> put_status(400) |> json(%{"message": res.message})
nil ->
conn |> put_status(400) |> json(%{"message": "Invalid oauth credentials."})
end
end
end
For secured endpoints you will need to add a parameter access_token
for your requests.
You can fetch the user id of the token owner via :
get_session(conn, :oauth2_server_user_id)
The Oauth2Server is released under the MIT license. See the LICENSE file.