Use Authentication from JavaScript

Learn how to use authentication from JavaScript.

Adding authentication

Clients that connect to our secured Socket must pass the authentication parameters on connection. Phoenix’s JavaScript client provides a simple way to add the proper authentication parameters.

We wrote an AuthSocket that accepts a “token” parameter and verifies it using a known secret. We’ll complete the client-side of this flow by including the token with the Socket connection. This task boils down to a few essential parts:

  • The controller generates a token when our page loads and writes it into the page’s JavaScript.

  • JavaScript sends the token parameter with the Socket connection.

  • The Socket uses the token in our Socket.

JavaScript authentication

We’ll generate an authentication token in the Controller that renders our page view. We’ve worked entirely in the default generated files so far, meaning we haven’t even looked at the Controller yet, but our change will not be very complex. Replace the existing index/2 function with the following code:

Get hands-on with 1200+ tech skills courses.