• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

WP Dev Life

A Journey through WordPress

  • About Jay
  • Dev Tools
  • Contact Us

wordpress

Authentication and the REST API

January 5, 2019 by Jay

Why authenticate and how?

The WordPress RESTful API was a major addition to the core ecosystem when it launched with WordPress 4.7. Having these endpoints opened up a slew of possibilities to be able to power the future of digital experiences. By using the REST API, developers are able to create native mobile and web applications that are driven by the WordPress backend. This is what’s referred to as a Headless WordPress site.

By default, anyone can make a GET request to any of the API endpoints for posts, pages, users, media, etc to garner data about your site and its information. WordPress Core has  included a full list of REST API endpoints which can be found in the developer handbook here.. When it comes to creating posts or pages or adding information to your site via an API you don’t want any random person spamming your site with junk, and that is where authentication comes into play.

There’s a few options available for authentication. The easiest for development and testing purposes would be Basic Authentication, which requires that you send an appropriate username and password encoded in base64 with each request.  You may have set up an .htpasswd file in conjunction with your .htaccess file in the past if you use Apache as your backend web server, and this is pretty similar to that, however instead of storing information in a hidden file, WordPress uses usernames and passwords from your database to authenticate. You can install the Basic Auth plugin from https://github.com/WP-API/Basic-Auth. Since this requires sending a username and password with every single request, I do not recommend using this in a production environment.

Another way of authenticating with the WordPress REST API would be to utilize JWT Authentication, or JSON Web Tokens, which is an open industry standard for representing claims securely between two parties. There’s a multitude of JWT Authentication plugins out there, but I typically see either the WP-API teams jwt-auth plugin used, which is still experimental, or the JWT Authentication for WP REST API plugin . Additionally Jonathan Dejong has also created a Simple JWT Authentication plugin, but they all seem to function on the same basic premises. Once this plugin is installed and configured you’ll need to generate a token to be able to prove that your application has the required permissions to access specific endpoints, such as showing all posts with the status of draft. By sending a POST request to the plugin’s token endpoint, containing a username and password combination, you’ll get back a token which you can use in the headers of future requests for authentication.

Testing Authentication and the REST API

So we’ve got our WordPress instance running, an authentication plugin setup and configured so now how do we make sure it is working as intended? Postman is my go to application for testing REST API calls. It’s interface is great, it has support for a multitude of platforms, and is just all around excellent, because let’s be real, who wants to write out long curl commands, manually setting headers, running the request again because you didn’t get all the information you needed. Sure that’s fine for a few people, but Postman simplifies the process tremendously.

When we make GET request to the posts endpoint we get back a JSON array that contains all of the posts on our site.

But if we change that GET to a POST we get a 401 Not Authorized error back, and this is because we haven’t authenticated our requests yet.

Basic Authentication with Postman

Let’s say the Basic Auth plugin is installed on our site, and we want to try to create a post. We can use a POST request to create a post within Postman. If you send a default POST request to the /wp-json/wp/v2/posts endpoint you’ll receive a 401 error. Click on the Authorization tab within Postman, and in the dropdown choose Basic Auth. To the right of that fill in your username and password you use for logging into the Admin Dashboard, and click Send.

You’ll get back a 400 response because we didn’t send any other data to WordPress to create a post.

If we fill in the required information as form-data on the Body tab in Postman, which in this case is Content, title, and excerpt we can create a draft post.

If you were to change the username or password in the Basic Auth settings you would get back a response telling you to reset your password. Just as a reminder, we don’t recommend the use of Basic Auth in production requests due to constantly having to pass your username and password.

JWT Authentication with Postman

JWT Authentication uses the Bearer authorization header rather than the Basic authorization header. To be able to generate the token for the header though we first have to make a request to the Token endpoint of our respective JWT Auth plugin to get this token, except you only need to pass in the username and password in the body of the request to generate the token. Once you have the token, you can then just send that in the headers instead of having to pass your username and password on every request.

On the Authorization tab in Postman, set the dropdown to No Auth, and change the request url to your JWT Authentication Token endpoint. For the body, set your username and password entries and submit your POST request to get your token.

Once you have that token, change the endpoint you want to authenticate against. Go back to the Authorization tab, change the dropdown from No Auth to Bearer and copy and paste your token into the Token field. Then create another post similar to what we did with the Basic Auth one. For the Body, ensure you have Content, title, and excerpt values and send your POST request. If everything is configured right you should get back a 200 response and see your new post’s JSON data in the bottom of Postman.

Final Thoughts

