PHP JWT Authentication Tutorial

In this tutorial, we’ll learn how to add JWT authentication to our REST API PHP application.
We’ll see what JWT is and how it works. We’ll also see how to get the authorization header in PHP. What is JWT
JWT stands for JSON Web Token and comprised of user encrypted information that can be used to authenticate users and exchange information between clients and servers. When building REST API, instead of server sessions commonly used in PHP apps we tokens which are sent with HTTP headers from the server to clients where they are persisted (usually using local storage) then attached to every outgoing request originating from the client to the server. The server checks the token and allow or deny access to the request resource. RESTful APIs are stateless. This means that requests from clients should contain all the necessary information required to process the request. If you are building a REST API application using PHP, you are not going to use the $_SESSION variable to save data about the client’s session. This means, we can not access the state of a client (such as login state). In order to solve the issue, the client is responsible for perisiting the state locally and send it to the sever with each request. Since these important information are now persisted in the client local storage we need to protect it from eyes dropping. Enter JWTs. A JWT token is simply a JSON object that has information about the user. For example:
{
"user": "bob",
"email": "bob@email.com",
"access_token": "at145451sd451sd4e5r4",
"expire_at"; "11245454"
}
Since thos token can be tampered with to get access to protected resources. For example, a malicious user can change the previous token as follows to access admin only resources on the server:
{
"user": "administrator",
"email": "admin@email.com"
}
To prevent this situation, we JWTs need to be signed by the server. If the token is changed on the client side, the token’s signature will no longer be valid and the server will deny access to the requested resource.
How JWT Works
JWT tokens are simply encrypted user’s information like identifier, username, email and password. When users are successfully logged in the server, the latter will produce and send a JWT token back to the client. This JWT token will be persisted by the client using the browser’s local storage or cookies and attached with every outgoing request so if the user requests access to certain protected resources, the token needs to be checked first by the server to allow or deny access. What is PHP-JWT
php-jwt is a PHP library that allows you to encode and decode JSON Web Tokens (JWT) in PHP, conforming to RFC 7519.
Prerequisites
You must have the following prerequsites to be able to follow this tutorial from scratch:
You need PHP 7, Composer and MySQL database system installed on your development environment,
You need to have basic knowledge of PHP and SQL.
Creating the MySQL Database and Table(s)
If you have the prerequisites, let’s get started by creating the MySQL database. We’ll be using the MySQL client installed with the server. Open a terminal and run the following command to invoke the client:
$ mysql -u root -p
You need to enter your MySQL password when prompted.
Next, let’s create a database using the following SQL instruction:
mysql> create database db;
Note: Here we assume you have a MySQL user called root. You need to change that to the name of an existing MySQL user.
You can also use phpMyAdmin or any MySQL client you are comfortable with to create the database and SQL tables.
Let’s now select the db database and create a users table that will hold the users of our application:
mysql> use db;
mysql> CREATE TABLE IF NOT EXISTS `Users` (
`id` INT AUTO_INCREMENT ,
`first_name` VARCHAR(150) NOT NULL ,
`last_name` VARCHAR(150) NOT NULL ,
`email` VARCHAR(255),
`password` VARCHAR(255),
PRIMARY KEY (`id`) );
Creating the Project Directory Structure
Let’s create a simple directory strucutre for our project. In your terminal, navigate to your working directory and create a folder for our project:
$ mkdir php-jwt-example
$ cd php-jwt-example
$ mkdir api && cd api
$ mkdir config
We first created the project’s directory. Next, we created an api folder. Inside it, we created a config folder. Connecting to your MySQL Database in PHP
Navigate to the config folder and create a database.php file with the following code:
<?php
// used to get mysql database connection
class DatabaseService{
private $db_host = "localhost";
private $db_name = "mydb";
private $db_user = "root";
private $db_password = "";
private $connection;
public function getConnection(){
$this->connection = null;
try{
$this->connection = new PDO("mysql:host=" . $this->db_host . ";dbname=" . $this->db_name, $this->db_user, $this->db_password);
}catch(PDOException $exception){
echo "Connection failed: " . $exception->getMessage();
}
return $this->connection;
}
}
?>
Installing php-jwt
Let’s now proceed to install the php-jwt library using Composer. In your terminal, run the following command from the root of your project’s directory:
$ composer require firebase/php-jwt
This will donwload the php-jwt library into a vendor folder.
You can require the php-jwt library to encode and decode JWT tokens using the following code:
<?php require "vendor/autoload.php";
use \Firebase\JWT\JWT;
Adding the User Registration API Endpoint
Inside the api folder, create a register.php file and add the following code to create a new user in the MySQL database:
<?php
include_once ‘./config/database.php’;
header("Access-Control-Allow-Origin: * ");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$firstName = ”;
$lastName = ”;
$email = ”;
$password = ”;
$conn = null;
$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();
$data = json_decode(file_get_contents("php://input"));
$firstName = $data->first_name;
$lastName = $data->last_name;
$email = $data->email;
$password = $data->password;
$table_name = ‘Users’;
$query = "INSERT INTO " . $table_name . "
SET first_name = :firstname,
last_name = :lastname,
email = :email,
password = :password";
$stmt = $conn->prepare($query);
$stmt->bindParam(‘:firstname’, $firstName);
$stmt->bindParam(‘:lastname’, $lastName);
$stmt->bindParam(‘:email’, $email);
$password_hash = password_hash($password, PASSWORD_BCRYPT);
$stmt->bindParam(‘:password’, $password_hash);
if($stmt->execute()){
http_response_code(200);
echo json_encode(array("message" => "User was successfully registered."));
}
else{
http_response_code(400);
echo json_encode(array("message" => "Unable to register the user."));
}
?>
Adding the User Login API Endpoint
Inside the api folder, create a login.php file and add the following code to check the user credentials and return a JWT token to the client:
<?php
include_once ‘./config/database.php’;
require "../vendor/autoload.php";
use \Firebase\JWT\JWT;
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$email = ”;
$password = ”;
$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();
$data = json_decode(file_get_contents("php://input"));
$email = $data->email;
$password = $data->password;
$table_name = ‘Users’;
$query = "SELECT id, first_name, last_name, password FROM " . $table_name . " WHERE email = ? LIMIT 0,1";
$stmt = $conn->prepare( $query );
$stmt->bindParam(1, $email);
$stmt->execute();
$num = $stmt->rowCount();
if($num > 0){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$id = $row[‘id’];
$firstname = $row[‘first_name’];
$lastname = $row[‘last_name’];
$password2 = $row[‘password’];
if(password_verify($password, $password2))
{
$secret_key = "YOUR_SECRET_KEY";
$issuer_claim = "THE_ISSUER";
$audience_claim = "THE_AUDIENCE";
$issuedat_claim = TIME_IN_SECONDS; // issued at
$notbefore_claim = TIME_IN_SECONDS; //not before
$token = array(
"iss" => $issuer_claim,
"aud" => $audience_claim,
"iat" => $issuedat_claim,
"nbf" => $notbefore_claim,
"data" => array(
"id" => $id,
"firstname" => $firstname,
"lastname" => $lastname,
"email" => $email
));
http_response_code(200);
$jwt = JWT::encode($token, $secret_key);
echo json_encode(
array(
"message" => "Successful login.",
"jwt" => $jwt
));
}
else{
http_response_code(401);
echo json_encode(array("message" => "Login failed.", "password" => $password, "password2" => $password2));
}
}
?>
We now have two restful endpoints for registering and log users in. At this point, you can use a REST client like Postman to intercat with the API.
First, start your PHP server using the following command:
$ php -S 127.0.0.1:8080
A development server will be running from the 127.0.0.1:8080 address.
Let’s now, create a user in the database by sending a POST request to the api/register.php endpoint with a JSON body that contains the first_name, last_name, email and password:
You should get an 200 HTTP response with a User was successfully registered. message.
Next, you need to send a POST request to the /api/login.php endpoint with a JSON body that contains the email and password used for registering the user:
You should get a Successful login message with a JWT token.
The JWT token needs to be persisted in your browser’s local storage or cookies using JavaScript then attached to each send HTTP request to access a protected resource on your PHP server.
Protecting an API Endpoint Using JWT
Let’s now see how we can protected our server endpoints using JWT tokens. Before accessing an endpoint a JWT token is sent with every request from the client. The server needs to decode the JWT and check if it’s valid before allowing access to the endpoint.
Inside the api folder, create a protected.php file and add the following code:
<?php
include_once ‘./config/database.php’;
require "../vendor/autoload.php";
use \Firebase\JWT\JWT;
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$secret_key = "YOUR_SECRET_KEY";
$jwt = null;
$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();
$data = json_decode(file_get_contents("php://input"));
$authHeader = $_SERVER[‘HTTP_AUTHORIZATION’];
$arr = explode(" ", $authHeader);
/*echo json_encode(array(
"message" => "sd" .$arr[1]
));*/
$jwt = $arr[1];
if($jwt){
try {
$decoded = JWT::decode($jwt, $secret_key, array(‘HS256’));
// Access is granted. Add code of the operation here echo json_encode(array(
"message" => "Access granted:",
"error" => $e->getMessage()
));
}catch (Exception $e){
http_response_code(401);
echo json_encode(array(
"message" => "Access denied.",
"error" => $e->getMessage()
));
}
}
?>
You can now send a POST request with an Authorization header in the following formats:
JWT <YOUR_JWT_TOKEN_HERE> Or also using the bearer format:
Bearer <YOUR_JWT_TOKEN_HERE>
Conclusion
In this tutorial, we’ve seen how to implement JWT authentication in PHP and MySQL.
via Planet MySQL
PHP JWT Authentication Tutorial

