Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

XSS/CSRF safe JWT auth designed for SPA

License

NotificationsYou must be signed in to change notification settings

tuwukee/jwt_sessions

Repository files navigation

Gem VersionMaintainabilityCodacy BadgeBuild Status

XSS/CSRF safe JWT auth designed for SPA

Table of Contents

Synopsis

The primary goal of this gem is to provide configurable, manageable, and safe stateful sessions based on JSON Web Tokens.

The gem stores JWT based sessions on the backend (currently, Redis and memory stores are supported), making it possible to manage sessions, reset passwords and logout users in a reliable and secure way.

It is designed to be framework agnostic, yet easily integrable, and Rails integration is available out of the box.

The core concept behindjwt_sessions is that each session is represented by a pair of tokens:access andrefresh. The session store is used to handle CSRF checks and prevent refresh token hijacking. Both tokens have configurable expiration times but in general the refresh token is supposed to have a longer lifespan than the access token. The access token is used to retrieve secure resources and the refresh token is used to renew the access token once it has expired. The default token store uses Redis.

All tokens are encoded and decoded byruby-jwt gem. Its reserved claim names are supported and it can configure claim checks and cryptographic signing algorithms supported by it.jwt_sessions itself usesext claim andHS256 signing by default.

Installation

Put this line in your Gemfile:

gem"jwt_sessions"

Then run:

bundle install

Getting Started

You should configure an algorithm and specify the signing key. By default the gem uses theHS256 signing algorithm.

JWTSessions.signing_key="secret"

Authorization mixin provides helper methods which are used to retrieve the access and refresh tokens from incoming requests and verify the CSRF token if needed. It assumes that a token can be found either in a cookie or in a header (cookie and header names are configurable). It tries to retrieve the token from headers first and then from cookies (CSRF check included) if the header check fails.

Creating a session

Each token contains a payload with custom session info. The payload is a regular Ruby hash.
Usually, it contains a user ID or other data which help identify the current user but the payload can be an empty hash as well.

>payload={user_id:user.id}=>{:user_id=>1}

Generate the session with a custom payload. By default the same payload is sewn into the session's access and refresh tokens.

>session=JWTSessions::Session.new(payload:payload)=>#<JWTSessions::Session:0x00007fbe2cce9ea0...>

Sometimes it makes sense to keep different data within the payloads of the access and refresh tokens.
The access token may contain rich data including user settings, etc., while the appropriate refresh token will include only the bare minimum which will be required to reconstruct a payload for the new access token during refresh.

session=JWTSessions::Session.new(payload:payload,refresh_payload:refresh_payload)

Now we can calllogin method on the session to retrieve a set of tokens.

>session.login=>{:csrf=>"BmhxDRW5NAEIx...",:access=>"eyJhbGciOiJIUzI1NiJ9...",:access_expires_at=>"...":refresh=>"eyJhbGciOiJIUzI1NiJ9...",:refresh_expires_at=>"..."}

Access/refresh tokens automatically contain expiration time in their payload. Yet expiration times are also added to the output just in case.
The token's payload will be available in the controllers once the access (or refresh) token is authorized.

To perform the refresh do:

>session.refresh(refresh_token)=>{:csrf=>"+pk2SQrXHRo1iV1x4O...",:access=>"eyJhbGciOiJIUzI1...",:access_expires_at=>"..."}

AvailableJWTSessions::Session.new options:

  • payload: a hash object with session data which will be included into an access token payload. Default is an empty hash.
  • refresh_payload: a hash object with session data which will be included into a refresh token payload. Default is the value of the access payload.
  • access_claims: a hash object withJWT claims which will be validated within the access token payload. For example,JWTSessions::Session.new(payload: { user_id: 1, aud: ['admin'], verify_aud: true }) means that the token can be used only by "admin" audience. Also, the endpoint can automatically validate claims instead. Seetoken_claims method.
  • refresh_claims: a hash object withJWT claims which will be validated within the refresh token payload.
  • namespace: a string object which helps to group sessions by a custom criteria. For example, sessions can be grouped by user ID, making it possible to logout the user from all devices. More infoSessions Namespace.
  • refresh_by_access_allowed: a boolean value. Default is false. It links access and refresh tokens (adds refresh token ID to access payload), making it possible to perform a session refresh by the last expired access token. SeeRefresh with access token.
  • access_exp: an integer value. Contains an access token expiration time in seconds. The value overrides global settings. SeeExpiration time.
  • refresh_exp: an integer value. Contains a refresh token expiration time in seconds. The value overrides global settings. SeeExpiration time.

