Articles on: Developers

How do I get the user id from the API calls?

This article applies only if your plugin on PluginLab implements a user-http or a oAuth authentication scheme. You can get more information about how to authenticate your users here.

It's a great time to remind how PluginLab works.

PluginLab acts as a proxy layer between your backend API and ChatGPT.

This allows us to proceed with various checks, track your events, provide multiple features and last but not least garantee your users are authenticated.


PluginLab proxy schema


So, as this graphic shows PluginLab will always send you at least two HTTP headers that will be useful for you:

X-PluginLab-Event-Id: the unique id of the event request
Authorization: the authorization bearer containing the ID Token you can use to verify and get the user's info.


Once decoded, the Authorization token will provide you the following info:
The user id
The user email
The user name (if any)
The user plan and price ids (if any)


Extract the Authorization Payload / Verify the token signature



The id token is a JWT. It means the payload is base64 encoded. However, you should not trust the content of the payload unless you verify the token's signature.

The easiest way to verify the signature is to use one of our SDK:
- NodeSDK
- PythonSDK

If you're using another language you can check this article to get more information about the token verification.


How to get the token from headers?



The Authorization token will be sent in the Authorization Header. Here are some ways you can get it based on multiple web frameworks.


Using Python (Flask)



from flask import Flask, request

app = Flask(__name__)

@app.route('/example', methods=['GET'])
def get_headers():
    event_id = request.headers.get('X-PluginLab-Event-Id')
    authorization = request.headers.get('Authorization')

    # Use the extracted header values as needed
    # ...

    return "Headers extracted successfully"

if __name__ == '__main__':
    app.run()



Using NodeJs (Express)



This is a basic example in node, altough we suggest you use our NodeJs SDK

const express = require('express');
const app = express();

app.get('/example', (req, res) => {
  const event_id = req.headers['x-pluginlab-event-id'];
  const authorization = req.headers['authorization'];

  // Use the extracted header values as needed
  // ...

  res.send('Headers extracted successfully');
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});



Using Go



package main

import (
	"fmt"
	"log"
	"net/http"
)

func exampleHandler(w http.ResponseWriter, r *http.Request) {
	eventID := r.Header.Get("X-PluginLab-Event-Id")
	authorization := r.Header.Get("Authorization")

	// Use the extracted header values as needed
	// ...

	fmt.Fprint(w, "Headers extracted successfully")
}

func main() {
	http.HandleFunc("/example", exampleHandler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}



Using Rust (Rocket)



#[macro_use]
extern crate rocket;

use rocket::http::Header;

#[get("/example")]
fn example(headers: &Header<'_>) -> &'static str {
    let event_id = headers.get_one("X-PluginLab-Event-Id").unwrap_or("");
    let authorization = headers.get_one("Authorization").unwrap_or("");

    // Use the extracted header values as needed
    // ...

    "Headers extracted successfully"
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![example])
}



Using PHP



<?php

$event_id = $_SERVER['HTTP_X_PLUGINLAB_EVENT_ID'];
$authorization = $_SERVER['HTTP_AUTHORIZATION'];

// Use the extracted header values as needed
// ...

echo "Headers extracted successfully";
?>



Using Java (Spring Boot)



import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class Application {

    @GetMapping("/example")
    public String example(
        @RequestHeader("X-PluginLab-Event-Id") String eventId,
        @RequestHeader("Authorization") String authorization
    ) {
        // Use the extracted header values as needed
        // ...

        return "Headers extracted successfully";
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Updated on: 27/07/2023

Was this article helpful?

Share your feedback

Cancel

Thank you!