Basic Authentication in WordPress —How to use, decode, and implement on Front-end application.
APIs have become a common approach for modern web and mobile applications and preventing such APIs is a huge factor.
There are multiple ways to prevent your APIs and some of them are Basic authentication, JWT authentication, Oauth2.0, etc. Among these types, Basic authentication is a simple authentication scheme built into the HTTP protocol.
The user needs to send an HTTP request with the Authorization header which will contain a Basic word followed by a space and base64-encoded string of username: password.
For example to send an authorized request with username: demo and password: Admin@123 base64-encoded string will look like this ZGVtbzpBZG1pbkAxMjM= and the Authorization header will have this look Authorization: Basic ZGVtbzpBZG1pbkAxMjM=
Note: Because base64 is easily decoded, Basic authentication should only be used together with other security mechanisms such as HTTPS/SSL.
In this blog, you can find,
- How to use Authentication in WordPress.
- How to send a request with Basic authentication in Postman.
- How to decode authorization tokens in WordPress.
- How to send API requests in React using Basic Authentication.
How to use Authentication in WordPress
In version 5.6 WordPress introduced a new system for making authenticated requests to various WordPress APIs — Application Passwords.
You can find this section at the end of the Edit User screen.
Application Passwords are 24 characters long, generated using wp_generate_password() without the use of special characters, so they consist exclusively of upper-case, lower-case, and numeric characters. For the cryptographically curious, that comes to over 142 bits of entropy.
e.g. abcd EFGH 1234 ijkl MNOP 6789
This password can be used while calling the API request.
Limitation
By default, Application Passwords are available to all users on sites served over SSL/HTTPS.
Solution
However, this can be customized using a filter provided by WordPress,
add_filter( 'wp_is_application_passwords_available', '__return_true' );
Create Application Password
After adding the above filter, you will be able to create an Application password.
And that's it! You can revoke the password at any time from the admin side.
How to send a request with Basic authentication in Postman
Now that the application password is created, you can use this password in Basic Authentication via any API platform, here I am going to demonstrate this on Postman.
Follow these steps,
- Open a new tab to create a new API request and paste any default or custom-created WordPress API.
- Navigate to the Authorization tab and select Basic Authentication in the dropdown menu.
- Add username(WordPress username) and password(Application Password).
- Now in the Headers tab, you can see the Authorization key with the encoded value(which will be hidden at first and noneditable).
- Finally, hit send button and you will get success response.
What if the wrong password is entered?
In this scenario, you will get a response like this.
{
"code": "incorrect_password",
"message": "The provided password is an invalid application password.",
"data": {
"status": 401
}
}
So far so good? Let’s move on to another interesting topic.
How to decode Authorization token in WordPress
Okay, so now we are requesting data from API using Basic authentication but we are not doing anything on the server side.
To make sure our credentials are correct, we need to decode the Authorization token.
Add the following snippet to your REST API callback function,
function rest_api_callback_funtion( WP_REST_Request $request ) {
$headers = $request->get_headers();
$auth_header = $headers['authorization'][0];
list($username, $password) = explode( ':', base64_decode( substr( $auth_header, 6 ) ) );
$user = wp_authenticate( $username, $password );
if ( is_wp_error( $user ) ) {
wp_send_json_error( 'Authentication required', 401 );
} else {
wp_send_json_success( 'Authentication success', 200 );
}
}
And done! Your API is secured in all the terms.
How to send API requests in React using Basic Authentication
Now that our API is secured we can finally use it with any front-end technology by passing the Authorization header. I am going to illustrate with React JS here.
While requesting an API call in React JS file we need to add headers like those shown in the following code snippet.
let base64 = require("base-64");
const [response, setResponse] = useState("");
const username = "username";
const password = "real mdrid reys deeu ropa 1435";
const requestOptions = {
method: "POST",
headers: {
Authorization: "Basic " + base64.encode(username + ":" + password),
},
};
const getquotes = async () => {
const fetchdata = await fetch(
`YOUR_API`,
requestOptions //headers are added here
);
const response = await fetchdata.json();
setResponse(response);
};
Finally completed!
Conclusion
So, These were some basic steps to achieve the Basic authentication in WordPress REST API. Alternatively, there are other ways to secure API requests but you will need to install plugins for the same. Since WordPress is providing its own it is more secure. (Don’t forget to use it on HTTPS/SSL though)