Helper methods withinAuthorization mixin:

  • authorize_access_request!: validates access token within the request.
  • authorize_refresh_request!: validates refresh token within the request.
  • found_token: a raw token found within the request.
  • payload: a decoded token's payload. Returns an empty hash in case the token is absent in the request headers/cookies.
  • claimless_payload: a decoded token's payload without claims validation (can be used for checking data of an expired token).
  • token_claims: the method should be defined by a developer and is expected to return a hash-like object with claims to be validated within a token's payload.

Rails integration

IncludeJWTSessions::RailsAuthorization in your controllers and addJWTSessions::Errors::Unauthorized exception handling if needed.

classApplicationController <ActionController::APIincludeJWTSessions::RailsAuthorizationrescue_fromJWTSessions::Errors::Unauthorized,with::not_authorizedprivatedefnot_authorizedrenderjson:{error:"Not authorized"},status::unauthorizedendend

Specify a signing key for JSON Web Tokens inconfig/initializers/jwt_session.rb
It is advisable to store the key itself in a secure way, f.e. within app credentials.

JWTSessions.algorithm="HS256"JWTSessions.signing_key=Rails.application.credentials.secret_jwt_signing_key

Most of the algorithms require private and public keys to sign a token. However, HMAC requires only a single key and you can use thesigning_key shortcut to sign the token. For other algorithms you must specify private and public keys separately.

JWTSessions.algorithm="RS256"JWTSessions.private_key=OpenSSL::PKey::RSA.generate(2048)JWTSessions.public_key=JWTSessions.private_key.public_key

You can build a login controller to receive access, refresh and CSRF tokens in exchange for the user's login/password.
Refresh controller allows you to get a new access token using the refresh token after access is expired. \

Here is an example of a simple login controller, which returns a set of tokens as a plain JSON response.
It is also possible to set tokens as cookies in the response instead.

classLoginController <ApplicationControllerdefcreateuser=User.find_by!(email:params[:email])ifuser.authenticate(params[:password])payload={user_id:user.id}session=JWTSessions::Session.new(payload:payload)renderjson:session.loginelserenderjson:"Invalid user",status::unauthorizedendendend

Now you can build a refresh endpoint. To protect the endpoint use the before_actionauthorize_refresh_request!.
The endpoint itself should return a renewed access token.

classRefreshController <ApplicationControllerbefore_action:authorize_refresh_request!defcreatesession=JWTSessions::Session.new(payload:access_payload)renderjson:session.refresh(found_token)enddefaccess_payload# payload here stands for refresh token payloadbuild_access_payload_based_on_refresh(payload)endend

In the above example,found_token is a token fetched from request headers or cookies. In the context ofRefreshController it is a refresh token.
The refresh request with headers must includeX-Refresh-Token (header name is configurable) with the refresh token.

X-Refresh-Token: eyJhbGciOiJIUzI1NiJ9...POST /refresh

When there are login and refresh endpoints, you can protect the rest of your secured controllers withbefore_action :authorize_access_request!.

classUsersController <ApplicationControllerbefore_action:authorize_access_request!defindex    ...enddefshow    ...endend

Headers must includeAuthorization: Bearer with access token.

Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...GET /users

Thepayload method is available to fetch encoded data from the token.

defcurrent_user@current_user ||=User.find(payload["user_id"])end

Methodsauthorize_refresh_request! andauthorize_access_request! will always try to fetch the tokens from the headers first and then from the cookies.For the cases when an endpoint must support only one specific token transport the following authorization methods can be used instead:

authorize_by_access_cookie!authorize_by_access_header!authorize_by_refresh_cookie!authorize_by_refresh_header!

Non-Rails usage

You must includeJWTSessions::Authorization module to your auth class and within it implement the following methods:

  1. request_headers
defrequest_headers# must return hash-like object with request headersend
  1. request_cookies
defrequest_cookies# must return hash-like object with request cookiesend
  1. request_method
defrequest_method# must return current request verb as a string in upcase, f.e. 'GET', 'HEAD', 'POST', 'PATCH', etcend

Example Sinatra app.
NOTE: Rack updates HTTP headers by using theHTTP_ prefix, upcasing and underscores for the sake of simplicity. JWTSessions token header names are converted to the rack-style in this example.

require"sinatra/base"JWTSessions.access_header="authorization"JWTSessions.refresh_header="x_refresh_token"JWTSessions.csrf_header="x_csrf_token"JWTSessions.signing_key="secret key"classSimpleApp <Sinatra::BaseincludeJWTSessions::Authorizationdefrequest_headersenv.inject({}){ |acc,(k,v)|acc[$1.downcase]=vifk =~/^http_(.*)/i;acc}enddefrequest_cookiesrequest.cookiesenddefrequest_methodrequest.request_methodendbeforedocontent_type"application/json"endpost"/login"doaccess_payload={key:"access value"}refresh_payload={key:"refresh value"}session=JWTSessions::Session.new(payload:access_payload,refresh_payload:refresh_payload)session.login.to_jsonend# POST /refresh# x_refresh_token: ...post"/refresh"doauthorize_refresh_request!access_payload={key:"reloaded access value"}session=JWTSessions::Session.new(payload:access_payload,refresh_payload:payload)session.refresh(found_token).to_jsonend# GET /payload# authorization: Bearer ...get"/payload"doauthorize_access_request!payload.to_jsonend# ...end

Configuration

List of configurable settings with their default values.

Token store

In order to configure a token store you should set up a store adapter in a following way:JWTSessions.token_store = :redis, { redis_url: 'redis://127.0.0.1:6379/0' } (options can be omitted). Currently supported stores are:redis and:memory. Please note, that if you want to use Redis as a store then you should haveredis-client gem listed in your Gemfile. If you do not configure the adapter explicitly, this gem will try to loadredis-client and use it. Otherwise it will fall back to amemory adapter.

Memory store only accepts aprefix (used for Redis db keys). Here is a default configuration for Redis:

JWTSessions.token_store=:redis,{redis_host:"127.0.0.1",redis_port:"6379",redis_db_name:"0",token_prefix:"jwt_",pool_size:Integer(ENV.fetch("RAILS_MAX_THREADS",5))}

On defaultpool_size is set to 5. Override it with the value of max number of parallel redis connections in your app.

You can also provide a Redis URL instead:

JWTSessions.token_store=:redis,{redis_url:"redis://localhost:6397"}

NOTE: ifREDIS_URL environment variable is set it is used automatically.

SSL, timeout, reconnect, etc. redis settings are supported:

JWTSessions.token_store=:redis,{read_timeout:1.5,reconnect_attempts:10,ssl_params:{verify_mode:OpenSSL::SSL::VERIFY_NONE}}

If you already have a configured Redis client, you can pass it among the options to reduce opened connections to a Redis server:

JWTSessions.token_store=:redis,{redis_client:redis_pool}
JWT signature
JWTSessions.algorithm="HS256"

You need to specify a secret to use for HMAC as this setting does not have a default value.

JWTSessions.signing_key="secret"

If you are using another algorithm like RSA/ECDSA/EDDSA you should specify private and public keys.

JWTSessions.private_key="abcd"JWTSessions.public_key="efjh"

NOTE: ED25519 and HS512256 requirerbnacl installation in order to make it work.

jwt_sessions only usesexp claim by default when it decodes tokens and you can specify which additional claims to use bysettingjwt_options. You can also specify leeway to account for clock skew.

JWTSessions.jwt_options[:verify_iss]=trueJWTSessions.jwt_options[:verify_sub]=trueJWTSessions.jwt_options[:verify_iat]=trueJWTSessions.jwt_options[:verify_aud]=trueJWTSessions.jwt_options[:leeway]=30# seconds

To pass options likesub,aud,iss, or leeways you should specify a method calledtoken_claims in your controller.