As Gutenberg becomes more prevalent in use throughout the WordPress community, I believe that REST API knowledge is going to become absolutely necessary. With different plugins extending WordPress’ core API, like Woocommerce’s API, this ll paves the way for some extremely slick digital experiences powered by WordPress as we move into the future. If you see anything I missed, or may not be 100% accurate about feel free to drop me a mention on Twitter, @wpdevlife.

Filed Under: REST API, WordPress Tagged With: rest-api, wordpress

Development Workflow

February 20, 2018 by Jay

Everyone has their own workflow. With all of the tools like GitHub, TravisCI, VVV, Webpack, and the list goes on, every team or individual is going to have their own workflow. Even better, is that platforms such as WP Engine are providing tools to enhance these workflows to get your code into production. We’ll be going over a few different tools that I’ve found useful and how I’ve incorporated them into my own personal workflow.

Local Environment

This is probably the most important part of it all. There’s been a slew of ways to configure your local environment. A lot of people have traditionally used The *AMP family of environments, where you install Apache, MySQL and PHP on your local machine. This prevents a challenge though because if you’re working with a team, each one of you may have inadvertently configured things differently, or you’re running on completely different operating systems, and code written for one may not work properly on the others.

Income the Vagrants & Containers. When I first started writing code in junior high I had no idea what I was doing but I had Dreamweaver and some free hosting through one of the plethora of free web hosts of the early 2000’s where you’d bypass their popups with some clever script at the bottom of your site. Utilizing virtualization software and configuration through VirtualBox, Vagrants have taken a good forefront. It allows you to essentially have a preconfigured environment that can mount your local filesystem and develop your websites. My personal favorite that I’ve used recently is VVV from 10up. Varying Vagrant Vagrants is an open source Vagrant configuration focused on WordPress development. This is a great tool for developing themes or plugins. As I get more familiar with it and try out others I’ll do some full reviews.

The other day I was introduced to Wocker in the /r/WordPress sub-reddit. Wocker is a local WordPress development environment built on Docker. I haven’t gotten to experiment with it yet but looks promising. You still need to have Vagrant installed and configured to utilize this as well.

Code Versioning

Git duh. Whether you’re working on a personal project, or your company has a set of private repositories, or even a centralized custom git server. Git is the front runner in handling code versioning. Deploying those code changes from git else where whether handled by TravisCI for continuous integration, or Jenkins for continuous deployment, is a whole other beast that we’ll eventually cover.

Staging & Production

WP Engine has always provided a staging area for developers to test changes before deploying them to their production site. Things have gotten even better recently with their Deploy Site and Copy Site features as well as their Workspaces and Environment Labels, the latter being more for organizational purposes. Using these features though you can easily create a backup point, and deploy that from your staging install to another environment such as your production install. This means you can push your code with git to a dev install, deploy that to staging, have QA review, then deploy staging to production pretty seamlessly. As long as you’re only deploying code changes then your database on live is never touched so if you’re an e-commerce store you can be assured that no customer information is lost.

Other Thoughts

I’m sure there’s a lot that I haven’t yet covered, and even more that I need to learn. These are the basics for my own personal workflow and as that changes then this article will get updated to reflect that, or maybe a yearly series that covers my workflow and how it’s changed. There’s an idea at least. Thanks again for reading and if you’ve liked it or found it helpful share on Social Media. If you have any questions don’t hesitate to contact me!

 

Filed Under: WordPress Tagged With: best-practices, development, wordpress

Use Amazon SES to send WordPress E-mails

February 19, 2018 by Jay

I originally wrote this guide for a WP Engine Support Garage article, as WPEngine  utilizes the Google Cloud Platform which will block sending e-mail over specific ports, and I wanted to provide an easy to use alternative. The article eventually got published on a co-workers blog, but I decided to publish it here as well. More visibility is better right?

Google allows only Google Apps to send email through ports 465 and 587, and prohibits any service from sending mail through port 25.

Many email providers have created better ways of sending or relaying email through alternate ports or APIs. But Microsoft Office 365 among others are left in the lurch when it comes to sending outgoing emails through Google Cloud servers. If you’re one of the many affected by this issue, this guide will help you configure email through Amazon Simple Email Service (SES) to send outgoing emails from your WordPress site.

This post is only going to cover sending e-mails out of your WordPress site, so password resets, transaction confirmations, and other similar types of e-mails. You could in theory use this and a mailing list plugin, but I recommend using an actual service for your mailing list such as MailChimp.

Setup your DNS Records

The first step is to validate your domain with the SES service–This requires adding DNS records with your DNS provider. The process is the same with any DNS provider, but we are using CloudFlare’s DNS dashboard in this example.

