nginx RTMP Streaming With Simple Authentication

Sun, Dec 10, 2017

I’ve been looking for a simple way to utilize RTMP streaming with OBS Studio without having to resort to bloated websites like twitch. RTMP streams you can just play using your media player of choice (usually), for example VLC. In addition this can be useful to collaborate with colleagues, as you can stream not just a single window but also your whole desktop. nginx has access to a RTMP module (surprisingly called nginx-rtmp-module ^^) which they say does not do authentication but just the streaming. However, it features certain event calls like on_publish or on_play. After digging into it for a bit there is actually a super easy way to do a very simple authentication scheme which could be extended by any script you like.

All you need is first the RTMP block in your nginx config file:

rtmp {
  server {
    listen 1935;
	ping 30s;
	notify_method get;
			  
	application stream {
	  live on;
      on_publish http://localhost[:port]/auth;
      on_play http://localhost[:port]/auth;
	  record off;
	}
  }
}

This just sets up the stream and then forces to trigger a certain url on_publish (i.e. if someone wants to stream to the server) and on_play (i.e. someone trying to play back the stream). Now, the stream or play request will only be accepted if the url given returns a HTTP 2xx status code, else the connection will be dropped.

We can work this to our advantage and just set up a quick and dirty server in the http section of nginx that directly checks for a given secret:

server {
  listen <port>;
  location /auth {
  if ($arg_psk = 'totallysecretpassword') {
    return 201;
  }
  return 404;
}

You could also implement multiple urls with different secrets for streaming and playing or you could let a script of your choosing answer the url request and check for a username and a password or id in a database. Once all is done you can access the stream via rtmp://host.tld/stream/user?psk=totallysecretpassword. Of course this sends your password via plaintext so you should take precautions and if your software supports it use rtmp via ssl/TLS.

UPDATE: there is now a followup article on how to realize a slightly more sophisticated authentication setup