So, i found solution and it works.
0)
Code: Select all
#define AUTH_COOKIE_KEY "auth-token"
1) Create struct
Code: Select all
typedef struct
{
uint64_t timestamp;
uint8_t fd;
} um_webserver_token_t;
static um_webserver_token_t auth_token;
2) Create basic methods, that operates with token
Code: Select all
/**
* Get user token from request
*
* @param char out
*
* @return void
*/
static void um_webserver_get_auth_token(httpd_req_t *req, char *out)
{
size_t size = 36;
httpd_req_get_cookie_val(req, AUTH_COOKIE_KEY, out, &size);
}
/**
* Add user token to token store
*
* @return void [return description]
*/
static void um_webserver_add_auth_user(um_webserver_token_t token)
{
auth_token.fd = token.fd;
auth_token.timestamp = token.timestamp;
}
/**
* Delete user token from token store
*
* @return void
*/
static void um_webserver_delete_user_token(httpd_req_t *req)
{
auth_token.fd = 0;
auth_token.timestamp = 0;
}
3) In login http handler
Code: Select all
if (strcmp(password, nvs_password) == 0 && strcmp(username, nvs_username) == 0)
{
success = true;
// Add user token to store
char token[36];
um_webserver_token_t user_token = {
.fd = httpd_req_to_sockfd(req),
.timestamp = esp_timer_get_time()};
um_webserver_add_auth_user(user_token);
sprintf(token, AUTH_COOKIE_KEY "=%lld:%d; Path=/; HttpOnly", user_token.timestamp, user_token.fd);
// Send cookie header to browser
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie
httpd_resp_set_hdr(req, "Set-Cookie", token);
}
4) In private handlers use
Code: Select all
static esp_err_t some_private_method(httpd_req_t *req)
{
httpd_resp_set_type(req, "application/json");
if (um_webserver_is_authenticated(req))
{
// Your code
}
return ESP_OK;
}
When the user is logged in successfully - we send cookie to browser. Browser remember that cookie and send back to server. Server will check cookie in private request.