Log in to the Amazon Web Services console and navigate to the SES page. Then click “Domains” from the left-hand navigation menu. Click “Verify a new domain” and enter your domain name. If you want to utilize DKIM then you can also generate DKIM signatures in this step. On the next screen you’ll be given your DNS records to set up within your DNS provider.

Add the DNS records from the Domain Verification Page

You can take the Type and Value fields from these records and paste them directly into your DNS provider’s dashboard. In our CloudFlare example simply log in, choose your domain name, and select “DNS records.” In the dropdown menu to select a type of record, choose “TXT” – then in “Value” enter the “Name” field from the Domain Verification Record, and in the box next to it, enter the “Value” field. Once Amazon SES has been able to detect the records have been added, your domain is verified for use with their service.

If you utilize an email provider for your domain’s emails such as Google Suite, Outlook365, or another email server then you do not need to input the MX record and will leave your current MX records as is. This means only your outgoing emails will be handled by Amazon SES.

Create an E-mail User

Now that Amazon has been able to verify our domain for sending email we need to create an SMTP user for our WordPress site to use for sending email. On the SES console home page, click “SMTP Settings” from the left-hand navigation. Then click the “Create My SMTP Credentials” button. Leave the default username as-is and click “Create.”

On the next screen be sure to download your login credentials–we will need them in the next step. To do this, just click “Show User SMTP Security Credentials” and you can copy and paste them into your text editor of choice.

Install & Configure an SMTP Plugin

Now that we’ve configured Amazon SES it’s time to configure your WordPress install to utilize the service. We’re going to be using the Easy WP SMTP plugin for this step. You can install this plugin by going to your plugins page in the WordPress Admin Dashboard of your site and going to Plugins > Add New > search for Easy WP SMTP > Install. Once installed you’ll want to activate the plugin so  we can configure it.

Google Cloud servers have ports 25, 465, and 587 disabled by default, but you can still use port 2587.

  • In the “From” field, put an email address you want WordPress to send email from. This could be anything as long as it has your domain name in it.
  • For the “Name” you can put anything you want your emails to show as from.
  • You can get your SMTP Host at the Amazon SES SMTP Settings page. If you setup SES in the US-East-1 region it will be: email-smtp.us-east-1.amazonaws.com.
  • Ensure that TLS is selected for the Type of Encryption setting.
  • For the sending port, input 2587.
  • Check the SMTP Authentication to yes and input your SMTP username and password that was created in the previous step.

Your settings should then look similar to this:

Configure the SMTP plugin

Send a Test E-mail

Now that your settings are configured, you’ll want to send a test email to make sure it’s working right. Right now your SES account is still in Sandbox mode, so we need to configure an email address to send email to first. In your Amazon SES console, click “Email Addresses.”

Click “Verify A New Email address,” enter in the email address you want to verify. Then click the “Verify This Email Address.” This will send an email to the specified email address. You’ll need to click the link within it to verify your email address. If you do not verify your email address, Amazon won’t send the email.

Once verified, head to the Easy WP SMTP Settings page in your dashboard and scroll down to the “Testing and Debugging Settings” section. Input the verified email address, a subject and message, and then send. Check your email to ensure that it was delivered. If it was not delivered, confirm your email address is validated and your port settings.

Request Amazon release Sandbox Mode

Amazon keeps your SES service in what is called Sandbox Mode which requires that all email addresses you send to be verified before email deliverability can be achieved. We need to request Amazon enable production access to SES by utilizing their support system for a Service Limit Increase.

Ensure “Service Limit Increase” is selected, and “Limit Type” is set for “SES Sending Limits.” In “Request 1” choose the region you setup SES for and then choose “SES Production Access.” Fill out the rest of the boxes and submit the request. Amazon typically takes 24 hours to grant access to Production Mode for SES.

Once they have taken SES out of Sandbox mode you should be able to test your site’s emails to ensure they’re delivering properly. Be sure to test any eCommerce emails, contact forms, or transactional emails. You should also ensure that your contact forms have a captcha configured. This ensures spammers are not able to abuse your forms, which in turn abuses your SES service.

That’s all there is to it! I hope you have found this useful. If you have any questions don’t hesitate to reach out!

Filed Under: AWS, WordPress Tagged With: aws, email, wordpress

Primary Sidebar

Learn Linux

Use LinuxAcademy to learn Linux, AWS, or other Cloud technologies.

Find Something

Categories

Recent Posts

  • Using withSelect for WordPress Block Components
  • Gutenberg: Attributes vs State
  • Getting Started with Unit Tests
  • WordPress REST API
  • Authentication and the REST API

Archives

  • November 2019
  • May 2019
  • January 2019
  • July 2018
  • February 2018

Copyright © 2025 · Wp Devlife on Genesis Framework · WordPress · Log in