{"id":13491654,"url":"https://github.com/danschultzer/ex_oauth2_provider","last_synced_at":"2025-05-16T10:08:15.415Z","repository":{"id":37579818,"uuid":"82525654","full_name":"danschultzer/ex_oauth2_provider","owner":"danschultzer","description":"Making OAuth 2 provider and authentication with http bearer as simple as possible for Elixir and Phoenix apps","archived":false,"fork":false,"pushed_at":"2024-08-16T13:59:49.000Z","size":558,"stargazers_count":196,"open_issues_count":17,"forks_count":69,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-04-09T04:07:48.948Z","etag":null,"topics":["elixir","oauth2-provider","oauth2-server","phoenix"],"latest_commit_sha":null,"homepage":"","language":"Elixir","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/danschultzer.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"danschultzer"}},"created_at":"2017-02-20T06:45:23.000Z","updated_at":"2025-03-20T20:33:07.000Z","dependencies_parsed_at":"2024-01-16T09:41:39.274Z","dependency_job_id":"6be96364-621c-4c34-a136-273af05d3062","html_url":"https://github.com/danschultzer/ex_oauth2_provider","commit_stats":{"total_commits":270,"total_committers":12,"mean_commits":22.5,"dds":"0.12592592592592589","last_synced_commit":"561876a24ca7de547d91b4985dff75fd34f399a4"},"previous_names":[],"tags_count":22,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danschultzer%2Fex_oauth2_provider","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danschultzer%2Fex_oauth2_provider/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danschultzer%2Fex_oauth2_provider/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danschultzer%2Fex_oauth2_provider/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/danschultzer","download_url":"https://codeload.github.com/danschultzer/ex_oauth2_provider/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254509478,"owners_count":22082892,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["elixir","oauth2-provider","oauth2-server","phoenix"],"created_at":"2024-07-31T19:00:59.059Z","updated_at":"2025-05-16T10:08:10.403Z","avatar_url":"https://github.com/danschultzer.png","language":"Elixir","funding_links":["https://github.com/sponsors/danschultzer"],"categories":["Elixir"],"sub_categories":[],"readme":"# ExOauth2Provider\n\n[![Github CI](https://github.com/danschultzer/ex_oauth2_provider/workflows/CI/badge.svg)](https://github.com/danschultzer/ex_oauth2_provider/actions?query=workflow%3ACI)\n[![hex.pm](http://img.shields.io/hexpm/v/ex_oauth2_provider.svg?style=flat)](https://hex.pm/packages/ex_oauth2_provider)\n[![hex.pm downloads](https://img.shields.io/hexpm/dt/ex_oauth2_provider.svg?style=flat)](https://hex.pm/packages/ex_oauth2_provider)\n\nThe no-brainer library to use for adding OAuth 2.0 provider capabilities to your Elixir app. You can use [phoenix_oauth2_provider](https://github.com/danschultzer/phoenix_oauth2_provider) for easy integration with your Phoenix app.\n\n## Installation\n\nAdd ExOauth2Provider to your list of dependencies in `mix.exs`:\n\n```elixir\ndef deps do\n  [\n    # ...\n    {:ex_oauth2_provider, \"~\u003e 0.5.7\"}\n    # ...\n  ]\nend\n```\n\nRun `mix deps.get` to install it.\n\n## Getting started\n\nGenerate the migrations and schema modules:\n\n```bash\nmix ex_oauth2_provider.install\n```\n\nAdd the following to `config/config.exs`:\n\n```elixir\nconfig :my_app, ExOauth2Provider,\n  repo: MyApp.Repo,\n  resource_owner: MyApp.Users.User\n```\n\nIf you don't have any user setup, you shuld consider setting up [`Pow`](https://github.com/danschultzer/pow) first.\n\n## Authorize code flow\n\n### Authorization request\n\nYou have to ensure that a `resource_owner` has been authenticated on the following endpoints, and pass the struct as the first argument in the following methods.\n\n```elixir\n# GET /oauth/authorize?response_type=code\u0026client_id=CLIENT_ID\u0026redirect_uri=CALLBACK_URL\u0026scope=read\ncase ExOauth2Provider.Authorization.preauthorize(resource_owner, params, otp_app: :my_app) do\n  {:ok, client, scopes}             -\u003e # render authorization page\n  {:redirect, redirect_uri}         -\u003e # redirect to external redirect_uri\n  {:native_redirect, %{code: code}} -\u003e # redirect to local :show endpoint\n  {:error, error, http_status}      -\u003e # render error page\nend\n\n# POST /oauth/authorize?response_type=code\u0026client_id=CLIENT_ID\u0026redirect_uri=CALLBACK_URL\u0026scope=read\nExOauth2Provider.Authorization.authorize(resource_owner, params, otp_app: :my_app) do\n  {:redirect, redirect_uri}         -\u003e # redirect to external redirect_uri\n  {:native_redirect, %{code: code}} -\u003e # redirect to local :show endpoint\n  {:error, error, http_status}      -\u003e # render error page\nend\n\n# DELETE /oauth/authorize?response_type=code\u0026client_id=CLIENT_ID\u0026redirect_uri=CALLBACK_URL\u0026scope=read\nExOauth2Provider.Authorization.deny(resource_owner, params, otp_app: :my_app) do\n  {:redirect, redirect_uri}         -\u003e # redirect to external redirect_uri\n  {:error, error, http_status}      -\u003e # render error page\nend\n```\n\n### Authorization code grant\n\n```elixir\n# POST /oauth/token?client_id=CLIENT_ID\u0026client_secret=CLIENT_SECRET\u0026grant_type=authorization_code\u0026code=AUTHORIZATION_CODE\u0026redirect_uri=CALLBACK_URL\ncase ExOauth2Provider.Token.grant(params, otp_app: :my_app) do\n  {:ok, access_token}               -\u003e # JSON response\n  {:error, error, http_status}      -\u003e # JSON response\nend\n```\n\n### Revocation\n\n```elixir\n# GET /oauth/revoke?client_id=CLIENT_ID\u0026client_secret=CLIENT_SECRET\u0026token=ACCESS_TOKEN\ncase ExOauth2Provider.Token.revoke(params, otp_app: :my_app) do\n  {:ok, %{}}                        -\u003e # JSON response\n  {:error, error, http_status}      -\u003e # JSON response\nend\n```\n\nRevocation will return `{:ok, %{}}` status even if the token is invalid.\n\n### Authorization code flow in a Single Page Application\n\nExOauth2Provider doesn't support **implicit** grant flow. Instead you should set up an application with no client secret, and use the **Authorize code** grant flow. `client_secret` isn't required unless it has been set for the application.\n\n### Other supported token grants\n\n#### Client credentials\n\n```elixir\n# POST /oauth/token?client_id=CLIENT_ID\u0026client_secret=CLIENT_SECRET\u0026grant_type=client_credentials\ncase ExOauth2Provider.Token.grant(params, otp_app: :my_app) do\n  {:ok, access_token}               -\u003e # JSON response\n  {:error, error, http_status}      -\u003e # JSON response\nend\n```\n\n#### Refresh token\n\nRefresh tokens can be enabled in the configuration:\n\n```elixir\nconfig :my_app, ExOauth2Provider,\n  repo: MyApp.Repo,\n  resource_owner: MyApp.Users.User,\n  use_refresh_token: true\n```\n\nThe `refresh_token` grant flow will then be enabled.\n\n```elixir\n# POST /oauth/token?client_id=CLIENT_ID\u0026client_secret=CLIENT_SECRET\u0026grant_type=refresh_token\u0026refresh_token=REFRESH_TOKEN\ncase ExOauth2Provider.Token.grant(params, otp_app: :my_app) do\n  {:ok, access_token}               -\u003e # JSON response\n  {:error, error, http_status}      -\u003e # JSON response\nend\n```\n\n#### Username and password\n\nYou'll need to provide an authorization method that accepts username and password as arguments, and returns `{:ok, resource_owner}` or `{:error, reason}`. Here'a an example:\n\n```elixir\n# Configuration in config/config.exs\nconfig :my_app, ExOauth2Provider,\n  password_auth: {Auth, :authenticate}\n\n# Module example\ndefmodule Auth do\n  def authenticate(username, password, otp_app: :my_app) do\n    User\n    |\u003e Repo.get_by(email: username)\n    |\u003e verify_password(password)\n  end\n\n  defp verify_password(nil, password) do\n    check_pw(\"\", password) # Prevent timing attack\n\n    {:error, :no_user_found}\n  end\n  defp verify_password(%{password_hash: password_hash} = user, password) do\n    case check_pw(password_hash, password) do\n      true  -\u003e {:ok, user}\n      false -\u003e {:error, :invalid_password}\n    end\n  end\nend\n```\n\nThe `password` grant flow will then be enabled.\n\n```elixir\n# POST /oauth/token?client_id=CLIENT_ID\u0026grant_type=password\u0026username=USERNAME\u0026password=PASSWORD\ncase ExOauth2Provider.Token.grant(params, otp_app: :my_app) do\n  {:ok, access_token}               -\u003e # JSON response\n  {:error, error, http_status}      -\u003e # JSON response\nend\n```\n\n## Scopes\n\nServer wide scopes can be defined in the configuration:\n\n```elixir\nconfig :my_app, ExOauth2Provider,\n  repo: MyApp.Repo,\n  resource_owner: MyApp.Users.User,\n  default_scopes: ~w(public),\n  optional_scopes: ~w(read update)\n```\n\n## Plug API\n\n### [ExOauth2Provider.Plug.VerifyHeader](lib/ex_oauth2_provider/plug/verify_header.ex)\n\nLooks for a token in the Authorization Header. If one is not found, this does nothing. This will always be necessary to run to load access token and resource owner.\n\n### [ExOauth2Provider.Plug.EnsureAuthenticated](lib/ex_oauth2_provider/plug/ensure_authenticated.ex)\n\nLooks for a verified token loaded by [`VerifyHeader`](#exoauth2providerplugverifyheader). If one is not found it will call the `:unauthenticated` method in the `:handler` module.\n\nYou can use a custom `:handler` as part of a pipeline, or inside a Phoenix controller like so:\n\n```elixir\ndefmodule MyAppWeb.MyController do\n  use MyAppWeb, :controller\n\n  plug ExOauth2Provider.Plug.EnsureAuthenticated,\n    handler: MyAppWeb.MyAuthErrorHandler\nend\n```\n\n The `:handler` module always defaults to [ExOauth2Provider.Plug.ErrorHandler](lib/ex_oauth2_provider/plug/error_handler.ex).\n\n### [ExOauth2Provider.Plug.EnsureScopes](lib/ex_oauth2_provider/plug/ensure_scopes.ex)\n\nLooks for a previously verified token. If one is found, confirms that all listed scopes are present in the token. If not, the `:unauthorized` function is called on your `:handler`.\n\n```elixir\ndefmodule MyAppWeb.MyController do\n  use MyAppWeb, :controller\n\n  plug ExOauth2Provider.Plug.EnsureScopes,\n    handler: MyAppWeb.MyAuthErrorHandler, scopes: ~w(read write)\nend\n```\n\nWhen scopes' sets are specified through a `:one_of` map, the token is searched for at least one matching scopes set to allow the request. The first set that matches will allow the request. If no set matches, the `:unauthorized` function is called.\n\n```elixir\ndefmodule MyAppWeb.MyController do\n  use MyAppWeb, :controller\n\n  plug ExOauth2Provider.Plug.EnsureScopes,\n    handler: MyAppWeb.MyAuthErrorHandler,\n    one_of: [~w(admin), ~w(read write)]\nend\n```\n\n### Current resource owner and access token\n\nIf the Authorization Header was verified, you'll be able to retrieve the current resource owner or access token.\n\n```elixir\nExOauth2Provider.Plug.current_access_token(conn) # access the token in the `:default` location\nExOauth2Provider.Plug.current_access_token(conn, :custom) # access the token in the `:custom` location if set as `:key` option in `plug ExOauth2Provider.Plug.VerifyHeader`\n```\n\n```elixir\nExOauth2Provider.Plug.current_resource_owner(conn) # Access the loaded resource owner in the `:default` location\nExOauth2Provider.Plug.current_resource_owner(conn, :custom) # Access the loaded resource owner in the `:secret` location if set as `:key` option in `plug ExOauth2Provider.Plug.VerifyHeader`\n```\n\n### Custom access token generator\n\nYou can add your own access token generator, as this example shows:\n\n```elixir\n# config/config.exs\nconfig :my_app, ExOauth2Provider,\n  access_token_generator: {AccessToken, :new}\n\ndefmodule AccessToken\n  def new(access_token) do\n    with_signer(%JWT.token{\n      resource_owner_id: access_token.resource_owner_id,\n      application_id: access_token.application.id,\n      scopes: access_token.scopes,\n      expires_in: access_token.expires_in,\n      created_at: access_token.created_at\n    }, hs256(\"my_secret\"))\n  end\nend\n```\n\nRemember to change the field type for the `token` column in the `oauth_access_tokens` table to accepts tokens larger than 255 characters.\n\n### Custom access token response body\n\nYou can add extra values to the response body.\n\n```elixir\n# config/config.exs\nconfig :my_app, ExOauth2Provider,\n  access_token_response_body_handler: {CustomResponse, :response}\n\ndefmodule CustomResponse\n  def response(response_body, access_token) do\n    Map.merge(response_body, %{user_id: access_token.resource_owner.id})\n  end\nend\n```\n\nRemember to change the field type for the `token` column in the `oauth_access_tokens` table to accepts tokens larger than 255 characters.\n\n## Using binary id\n\n### Generate migration file with binary id\n\nYou'll need to create the migration file and schema modules with the argument `--binary-id`:\n\n```bash\nmix ex_oauth2_provider.install --binary-id\n```\n\n## Acknowledgement\n\nThis library was made thanks to [doorkeeper](https://github.com/doorkeeper-gem/doorkeeper), [guardian](https://github.com/ueberauth/guardian) and [authable](https://github.com/mustafaturan/authable), that gave the conceptual building blocks.\n\nThanks to [Benjamin Schultzer](https://github.com/schultzer) for helping to refactor the code.\n\n## LICENSE\n\n(The MIT License)\n\nCopyright (c) 2017-2019 Dan Schultzer \u0026 the Contributors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanschultzer%2Fex_oauth2_provider","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdanschultzer%2Fex_oauth2_provider","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanschultzer%2Fex_oauth2_provider/lists"}