All Projects → BinarCode → laravel-stateless-session

BinarCode / laravel-stateless-session

Licence: MIT license
CSRF verification and session persistent through request/response headers.

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to laravel-stateless-session

Aura.session
Tools for managing sessions, including session segments and read-once messages
Stars: ✭ 185 (+460.61%)
Mutual labels:  session, csrf
CSRF-tutorial
Use Django To Introduce CSRF and Cookies , Session 📝
Stars: ✭ 49 (+48.48%)
Mutual labels:  session, csrf
Akka Http Session
Web & mobile client-side akka-http sessions, with optional JWT support
Stars: ✭ 429 (+1200%)
Mutual labels:  session, csrf
Php Serialize
Use PHP's serialization methods from Ruby.
Stars: ✭ 119 (+260.61%)
Mutual labels:  session
Curiefense
Curiefense is a unified, open source platform protecting cloud native applications.
Stars: ✭ 136 (+312.12%)
Mutual labels:  session
Wwdc
You don't have the time to watch all the WWDC session videos yourself? No problem me and many contributors extracted the gist for you 🥳
Stars: ✭ 2,561 (+7660.61%)
Mutual labels:  session
dialectic
Transport-polymorphic, asynchronous session types for Rust
Stars: ✭ 60 (+81.82%)
Mutual labels:  session
Slim Session
A very simple session middleware for Slim Framework 2/3/4.
Stars: ✭ 200 (+506.06%)
Mutual labels:  session
Nodesession
Session handling for NodeJS
Stars: ✭ 111 (+236.36%)
Mutual labels:  session
Thinkgo
A lightweight MVC framework written in Go (Golang).
Stars: ✭ 184 (+457.58%)
Mutual labels:  session
hutplate
A Go library over standard net/http library with auth, session, err handling and more.
Stars: ✭ 28 (-15.15%)
Mutual labels:  session
Tlog
Terminal I/O logger
Stars: ✭ 170 (+415.15%)
Mutual labels:  session
Redux React Session
🔑 Simple Session API storage for Redux and React
Stars: ✭ 140 (+324.24%)
Mutual labels:  session
mst-persist
Persist and hydrate MobX-state-tree stores (in < 100 LoC)
Stars: ✭ 75 (+127.27%)
Mutual labels:  session
Cash
HTTP response caching for Koa. Supports Redis, in-memory store, and more!
Stars: ✭ 122 (+269.7%)
Mutual labels:  session
SanSessionToolbar
⚡ Session Toolbar that can be applied into Zend/Laminas DeveloperTools
Stars: ✭ 39 (+18.18%)
Mutual labels:  session
Ibase4j
Spring,SpringBoot 2.0,SpringMVC,Mybatis,mybatis-plus,motan/dubbo分布式,Redis缓存,Shiro权限管理,Spring-Session单点登录,Quartz分布式集群调度,Restful服务,QQ/微信登录,App token登录,微信/支付宝支付;日期转换、数据类型转换、序列化、汉字转拼音、身份证号码验证、数字转人民币、发送短信、发送邮件、加密解密、图片处理、excel导入导出、FTP/SFTP/fastDFS上传下载、二维码、XML读写、高精度计算、系统配置工具类等等。
Stars: ✭ 1,548 (+4590.91%)
Mutual labels:  session
sessions
A non-blocking session handler for PHP
Stars: ✭ 23 (-30.3%)
Mutual labels:  session
secure-cookie
Secure cookies and sessions for WSGI
Stars: ✭ 30 (-9.09%)
Mutual labels:  session
rust cms
使用Rust编写一个CMS(内容管理系统)可以做为个人博客,公司网站
Stars: ✭ 32 (-3.03%)
Mutual labels:  session

CSRF verification and session persistent through request/response headers.

This is a lightweight package which allow you to manage a session in a stateless communication (REST/API) when the API domain and main web application domain are different.

E.g.

  • API hosted under: api.foo.com
  • WEB hosted under: tenant1.com, tenant2.com etc.

In that case you cannot set cookie for different main domains

See why you cannot set cookie under different domain.

Installation

You can install the package via composer:

composer require binarcode/laravel-stateless-session

Usage

  1. Trigger session, make a GET request to: /api/csrf-header. This will return a header with the session key and an optional header with CSRF token XSRF-TOKEN. The header name could be configured in: stateless.header

  2. Use this header session key/value for every request you want to take care of the session.

  3. If you want to benefit of the CSRF protection of your requests, you should add the follow middlewares to your routes:

use Binarcode\LaravelStatelessSession\Http\Middleware\StatelessStartSession;
use Binarcode\LaravelStatelessSession\Http\Middleware\StatelessVerifyCsrfToken;

->middleware([
    StatelessStartSession::class,
    StatelessVerifyCsrfToken::class,
]);

You can create a middleware group in your Http\Kernel with these 2 routes as:

protected $middlewareGroups = [
// ...
    'stateless.csrf' => [
        StatelessStartSession::class,
        StatelessVerifyCsrfToken::class,
    ],
// ...
]

Now the server will return 419 (Page expired code).

Unless you send back a request header named: X-CSRF-TOKEN with the value received by the first GET request in the XSRF-TOKEN header.

Done.

  • At this point you have CSRF protection.

  • And you can play with SessionManager and use the session() helper to store/get information (e.g. flash sessions).

Config

The lifetime and other options could be set as before in the session file.

The VerifyHeaderCsrfToken and StartStatelessSession middlewares will inject into headers the session key.

The session key name could be configured in the:

stateless.header => env('STATELESS_HEADER', 'X-STATELESS-HEADER')

Danger: The key name separators should use - not _ according with this.

You can customize the middleware for the csrf-header route. In some cases you may need some custom cors middleware for example:

stateless.middleware => [ 
    \Barryvdh\Cors\HandleCors::class,
]

Real use case

Let's say you want to allow visitors to submit a newsletter form. You want also to protect your API with CSRF.

You can setup a GoogleRecaptcha for that, but that's so annoying.

Solution:

Vue newsletter page:

// Newsletter.vue
{
    async created() {
        const response = await axios.get(`${host}/api/csrf-header`);
        this.csrfToken =  response.headers['XSRF-TOKEN'];
        this.sessionKey =  response.headers['LARAVEL-SESSION'];
    },
    methods: {
    
        async subscribe() {
            await axios.post(`${host}/api/newsletter`, {email: '[email protected]'}, {
                headers: { 
                    'LARAVEL-SESSION': this.sessionKey, 
                    'X-CSRF-TOKEN': this.csrfToken
                }
            });
        }   
        
    }
}

api.php

Route::post('api/subscribe', function (Request $request) {

    // at this point the CSRF token is verified 

    Subscribers::createFromEmail($request->get('email'));

    return response('', 201)->json();

})->middleware([
    StartStatelessSession::class,
    VerifyHeaderCsrfToken::class,
]);

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

Since the Session Key and X-CSRF-TOKEN could be read by the JavaScript code, that means it's less secure than a usual http-only Cookie. But since we have different domains for the API and WEB, we don't have a way to setup a cookie. You can think of this as of the Bearer token. The security impact is exactly the same.

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].