Installation
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
Prerequisites
NOTE : Postgres & MongoDB are not yet supported
You must have a table named users with the following fields:
idbigint(20)emailstringpasswordstring
Use comeonin for password hashing
Setup
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: 3600Sample setup for endpoints that needs an access_token
pipeline :secured_api do plug :fetch_session plug :accepts, ["json"] plug Oauth2Server.Secured endscope "/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
Usage
$ mix ecto.migrate
$ mix deps.get
$ mix deps.compile
$ mix compileTo create oauth tables execute the command :
$ mix oauth2_server.initTo create an Oauth client execute :
$ mix oauth2_server.clientcreate --password --refresh-tokenNOTE : Available grant_types as of now are password, refresh_token, client_credentials
$ mix oauth2_server.clientcreate --password --refresh-token --client-credentialsCreating access_token (parameters)
client_id : string
secret : string
grant_type : password
email : email
password : passwordRefreshing the access_token (parameters)
client_id : string
secret : string
grant_type : refresh_tokenParameters for client_credentials (parameters)
client_id : string
secret : string
grant_type : client_credentials
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)License
The Oauth2Server is released under the MIT license. See the LICENSE file.