Authentication

PieSocket Channels are easy to use by design but this brings its own problems. Anyone with your API key (which is public by nature, unlike secret key) can exhaust your quota, or view data going in and out. You can solve this problem by enabling authentication for your API keys.

Enable Authentication

Log in to your PieSocket dashboard and then go to API Keys section.

You will find a settings icon next to the desired API key, click it to open settings, and enable authentication.

Authentication is only available on paid plans.

How To Authenticate

Once you have enabled authentication for an API key, it will throw following error and disconnect automatically when you try to connect.

{danger.fa-close} {"error":"Authentication failed, provide valid jwt token."}

You need to add a JWT token to the request to authenticate the user for access of the PieSocket channel.

JWT Token

There are two ways to send the JWT token with the WebSocket request.

Method Key Example
Query Param jwt wss://demo.piesocket.com/v3/1?api_key=xxx&jwt=JWT_TOKEN
Header jwt Host: demo.piesocket.com; jwt: JWT_TOKEN

Generating JWT Token

You need to generate a valid JWT token on your server using the API Secret.

Use following payload to generate your JWT token with HS256 encryption algorithm and sign it using your API secret key.

{
  "sub": CHANNEL_ID,  
  "iat": ISSUED_TIME, 
  "exp": EXPIRY_TIME
}

It is possible to generate JWT token online for testing purpose with JWT.io

{danger.fa-close} This token is only valid for the Channel ID specified in sub key of the token payload. You need to create a separate JWT token for a different channel.

Generating JWT on your server

You can generate JWT tokens on your server using any programming language. Following are a few reference links:

# Programming Language Library
1 PHP firebase/php-jw
2 Python PyJWT
3 NodeJS jsonwebtoken
4 Go jwt-go
5 Ruby ruby-jwt

You can find a JWT library for any language by typing in "Language name JWT library" in google.

Identifying A User

If you wish to identify an user or send notifications to one specific user over the WebSocket, you can make use of channel IDs suffixed/prefixed with the user ID on your database.

For example, let all users on your website join user_123 channel where 123 is their ID. Now if you want to send notification to user 456, you can publish a messge on the user_456 channel. Since you are using Authentication with JWT, users can not join each other's channels without your server issusing them a JWT token.