Added a simple csrf token middleware.

This commit is contained in:
Relintai 2022-01-09 15:25:55 +01:00
parent 4c6e02d07f
commit 8e903f2695
4 changed files with 95 additions and 0 deletions

49
core/http/csrf_token.cpp Normal file
View File

@ -0,0 +1,49 @@
#include "csrf_token.h"
#include "core/hash/sha256.h"
#include "http_session.h"
#include "request.h"
bool CSRFTokenMiddleware::on_before_handle_request_main(Request *request) {
switch (request->get_method()) {
case HTTP_METHOD_POST:
case HTTP_METHOD_DELETE:
case HTTP_METHOD_PATCH:
case HTTP_METHOD_PUT: {
if (!request->session.is_valid()) {
request->send_error(HTTP_STATUS_CODE_401_UNAUTHORIZED);
return true;
}
if (!request->validate_csrf_token()) {
request->send_error(HTTP_STATUS_CODE_401_UNAUTHORIZED);
return true;
}
break;
}
default:
break;
}
// don't create the session itself
if (!request->session.is_valid()) {
return false;
}
if (!request->has_csrf_token()) {
request->set_csrf_token(create_token());
}
return false;
}
String CSRFTokenMiddleware::create_token() {
return "test";
}
CSRFTokenMiddleware::CSRFTokenMiddleware() {
}
CSRFTokenMiddleware::~CSRFTokenMiddleware() {
}

21
core/http/csrf_token.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef CSRF_TOKEN_H
#define CSRF_TOKEN_H
#include "middleware.h"
class Request;
class CSRFTokenMiddleware : public Middleware {
RCPP_OBJECT(CSRFTokenMiddleware, Middleware);
public:
//returnring true means handled, false means continue
bool on_before_handle_request_main(Request *request);
virtual String create_token();
CSRFTokenMiddleware();
~CSRFTokenMiddleware();
};
#endif

View File

@ -40,6 +40,29 @@ String Request::get_csrf_token() {
return ""; return "";
} }
void Request::set_csrf_token(const String &value) {
if (session.is_valid()) {
session->add("csrf_token", value);
}
}
bool Request::validate_csrf_token() {
String param_token = get_parameter("csrf_token");
param_token.trim();
if (param_token == "") {
return false;
}
String token = get_csrf_token();
if (token == "") {
return false;
}
return param_token == token;
}
const String Request::get_cookie(const String &key) { const String Request::get_cookie(const String &key) {
static String str(0); static String str(0);
return str; return str;

View File

@ -42,6 +42,8 @@ public:
bool has_csrf_token(); bool has_csrf_token();
String get_csrf_token(); String get_csrf_token();
void set_csrf_token(const String &value);
bool validate_csrf_token();
virtual const String get_cookie(const String &key); virtual const String get_cookie(const String &key);
virtual void add_cookie(const ::Cookie &cookie); virtual void add_cookie(const ::Cookie &cookie);