Authentication using FrontQL
Introduction
In modern web applications, securing user data and ensuring that access is granted only to authorized users is paramount. Authentication is the process that verifies the identity of a user, and with FrontQL, integrating authentication into your application can be both seamless and robust.
FrontQL simplifies the interaction with your Backend API, providing a set of tools and methods to handle authentication effectively. By leveraging FrontQL, you can implement authentication seamlessly, which includes issuing and validating JWT (JSON Web Tokens).
Key Concepts
Before we dive into the code, let’s go over a few key concepts that are crucial for understanding authentication with FrontQL:
- Authentication vs Authorization: Authentication verifies who the user is, while authorization determines what resources the user can access.
- Tokens: Tokens are encrypted strings that the server generates upon successful login. These tokens are then used to make authenticated requests.
- JWT (JSON Web Tokens): A popular type of token that contains encoded JSON objects, including a set of claims. JWTs are used in token-based authentication to pass the identity of authenticated users between the client and the server.
Implementing Authentication
Implementing authentication with FrontQL typically involves the following steps:
- User Login: Users provide their credentials (such as username and password) which are sent to the server, along with the required fields (such as id, name, email, role etc.).
- Token Generation: Upon successful authentication, the server generates a token and sends it back to the client.
- Storing the Token: The client stores the token, usually in local storage or a cookie.
- Making Authenticated Requests: For subsequent requests, the client attaches the token throught the
session
parameter. - Token Validation: The server validates the token with each request and grants or denies access to the requested resources.
Important Notes
- The HTTP request has to be POST request.
- The url must be prefix with
/auth-
for authentication.
Example
Here’s a simple example of implementing authentication using FrontQL:
async function login() { const response = await Api.post("/auth-users", { // users can be replaced with any name of the collection body: { username: "john", password: "password", }, fields: "id,name,email,role", });
return response;};
async function login() { const url = `${BASE_URL}/auth-users`; // Replace BASE_URL with the base URL of API server and users can be replaced with any name of the collection const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", fields: "id,name,email,role", app: DATABASE, // Replace DATABASE with the name of your database token: TOKEN, // Replace TOKEN with the token // OR // Authorization: `Bearer ${AUTH_TOKEN}`, // Replace AUTH_TOKEN with the authorization token, }, body: JSON.stringify({ username: "john", password: "password", }) });
const data = await response.json(); return data;};
Output
This example takes the user’s credentials from the request body and returns the user’s details along with a token.
{ "err": false, "result": { "id": 1, "name": "John Doe", "role": "admin" }, "session": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkpvaG4iLCJlbWFpbCI6ImFkbWluQGdtYWlsLmNvbSIsImlhdCI6MTY3MjMxNjMxN30.8q8Ks9yFVnQp9Y5Z5QI6pJcBbIjJpJlM"}
Using The Session
We can use the session
in the following way:
-
To filter the data for a specific user:
async function getUser() {const response = await Api.get("/users", {filter: "id:{id}",session:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkpvaG4iLCJlbWFpbCI6ImFkbWluQGdtYWlsLmNvbSIsImlhdCI6MTY3MjMxNjMxN30.8q8Ks9yFVnQp9Y5Z5QI6pJcBbIjJpJlM",});return response;}This will return only the user with the specified id.
-
To insert a data for a specific user:
async function savePost() {const response = await Api.post("/posts", {body: {title: "Post Title",body: "Post Body",},filter: "user:{id}",session:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkpvaG4iLCJlbWFpbCI6ImFkbWluQGdtYWlsLmNvbSIsImlhdCI6MTY3MjMxNjMxN30.8q8Ks9yFVnQp9Y5Z5QI6pJcBbIjJpJlM",});return response;}This will create a new post for the user with the specified id.
-
In SQL queries:
async function getUsers() {const response = await Api.sql("/users", {body: {sql: "SELECT * FROM users WHERE id=?",params: ["{id}"],},session:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkpvaG4iLCJlbWFpbCI6ImFkbWluQGdtYWlsLmNvbSIsImlhdCI6MTY3MjMxNjMxN30.8q8Ks9yFVnQp9Y5Z5QI6pJcBbIjJpJlM",});return response;}
-
To filter the data for a specific user:
async function getUser() {const url = `${BASE_URL}/users`;const response = await fetch(url, {method: "GET",headers: {"Content-Type": "application/json",filter: "id:{id}",session:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkpvaG4iLCJlbWFpbCI6ImFkbWluQGdtYWlsLmNvbSIsImlhdCI6MTY3MjMxNjMxN30.8q8Ks9yFVnQp9Y5Z5QI6pJcBbIjJpJlM",app: DATABASE, // Replace DATABASE with the name of your databasetoken: TOKEN, // Replace TOKEN with the token// OR// Authorization: `Bearer ${AUTH_TOKEN}`, // Replace AUTH_TOKEN with the authorization token},});const data = await response.json();return data;}This will return only the user with the specified id.
-
To insert a data for a specific user:
async function savePost() {const url = `${BASE_URL}/posts`;const response = await Api.post(url, {method: "POST",headers: {"Content-Type": "application/json",filter: "user:{id}",session:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkpvaG4iLCJlbWFpbCI6ImFkbWluQGdtYWlsLmNvbSIsImlhdCI6MTY3MjMxNjMxN30.8q8Ks9yFVnQp9Y5Z5QI6pJcBbIjJpJlM",app: DATABASE, // Replace DATABASE with the name of your databasetoken: TOKEN, // Replace TOKEN with the token// OR// Authorization: `Bearer ${AUTH_TOKEN}`, // Replace AUTH_TOKEN with the authorization token},body: JSON.stringify({title: "Post Title",body: "Post Body",}),});return response;}This will create a new post for the user with the specified id.
-
In SQL queries:
async function getUsers() {const url = `${BASE_URL}/sql-users`;const response = await Api.sql(url, {method: "POST",headers: {'Content-Type': 'application/json',session:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkpvaG4iLCJlbWFpbCI6ImFkbWluQGdtYWlsLmNvbSIsImlhdCI6MTY3MjMxNjMxN30.8q8Ks9yFVnQp9Y5Z5QI6pJcBbIjJpJlM",app: DATABASE, // Replace DATABASE with the name of your databasetoken: TOKEN, // Replace TOKEN with the token// OR// Authorization: `Bearer ${AUTH_TOKEN}`, // Replace AUTH_TOKEN with the authorization token}body: JSON.stringify({sql: "SELECT * FROM users WHERE id=?",params: ["{id}"],}),});return response;}