针对 SPA 设计的 XSS/CSRF 安全 JWT 身份验证
XSS/CSRF safe JWT auth designed for SPA
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.
Put this line in your Gemfile:
gem "jwt_sessions"Then run:
bundle installYou should configure an algorithm and specify the signing key. By default the gem uses the HS256 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.
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)
=> #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 call login 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=>"..."}Available JWTSessions::Session.new options:
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.Helper methods within Authorization mixin:
Include JWTSessions::RailsAuthorization in your controllers and add JWTSessions::Errors::Unauthorized exception handling if needed.
class ApplicationController 1Flush a session by its access token:
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_payloadOr by refresh token UID:
session.flush_by_uid(uid) # => 1It'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 namespaceSelectively 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 namespaceFlush 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 tokensForce flush of all app sessions:
JWTSessions::Session.flush_allTo 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.
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:
…Fork & Pull Request.
RbNaCl and sodium cryptographic library are required for tests.
For MacOS see these instructions.
For example, with Homebrew:
brew install libsodiumMIT
暂无开放 Issues,或尚未同步最近议题。