The source code example

JWT-RESTfull-IN-CI-Tutorial

Simulating business scenarios

In the last post, we have done enough preparation and laid out specific business scenarios:

1. The TOKEN is generated after the user logs in successfully.

2. Every time the client performs CRUD operations on the TODO model, it carries the TOKEN.

3. The server verifies the validity of the TOKEN and responds to the request and performs database operations.

There will be no form validation, registration logic for the rest of the coding, because this article is just describing how to integrate a CI into a JWT RESTfull API Repo.

Define the model

application/modles/User_model.php

In the User model, a simple login method is used to compare whether the account password is correct. We just simulate the HTTP request for real database operations:

Since there is no written registration logic, you should add a user to the database in advance, such as:

application/models/Todo_model.php

In Todo model, add, delete, modify, query a single record, query all records and other operations:

Authorization auxiliary class

Since the production and verification of tokens come from methods in JWT class, we can encapsulate our “auxiliary classes” in CI to make it more convenient to use JWT class. In general, CI puts customized auxiliary classes in application/helpers/.

In this auxiliary class, JWT is introduced and two methods are encapsulated in the Authorization class:

1. Func validateToken: used to verify the validity of the TOKEN.

2. Func generateToken: used to produce tokens;

Autoload configuration items

$this->load>library(‘database’); $this->load>library(‘database’); We can configure specific libraries, helpers, and so on directly into Autoload that need to be automatically loaded.

Auth controller

With that in mind, it’s time to write the first controller and complete scenario 1: the client sends the POST request, the server passes the username & Password parameters, verifies the validity of the parameters, produces the TOKEN, and returns it to the client.

Next, we need to simulate the “Get TOKEN” POST request on the client side.

Open a tool dedicated to testing your interface, such as Postman, which I used here apizza: apizza.cc/

As in the previous article, we use PHP -s localhost:8000, type the command in the root directory, get the project up and running, and simulate our request in Apizza:

If the account password passed by the client does not exist, the server should return the status code 401 Unauthorized:

Todo controller

The controller gives an API for CURD operations on the Todo model. Typically, the server API URL should look something like this: http://example.com/api/, CI upgrade to 3.* controller supports multilevel directory structure, now let’s create Todo controller:

The four method names correspond to the four request modes: GET, POST, PUT, and DELETE.

1. A POST request

Todo is still an empty table, so we start with a POST request, which is usually used to create resources:

On success, the interface will return the 200 status code and the newly created TODO record will be returned as data. Now we make several requests for the API to insert three records into the database for us:

2. GET request

Now that there are three records in the table, write a GET request to obtain the resource. The server checks whether there is an ID parameter in the URL. If there is an ID parameter, return the single data of the ID. To actually develop your throw you need to fill in these logics:

Single record:

All records:

3. PUT request

PUT is usually used to modify a specified resource:

4. DELETE the request

DELETE Deletes a specified resource:

Hook function

At this point, our entire API is written.

The next and final step is to add a hook function that verifies whether the request header contains the TOKEN and validates it in the hook function before the API controller calls the method.

1. First of all, we need to open the application/config/config. PHP, open hooks:

2. Specify the hooks

There are seven hooks for CI, and we choose Post_controller_constructor, which executes immediately after your controller has been instantiated without any of its methods being called. We still need to specify the custom hook class we are going to use and the name of the function to execute in the hook configuration:

3. Write ApiAuthHook

Protect the routing

When we access either API request again, the server will respond with an Error Code of 400:

Remember the first AUth /token/ POST request? The request to the server returns a TOKEN, such as: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9. EyJpZCI6IjEifQ. RpPLzNRB1nK_N_Ch7eSvJCpwFKwEWyNozS67RE6eaUU

Now we add Authorization to the request header and set its value to TOKEN:

Cool! The interface returned all data normally!

Why lovchun.com in front of TOKEN value?

The front-end needs to store tokens through cookies or localStorage to save the credentials that call the interface.

Imagine if your front-end engineering needs to connect to multiple API servers. How do you identify which Server the TOKEN corresponds to?

The Authorization value is stored as “Unique identifier” + “one English space” + “TOKEN”. During server verification, the TOKEN can be obtained by searching the Authorization of the “unique identifier” (of course, you can customize this identifier) :


If you start your project as Apache or another Web Server, Apache filters out the Authorization field in the request header!

Please modify it in the.htaccess file in the root directory so that your Apache can receive Authorization normally: