{"id":19472975,"url":"https://github.com/brocoders/jwt_authentication","last_synced_at":"2025-04-25T12:31:28.520Z","repository":{"id":28098662,"uuid":"31596838","full_name":"brocoders/jwt_authentication","owner":"brocoders","description":"Rails JWT token Authentication for Devise","archived":false,"fork":false,"pushed_at":"2017-01-23T20:07:42.000Z","size":44,"stargazers_count":34,"open_issues_count":6,"forks_count":11,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-03T22:01:39.665Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/brocoders.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-03-03T12:18:33.000Z","updated_at":"2024-11-01T09:06:25.000Z","dependencies_parsed_at":"2022-08-22T18:10:21.391Z","dependency_job_id":null,"html_url":"https://github.com/brocoders/jwt_authentication","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brocoders%2Fjwt_authentication","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brocoders%2Fjwt_authentication/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brocoders%2Fjwt_authentication/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brocoders%2Fjwt_authentication/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/brocoders","download_url":"https://codeload.github.com/brocoders/jwt_authentication/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250817661,"owners_count":21492192,"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":[],"created_at":"2024-11-10T19:16:38.552Z","updated_at":"2025-04-25T12:31:28.080Z","avatar_url":"https://github.com/brocoders.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"JWT Authentication\n===========================\n\n  [devise]: https://github.com/plataformatec/devise\n  [jwt-gem]: https://github.com/progrium/ruby-jwt\n  [sta-gem]: https://github.com/gonzalo-bulnes/simple_token_authentication\n\nThis is a mix of [Simple Token Authentication][sta-gem] and [JWT][jwt-gem], based on [Devise][devise].\n\n\n\n* [Installation](#installation)\n* [Using](#using)\n* [Configuring](#configuring)\n* [Authentication](#authentication)\n* [Devise](#devise)\n\nInstallation\n-----\n\nAdd the gem to your `Gemfile`:\n\n```ruby\n# Gemfile\n\ngem 'jwt_authentication', github: 'Rezonans/jwt_authentication'\n```\n\nUsing\n-----\n\n### Models\n\nMake the models token authenticatable\n\n#### ActiveRecord\n\nFirst define which model or models will be token authenticatable (typ. `User`):\n\n```ruby\n# app/models/user.rb\n\nclass User \u003c ActiveRecord::Base\n  acts_as_jwt_authenticatable\n\n  # Note: you can include any module you want. If available,\n  # token authentication will be performed before any other\n  # Devise authentication method.\n  #\n  # Include default devise modules. Others available are:\n  # :confirmable, :lockable, :timeoutable and :omniauthable\n  devise :invitable, :database_authenticatable,\n         :recoverable, :rememberable, :trackable, :validatable,\n         :lockable\n\n  # ...\nend\n```\n\nMethod `acts_as_jwt_authenticatable` extends Model with several methods: `:jwt_token`, `:generate_authentication_token!`\nand some others. Obviously, `:jwt_token` returns token for current record and `:generate_authentication_token!` updates record with new authentication_token.\n\nIf the model or models that you have chosen does not contain `:authentication_token` column, then add the new column onto it (with index):\n\n```bash\nrails g jwt_authentication MODEL\n```\nThis will add 'acts_as_jwt_authenticatable' to specified MODEL. Also, this will generate migration for adding 'authentication_token' to MODEL.\nTo skip generating migration add '-m' parameter: rails g jwt_authentication User -m.\nMigration looks like:\n```ruby\n  def change\n    add_column :users, :authentication_token, :string\n    add_index  :users, :authentication_token\n  end\n```\n\n\n### Allow controllers to handle jwt authentication\n\nDefine controllers, which will handle jwt authentication (typ. `HomeController`) for which _jwt authenticatable_ models:\n\n ```ruby\n # app/controllers/home_controller.rb\n\n class HomeController \u003c ActionController::Base # or ActionController::API\n   # ...\n\n   acts_as_jwt_authentication_handler\n   # Note: you can specify several parameters for handling authentication for this controller:  \n   #   :models (which \"acts as jwt authenticatable\") for authenticating, hash, that specifies models\n   #            and those authentication parameters :header_name, :param_name, :sign_in\n   #\n   # example:\n   #  acts_as_jwt_authentication_handler models: {terminal: {header_name: 'terminal_auth_token',\n   #                                                         param_name: 'X-Auth-Terminal-Token',\n   #                                                         sign_in: :simplified}\n   # \n   # ...\n end\n ```\n\nMethod `acts_as_jwt_authentication_handler` extends controller with methods: `:jwt_authenticate_user`, `:jwt_authenticate_user!` and with another ones.\nInstead of _user_ there will be specified model names, pair of methods for each model.\n\nSee detailed parameters and methods description in [Authentication](#authentication)\n\nAtfer controller was extended with jwt_authentication helpers, you may authenticate entity in _actions_ or in _before filter_:\n\n```ruby\nclass TerminalsController \u003c ActionController\n  acts_as_jwt_authentication_handler models: {terminal: {sign_in: :simlified}}\n  before_filter :jwt_authenticate_terminal!\n\n  def show\n    @terminal\n  end\n\nend\n\n```\n\n### Routing\n\nDefine devise routes for creating devise mapping.\n\n```ruby\n# config/routes.rb\n\n...\ndevise_for :users, module: :jwt_authentication\n...\n\n```\nDevise routing is necessary, because it creates devise mappings.\n\nConfiguring\n------\n\nSome aspects of the behavior of _Jwt Authentication_ can be customized with an initializer.\nBelow is an example with reasonable defaults:\n\n```ruby\n# config/initializers/jwt_authentication.rb\n\nJwtAuthentication.configure do |config|\n  #\n  # # Configure models, that will be default for `acts_as_jwt_authentication_handler` calling.\n  # # Note: specified model should have `authentication_token` attribute (Model should \"act as jwt authenticatable\")\n  # # header_name - name of header to search auth_token within request\n  # # param_name - name of parameters to search auth_token within request\n  # # sign_in - method to be executed if authentication success, possible values: :devise, :simplified\n  # #           if :devise selected, devises method sign_in() will be called at success authentication,\n  # #           if :simplified selected, instance variable with name of resource will be set (@user or @terminal)\n  # config.models = {user: {header_name: 'X-User-Token',\n  #                         param_name: 'user_token',\n  #                         sign_in: :devise}}\n  #\n  # # Configure mark of jwt timeout verification\n  # config.jwt_timeout_verify = true\n  #\n  # # Configure jwt timeout leeway (value in seconds)\n  # config.jwt_timeout_leeway = 60\n  #\n  # # Configure jwt timeout for simple login (without \"remember me\")\n  # # Devise SessionsController generates jwt according to this parameter\n  # # * This parameter may be overridden in each model:\n  # #    acts_as_jwt_authenticatable jwt_timeout: 10.minutes\n  # config.jwt_timeout = 20.minutes\n  #\n  # # Configure jwt timeout for session login (with \"remember me\")\n  # # Devise SessionsController generates jwt according to this parameter\n  # # * This parameter may be overridden in each model:\n  # #    acts_as_jwt_authenticatable jwt_timeout_remember_me: 1.week\n  # config.jwt_timeout_remember_me = 1.month\n  #\n  # # Configure list of model keys to be stored in jwt payload.\n  # # Also, record will be searched by this fields at authentication.\n  # # * This parameter may be overridden in each model:\n  # #    acts_as_jwt_authenticatable key_fields: [:email, :id]\n  # config.key_fields = [:email]\n  #\n\nend\n```\n\nAuthentication\n-----\n\nAs there was mentioned in [Using](#using), method `acts_as_jwt_authentication_handler` adds to controller two methods:\n`:jwt_authenticate_user` and `:jwt_authenticate_user!`. Method with bang raises error, if authentication falls,\nmethod without bang do nothing if authentication falls.\n Authentication process is pretty simple:\n* Analize request - try to find token either in params or header. If token is not found, authentication falls.\n* Read payload from jwt\n* Search for entity by field, that payload contains. If entity is not found, authentication falls.\n* Decode jwt with entities `authentication_token` (private key, that is stored as entities field).\n     If `jwt_timeout_verify` specified, timeout verification will take place also.\n* If token successfully verified - _sign_in handler_ will be called, otherwise authentication falls.\n\n `sign_in_handler`. You may specify, what to do at success authentication in `sign_in` parameter in model:\n   ```ruby\n   # config/initializers/jwt_authentication.rb\n   ...\n   config.models = {user: {sign_in: :devise}}\n   ...\n   ```\n There are 2 variants:\n* `:devise` (default) - `:sign_in` (devise controller method) will be called\n* `:simplified` - create instance variable with resource name (@user, @terminal, etc).\n\nDevise\n-----\n\nJwtAuthentication inherits devise controllers: Registrations, Confirmations, Sessions, Passwords.\nSo, you can extend this functionality with inheritance or override of some of them.\nNote, that you need to specify routes to this inherited controllers, like here:\n```ruby\n# config/routes.rb\n...\ndevise_for :users, module: :jwt_authentication\n...\n\n```\n_Note: request format will be set to `:json` by before filter `:set_request_format!`, that is plugged to each inherited devise controller.\nIt is necessary for process action if `warder.authenticate!` falls. It will render view for sessions creating by default, \nbut in our case we need json response :unauthorized_  \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrocoders%2Fjwt_authentication","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbrocoders%2Fjwt_authentication","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrocoders%2Fjwt_authentication/lists"}