WebSocketServerHttpHeaderValidation.ino 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * WebSocketServerHttpHeaderValidation.ino
  3. *
  4. * Created on: 08.06.2016
  5. *
  6. */
  7. #include <Arduino.h>
  8. #include <ESP8266WiFi.h>
  9. #include <ESP8266WiFiMulti.h>
  10. #include <WebSocketsServer.h>
  11. #include <Hash.h>
  12. ESP8266WiFiMulti WiFiMulti;
  13. WebSocketsServer webSocket = WebSocketsServer(81);
  14. #define USE_SERIAL Serial1
  15. const unsigned long int validSessionId = 12345; //some arbitrary value to act as a valid sessionId
  16. /*
  17. * Returns a bool value as an indicator to describe whether a user is allowed to initiate a websocket upgrade
  18. * based on the value of a cookie. This function expects the rawCookieHeaderValue to look like this "sessionId=<someSessionIdNumberValue>|"
  19. */
  20. bool isCookieValid(String rawCookieHeaderValue) {
  21. if (rawCookieHeaderValue.indexOf("sessionId") != -1) {
  22. String sessionIdStr = rawCookieHeaderValue.substring(rawCookieHeaderValue.indexOf("sessionId=") + 10, rawCookieHeaderValue.indexOf("|"));
  23. unsigned long int sessionId = strtoul(sessionIdStr.c_str(), NULL, 10);
  24. return sessionId == validSessionId;
  25. }
  26. return false;
  27. }
  28. /*
  29. * The WebSocketServerHttpHeaderValFunc delegate passed to webSocket.onValidateHttpHeader
  30. */
  31. bool validateHttpHeader(String headerName, String headerValue) {
  32. //assume a true response for any headers not handled by this validator
  33. bool valid = true;
  34. if(headerName.equalsIgnoreCase("Cookie")) {
  35. //if the header passed is the Cookie header, validate it according to the rules in 'isCookieValid' function
  36. valid = isCookieValid(headerValue);
  37. }
  38. return valid;
  39. }
  40. void setup() {
  41. // USE_SERIAL.begin(921600);
  42. USE_SERIAL.begin(115200);
  43. //Serial.setDebugOutput(true);
  44. USE_SERIAL.setDebugOutput(true);
  45. USE_SERIAL.println();
  46. USE_SERIAL.println();
  47. USE_SERIAL.println();
  48. for(uint8_t t = 4; t > 0; t--) {
  49. USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
  50. USE_SERIAL.flush();
  51. delay(1000);
  52. }
  53. WiFiMulti.addAP("SSID", "passpasspass");
  54. while(WiFiMulti.run() != WL_CONNECTED) {
  55. delay(100);
  56. }
  57. //connecting clients must supply a valid session cookie at websocket upgrade handshake negotiation time
  58. const char * headerkeys[] = { "Cookie" };
  59. size_t headerKeyCount = sizeof(headerkeys) / sizeof(char*);
  60. webSocket.onValidateHttpHeader(validateHttpHeader, headerkeys, headerKeyCount);
  61. webSocket.begin();
  62. }
  63. void loop() {
  64. webSocket.loop();
  65. }