The Best Under-Sink Water Filter

The Best Under-Sink Water Filter

Anyone who goes through more than a couple of gallons of drinking water a day will probably be happiest with an under-sink filtration system like the Aquasana AQ-5200. If you prefer (or need) filtered water, this provides a continuous supply of it on demand from a separate tap. We recommend the Aquasana AQ-5200 because its certifications are among the best of any system we’ve found.

via Wirecutter: Reviews for the Real World
The Best Under-Sink Water Filter

Laravel Money

Laravel Money

Laravel Money is a composer package by Ricardo Gobbo de Souza for working with and formatting money in Laravel projects.

Laravel money uses the moneyphp/money PHP package under the hood and gives you a bunch of helpers:

use Cknow\Money\Money; echo Money::USD(500); // $5.00 

This package includes a ton of advanced features for doing money operations, comparisons, aggregations, formatting, and parsing:

// Basic operations Money::USD(500)->add(Money::USD(500)); // $10.00 Money::USD(500)->subtract(Money::USD(400)); // $1.00 // Aggregation Money::min(Money::USD(100), Money::USD(200), Money::USD(300)); // Money::USD(100) // Formatters Money::USD(500)->format(); // $5.00 // Parsers Money::parse('$1.00'); // Money::USD(100) 

You can also create a custom formatter for your specific use-case:

Money::USD(500)->formatByFormatter(new MyFormatter()); 

Be sure to check out the advanced usage and included helper functions in the project’s README file. Also, check out the Money PHP documentation for complete details of what this package is capable of doing.

You can learn more about this package and check out the source code on GitHub at cknow/laravel-money.


Filed in: News / packages


Enjoy this? Get Laravel News delivered straight to your inbox every Sunday.

No Spam, ever. We’ll never share your email address and you can opt out at any time.

via Laravel News
Laravel Money

Westworld Welcomes Lena Waithe to Season Three

Lena Waithe at he 2019 Winter Television Critics Association Press Tour.
Photo: Frederick M. Brown (Getty)

Westworld’s last season ended with the power dynamics between the titular park’s human guests and cybernetic hosts shifting in a radical way as the inorganic beings moved forward on their path to wrestling freedom from their creators. But for the show’s next season, the cast is getting larger in order to tell even more stories about new characters.

According to The Hollywood Reporter, Master of None’s Lena Waithe is set to join Westworld’s third season in a role that, like Aaron Paul’s, is being kept secret ahead of the show’s 2020 premiere. It’s anyone’s guess whether Waithe will be portraying a human, a host, or, perhaps both.

[The Hollywood Reporter]


For more, make sure you’re following us on our new Instagram @io9dotcom.