classUsersController <ApplicationControllerbefore_action:authorize_access_request!deftoken_claims{aud:["admin","staff"],verify_aud:true,# can be used locally instead of a global settingexp_leeway:15# will be used instead of default leeway only for exp claim}endend

Claims are also supported byJWTSessions::Session and you can passaccess_claims andrefresh_claims options in the initializer.

Request headers and cookies names

Default request headers/cookies names can be reconfigured.

JWTSessions.access_header="Authorization"JWTSessions.access_cookie="jwt_access"JWTSessions.refresh_header="X-Refresh-Token"JWTSessions.refresh_cookie="jwt_refresh"JWTSessions.csrf_header="X-CSRF-Token"
Expiration time

Access token must have a short life span, while refresh tokens can be stored for a longer time period.

JWTSessions.access_exp_time=3600# 1 hour in secondsJWTSessions.refresh_exp_time=604800# 1 week in seconds

It is defined globally, but can be overridden on a session level. SeeJWTSessions::Session.new options for more info.

Exceptions

JWTSessions::Errors::Error - base class, all possible exceptions are inhereted from it.
JWTSessions::Errors::Malconfigured - some required gem settings are empty, or methods are not implemented.
JWTSessions::Errors::InvalidPayload - token's payload doesn't contain required keys or they are invalid.
JWTSessions::Errors::Unauthorized - token can't be decoded or JWT claims are invalid.
JWTSessions::Errors::ClaimsVerification - JWT claims are invalid (inherited fromJWTSessions::Errors::Unauthorized).
JWTSessions::Errors::Expired - token is expired (inherited fromJWTSessions::Errors::ClaimsVerification).

CSRF and cookies

When you use cookies as your tokens transport it becomes vulnerable to CSRF. That is why both the login and refresh methods of theSession class produce CSRF tokens for you.Authorization mixin expects that this token is sent with all requests except GET and HEAD in a header specified among this gem's settings (X-CSRF-Token by default). Verification will be done automatically and theAuthorization exception will be raised in case of a mismatch between the token from the header and the one stored in the session.
Although you do not need to mitigate BREACH attacks it is still possible to generate a new masked token with the access token.

session=JWTSessions::Session.newsession.masked_csrf(access_token)
Refresh with access token

Sometimes it is not secure enough to store the refresh tokens in web / JS clients.
This is why you have the option to only use an access token and to not pass the refresh token to the client at all.
Session acceptsrefresh_by_access_allowed: true setting, which links the access token to the corresponding refresh token.

Example Rails login controller, which passes an access token token via cookies and renders CSRF:

classLoginController <ApplicationControllerdefcreateuser=User.find_by!(email:params[:email])ifuser.authenticate(params[:password])payload={user_id:user.id}session=JWTSessions::Session.new(payload:payload,refresh_by_access_allowed:true)tokens=session.loginresponse.set_cookie(JWTSessions.access_cookie,value:tokens[:access],httponly:true,secure:Rails.env.production?)renderjson:{csrf:tokens[:csrf]}elserenderjson:"Invalid email or password",status::unauthorizedendendend

The gem provides the ability to refresh the session by access token.

session=JWTSessions::Session.new(payload:payload,refresh_by_access_allowed:true)tokens=session.refresh_by_access_payload

In case of token forgery and successful refresh performed by an attacker the original user will have to logout.
To protect the endpoint use the before_actionauthorize_refresh_by_access_request!.
Refresh should be performed once the access token is already expired and we need to use theclaimless_payload method in order to skip JWT expiration validation (and other claims) in order to proceed.

Optionallyrefresh_by_access_payload accepts a block argument (the same wayrefresh method does).The block will be called if the refresh action is performed before the access token is expired.Thereby it's possible to prohibit users from making refresh calls while their access token is still active.

tokens=session.refresh_by_access_payloaddo# here goes malicious activity alertraiseJWTSessions::Errors::Unauthorized,"Refresh action is performed before the expiration of the access token."end

Example Rails refresh by access controller with cookies as token transport:

classRefreshController <ApplicationControllerbefore_action:authorize_refresh_by_access_request!defcreatesession=JWTSessions::Session.new(payload:claimless_payload,refresh_by_access_allowed:true)tokens=session.refresh_by_access_payloadresponse.set_cookie(JWTSessions.access_cookie,value:tokens[:access],httponly:true,secure:Rails.env.production?)renderjson:{csrf:tokens[:csrf]}endend

For the cases when an endpoint must support only one specific token transport the following auth methods can be used instead:

authorize_refresh_by_access_cookie!authorize_refresh_by_access_header!

Refresh token hijack protection

There is a security recommendation regarding the usage of refresh tokens: only perform refresh when an access token expires.
Sessions are always defined by a pair of tokens and there cannot be multiple access tokens for a single refresh token. Simultaneous usage of the refresh token by multiple users can be easily noticed as refresh will be performed before the expiration of the access token by one of the users. As a result,refresh method of theSession class supports an optional block as one of its arguments which will be executed only in case of refresh being performed before the expiration of the access token.

session=JwtSessions::Session.new(payload:payload)session.refresh(refresh_token){ |refresh_token_uid,access_token_expiration| ...}

Flush Sessions

Flush a session by its refresh token. The method returns number of flushed sessions:

session=JWTSessions::Session.newtokens=session.loginsession.flush_by_token(tokens[:refresh])# => 1

Flush a session by its access token:

session=JWTSessions::Session.new(refresh_by_access_allowed:true)tokens=session.loginsession.flush_by_access_payload# orsession=JWTSessions::Session.new(refresh_by_access_allowed:true,payload:payload)session.flush_by_access_payload

Or by refresh token UID:

session.flush_by_uid(uid)# => 1
Sessions namespace

It's possible to group sessions by custom namespaces:

session=JWTSessions::Session.new(namespace:"account-1")

Selectively flush sessions by namespace:

session=JWTSessions::Session.new(namespace:"ie-sessions")session.flush_namespaced# will flush all sessions which belong to the same namespace

Selectively flush one single session inside a namespace by its access token:

session=JWTSessions::Session.new(namespace:"ie-sessions",payload:payload)session.flush_by_access_payload# will flush a specific session which belongs to an existing namespace

Flush access tokens only:

session=JWTSessions::Session.new(namespace:"ie-sessions")session.flush_namespaced_access_tokens# will flush all access tokens which belong to the same namespace, but will keep refresh tokens

Force flush of all app sessions:

JWTSessions::Session.flush_all
Logout

To logout you need to remove both access and refresh tokens from the store.
Flush sessions methods can be used to perform logout.
Refresh token or refresh token UID is required to flush a session.
To logout with an access token,refresh_by_access_allowed should be set to true on access token creation. If logout by access token is allowed it is recommended to ignore the expiration claim and to allow to logout with the expired access token.

Examples

Rails API
Sinatra API

You can use a mixed approach for the cases when you would like to store an access token in localStorage and refresh token in HTTP-only secure cookies.
Rails controllers setup example:

classLoginController <ApplicationControllerdefcreateuser=User.find_by(email:params[:email])ifuser&.authenticate(params[:password])payload={user_id:user.id,role:user.role,permissions:user.permissions}refresh_payload={user_id:user.id}session=JWTSessions::Session.new(payload:payload,refresh_payload:refresh_payload)tokens=session.loginresponse.set_cookie(JWTSessions.refresh_cookie,value:tokens[:refresh],httponly:true,secure:Rails.env.production?)renderjson:{access:tokens[:access],csrf:tokens[:csrf]}elserenderjson:"Cannot login",status::unauthorizedendendendclassRefreshController <ApplicationControllerbefore_action:authorize_refresh_request!defcreatetokens=JWTSessions::Session.new(payload:access_payload).refresh(found_token)renderjson:{access:tokens[:access],csrf:tokens[:csrf]}enddefaccess_payloaduser=User.find_by!(email:payload["user_id"]){user_id:user.id,role:user.role,permissions:user.permissions}endendclassResourcesController <ApplicationControllerbefore_action:authorize_access_request!before_action:validate_role_and_permissions_from_payload# ...end

Contributing

Fork & Pull Request.
RbNaCl and sodium cryptographic library are required for tests.

For MacOS seethese instructions.
For example, with Homebrew:

brew install libsodium

License

MIT


[8]ページ先頭

©2009-2025 Movatter.jp