百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
J

jwt_sessions

> 安全
开源

针对 SPA 设计的 XSS/CSRF 安全 JWT 身份验证

596 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

针对 SPA 设计的 XSS/CSRF 安全 JWT 身份验证

jwt_sessions

XSS/CSRF safe JWT auth designed for SPA

Table of Contents

  • Synopsis
  • Installation
  • Getting Started
    • Creating a session
    • Rails integration
    • Non-Rails usage
  • Configuration
    • Token store
    • JWT signature
    • Request headers and cookies names
    • Expiration time
    • Exceptions
    • CSRF and cookies
      • Refresh with access token
    • Refresh token hijack protection
  • Flush Sessions - Sessions namespace - Logout
  • Examples
  • Contributing
  • License

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 behind jwt_sessions is that each session is represented by a pair of tokens: access and refresh. 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 by ruby-jwt gem. Its reserved claim names are supported and it can configure claim checks and cryptographic signing algorithms supported by it. jwt_sessions itself uses ext claim and HS256 signing by default.

Installation

Put this line in your Gemfile:

ruby
gem "jwt_sessions"

Then run:

bundle install

Getting Started

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

ruby
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.

ruby
> 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.

ruby
> session = JWTSessions::Session.new(payload: payload)
=> #

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.

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

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

ruby
> 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:

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

Available JWTSessions::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 with JWT 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. See token_claims method.
  • refresh_claims: a hash object with JWT 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 info Sessions 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. See Refresh with access token.
  • access_exp: an integer value. Contains an access token expiration time in seconds. The value overrides global settings. See Expiration time.
  • refresh_exp: an integer value. Contains a refresh token expiration time in seconds. The value overrides global settings. See Expiration time.

Helper methods within Authorization 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

Include JWTSessions::RailsAuthorization in your controllers and add JWTSessions::Errors::Unauthorized exception handling if needed.

ruby
class ApplicationController  1

Flush a session by its access token:

ruby
session = JWTSessions::Session.new(refresh_by_access_allowed: true)
tokens = session.login
session.flush_by_access_payload
# or
session = JWTSessions::Session.new(refresh_by_access_allowed: true, payload: payload)
session.flush_by_access_payload

Or by refresh token UID:

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

It's possible to group sessions by custom namespaces:

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

Selectively flush sessions by namespace:

ruby
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:

ruby
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:

ruby
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:

ruby
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:

…

Contributing

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

For MacOS see these instructions.
For example, with Homebrew:

bash
brew install libsodium

License

MIT

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyaccess-tokenapiauthcsrf-token

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类安全
定价开源

> 相关工具

O
OWASP ZAP
开源 Web 应用安全扫描器
O
owasp-wstg-tracker
Simple web app to track OWASP WSTG security testing progress
H
homebridge-mi-gateway-security
XiaoMi Gateway Security plugin for HomeBridge.