via Gizmodo
Westworld Welcomes Lena Waithe to Season Three

50 Game of Thrones Memes That Will Crack You Up

The wait is almost over for Game of Thrones fans. Come April 14, the eighth and final season of the show will finally be released and our two-year wait will finally be rewarded… probably with all the characters except Bran Stark dying because <spoilers>. There’s no doubt that it’s going to be dark, bloody, and even more incestuous than ever before. Oddly enough, Game of Thrones memes is the complete opposite of the show.

Outside the show exists a fandom of darkly humorous geeks (us). They have created their own funny fanfiction in the form of cropped photos and the impact font to make us all preoccupied while waiting for each season of the show.

How Will Game of Thrones End?

Of course, Game of Thrones is not without its innate funny moments, especially when certain characters are on-screen:

There’s also that one time The Hound laid his life down the line for some chickens:

And of course, Ser Bronn of the Blackwater, Saver of Tyrion, The Blower of the Wildfire, Walking joke encyclopedia:

Still, you’d be surprised at the creativity of some people in their Game of Thrones memes. Some of them are downright witty and most remind us why we all love the show. So, without further ado, here are some funny Game of Thrones memes– sorry, the funniest Game of Thrones memes this side of Westeros.

50. Syrio Forel A man would have been so proud…

49. What’s the difference? He died there anyway…

48. All that commitment just to get stabbed over a watch…

47. Let me tell you the story of Littlefinger…

46. Novice time travelers be like…

45. Bran please, priorities…

44. It was that during that day when Robb underestimated the power of plot armor…

43. We almost forgot about Rickon Stark, the Expendable

42. Ser Davos Seaworth, Lord of Introductions…

41. Jon Snow, Knower of Nothing

40. Shhh, he’s uhh… warging or something…

39. Arya took all the XP, sorry Sansa…

38. I heard the Night’s Watch bachelor party was cool– ice cold even, literally…

37. Jon Snuuuu…

36. Error 404, bleached hair not found…

35. I swear, he was more laid back when he was with Ygritte…

34. A man always speaks in third person…

33.  What was this guy’s name again? Groot?

32. Will it also die after fulfilling its life’s purpose?

31. A man has no honor…

30. Would you rather be: Alive but without genitals? Or dead with burned genitals?

29. I swear if you forget to add Dragon Queen, I’m not leaving a tip…

 

 

28. At least Theon doesn’t need a hand…

27. Uh, dwarf jokes are so PETTY..

26. Fame or Shame? Oh right, she had no choice…

25. A castle with Elsa from Frozen nonetheless…

24. Oh, no she di-int…

23. Too softcore, not enough for HBO…

22. The math checks out…

21. The show just keeps getting more and more incesting…

20. Interesting family tree, nothing is twice removed…

19. Must be nice having a White Walker as a brother-in-law…

18. Lannisters, they keep things simple…

17. How about paintings of stones and pillars instead?

16. Cersei.exe has encountered a critical error, terminate everyone in Westeros?

15. You cannot fix what’s not broken, silly Jaime…

14. Of course, Targaryens would know a lot about DNA and RNA, they’ve shared the same one for generations…

13. When bae trades you for a hotter redhead…

12. Not nice Jon, kicking a man while he’s down…

11. Well, here’s one thing Bran Stark got right…

10. Ser Jorah Mormont, Lord of the Friendzone, Begger of the Khaleesi, the Unrequited

9. We assure you, we’re not being mean to him…

8. No, really, that’s just how he is in the show…

7. Khaleesi please, you’re breaking his heart…

6. How ’bout a taste of your own medicine Dany?

5. Jaime “Cersei is life, sister is wife” Lannister…

4. Single mom, ideal date should be willing to babysit dragons…

3. A man of few words, will also hold the door for you…

 

2. Make Astapor Great Again…

1. I can only imagine his laughter right now…

That last part? Half-a-joke at this point… that’s a definite maybe. Oh, here are some honorable mentions if videos are more your speed:

Here’s a good old classic from Bad Lip Reading:

Last but not least, though you probably already saw this one if you’re a fan of Family Guy, pretty much sums up the whole fandom:

Anyway, those are the best Game of Thrones memes. More will surely come (along with more character deaths) once Game of Thrones Season 8 gets released on April 14 on HBO.

You might also like:

WWEsteros: Who Will Rule the Iron Throne?

Enjoy The Women of Game of Thrones in a Pin-Up “Calendar”

via Forever Geek
50 Game of Thrones Memes That Will Crack You Up

The Most Loved and Most Disliked Programming Languages Revealed in Stack Overflow Survey

angel’o’sphere shares a report: The annual Stack Overflow survey is one of the most comprehensive snapshots of how programmers work, with this year’s poll being taken by almost 90,000 developers across the globe. This year’s survey details which languages developers enjoy using, which are associated with the best paid jobs, which are most commonly used, as well as developers’ preferred frameworks, databases, and integrated development environments. Python’s versatility continues to fuel its rise through Stack Overflow’s rankings for the "most popular" languages, which lists the languages most widely used by developers. This year’s survey finds Python to be the fastest-growing major programming language, with Python edging out Android and enterprise workhorse Java to become the fourth most commonly used language. […] More importantly for developers, this popularity overlaps with demand for the language, with Julia Silge, data scientist at Stack Overflow, saying that jobs data gathered by Stack Overflow also shows Python to be one of the most in-demand languages sought by employers. […] Rust may not have as many users as Python or JavaScript but it has earned a lot of affection from those who use it. For the fourth year running, the language tops Stack Overflow’s list of "most-loved" languages, which means the proportion of Rust developers who want to continue working with it is larger than that of any other language.[…] Go stands out as a language that is well paid, while also being sought after and where developers report high levels of job satisfaction. Full report here.



Share on Google+

Read more of this story at Slashdot.

via Slashdot
The Most Loved and Most Disliked Programming Languages Revealed in Stack Overflow Survey

Everything You Wanted To Know About Building A Shipping Container Home

As makers, we have a tendency to escalate our vision. Each project idea seems to get a little more complex, a little more grandiose in scale. Ben Uyeda of Homemade modern is no different. We’ve followed along for years as he and his friends have constructed various cleverly designed pieces of furniture and home based projects on homemade modern, but recently he’s published a massive project that dwarfs all the others in scale. This project is so massive, it got its very own channel to house it, the modern home project. Ben has set out to build and thoroughly document building a home from shipping containers in the desert of Joshua Tree.

 

Shipping container homes have been around for quite some time. What Ben is doing in terms of construction isn’t necessarily new. However, his thorough documentation seems to be where the value lies. Ben pointed out that he had considered a shipping container home for a long time but had never seemed to find a useful compendium of all he needed to know (remember, Ben has a background in doing architectural projects, before getting into making videos on youtube!). He set out to remedy this reference issue by creating his own version.

As you follow along you’ll learn everything you would need to know to build a container home in the same geographical area as him. It would, of course, be impossible to say that you would learn everything you’d need to know to build anywhere because regional building codes can be not only different, but even contradictory, but with that in mind, this is a very good start.

There are currently only 3 videos published on this project, but there are more on the way. Even though I never intend to build a shipping container home, I have found this to be thoroughly entertaining and educational. I’m looking forward to more on this series and have actually found a few bits of information that I think could assist me in upgrades I’d like to make to my workshop.

Ben will be speaking about this project at the upcoming Maker Faire Bay Area, so make sure to get tickets and come listen and ask questions!

 

via MAKE Magazine
Everything You Wanted To Know About Building A Shipping Container Home