Posted on Leave a comment

Create SSL Site At Your Localhost With MAMP/NodeJS In 5 Minutes

ssl on localhost

As a software developer, I usually found myself frustrated looking at the browser with the following notice when loading my local site:

Create SSL Site At Your Localhost With MAMP/NodeJS In 5 Minutes 1

Yes, the infamous “Your connection is not private notice”. You can bypass that by typing “THISISUNSAFE” in Chrome/Edge. However, a hack is still a hack. You deserve a good solution.

Today, I’m the solution provider. Let’s walk with me to make https://abc.local load with SSL like a normal secure site.

Here is the environment:

  • OS: MacOS 10.15.3
  • MAMP running Apache 2.4

Your environment may be different, however, the method is applicable to other environments running Apache.

Let’s get started.

How to configure Apache 2.4 on MAMP to enable local secure site

Step 1: Add your site to /etc/hosts

This is the easiest one. To host a site on your localhost, you need to add a record of that site to /etc/hosts file so when you type that site into your browser address bar, the browser know to look for it at your localhost.

In our case, we need to add abc.local to /etc/hosts.

Let’s open /etc/hosts by typing:

sudo vim /etc/hosts

I’m using vim as the text editor, however, you can use any other program you like. The important thing to note is opening it with sudo or you cannot save your changes.

On Windows, the equivalent of /etc/hosts is C:\Windows\System32\drivers\etc\hosts. Just open your notepad with Administrator right and then open the hosts file and you’ll be fine.

Let’s insert:

127.0.0.1 abc.local

at the end of the hosts file and save then close it. Like this:

Create SSL Site At Your Localhost With MAMP/NodeJS In 5 Minutes 2

And you are done with step one!

Step 2: Enable NameVirtualHost, SSL, Vhosts In Apache

In this step, we are going to modify some of Apache’s configurations so it’ll accept SSL, VirtualHost records and Named virtual host. If you have been using MAMP (or XAMPP) for a while, you know how to access the server via http://localhost… However, to access localhost with custom domain name like abc.local, you need to do the following:

First, open the file at /Applications/MAMP/conf/apache/httpd.conf with your favorite text editor. I’ll use Vim as usual.

Now, look for the following lines:

Include /Applications/MAMP/conf/apache/extra/httpd-ssl.conf
 Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

And remove the # character at the beginning of those lines.

Save the file and quit.

Next, let’s open /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf to enable name based virtual hosting.

Let’s add the following lines if they are not available or commented:

NameVirtualHost *:80
NameVirtualHost *:443

Then save the file and quit.

You are ready for step 3!

Step 3: Generate your self signed SSL certificates

To generate a certificate for your site, open terminal and run the following command:

openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
  -keyout abc.local.key -out abc.local.crt -extensions san -config \
  <(echo "[req]"; 
    echo distinguished_name=req; 
    echo "[san]"; 
    echo subjectAltName=DNS:abc.local,DNS:developer.abc.local,DNS:www.abc.local,DNS:api.abc.local,IP:10.0.0.1,IP:127.0.0.1
    ) \
  -subj "/CN=abc.local"

As you can see, in the script, I didn’t just generate certificate for abc.local. I also generate certificate for a bunch of subdomains like www, developer… If you need SSL for subdomain, you can add more DNS record. One caveat though, you cannot add subdomain of subdomain. For example, info.developer.abc.local would not work.

You can also notice that the params -day 3650. That means the certificate is valid for 10 years! How about 100 years? Just replace 3650 with 36500.

generating ssl certificate for the local site

As you can see, I’ve successfully generate the certificate files with the command. You’ll get two files: abc.local.key and abc.local.crt. Let’s put these two files in /Applications/MAMP/conf/apache/ssl. If this folder is not available, you need to create it.

Phew! You’ve done a lot. There is two more steps before you can load your site over SSL. Let’s get to step 4!

Step 4: Create your virtual host record in httpd-ssl.conf

Remember httpd-ssl.conf? You’ve seen this file earlier in the post. Let’s open it and add the following record at the end of the file:

<VirtualHost _default_:443>
	ServerName abc.local
	ServerAlias abc.local
	DocumentRoot "/Applications/MAMP/htdocs/abc/"
	ErrorLog "logs/abc.local-error_log"
	CustomLog "logs/abc.local-access_log" common

	SSLEngine on
	SSLCertificateFile  "/Applications/MAMP/conf/apache/ssl/abc.local.crt"
	SSLCertificateKeyFile  "/Applications/MAMP/conf/apache/ssl/abc.local.key"
</VirtualHost>

Let’s safe the file and quit. Now, it’s time to work on the certificate.

Step 5: Trust your certificate

Since your certificate is self-signed, you need to manually trust it. Let’s open the abc.local.crt file by double clicking on it:

Install the certificate

Now, select System as Keychain and click on Add. The system will ask you to enter password. Do as asked to complete this step.

Now, look for abc.local in the list of certificates and double click on that.

Trust the self-signed certificate

Select Always trust and close the window. You may be asked to enter your password again. Do so as this is the last step you need to work with the certificate!

Final step: Restart MAMP and view your site

Now, go to your browser and type https://abc.local, you should see the site is successfully loaded without any security warning. Clicking on the lock icon, you’ll see the site is trusted:

SSL certificate is working on localhost mac MAMP

You may see a 404 page. That’s expected since our path to the site is not available yet (htdocs/abc). Let me create a very quick index.html in htdocs/abc so you’ll see the content.

Hello from http on localhost MAMP

That’s it! now you have the SSL certificate valid for 10 years!

Bonus tips: How to make SSL works on webpack-dev-server

Now you know how to create secure site on localhost with MAMP. Using the same certificate files, you can make any sites with webpack dev server or other nodejs based app secure on localhost too.

In this example, I’m going to create a new Vue cli project and also create a vue.config.js file at the project root. The content of the file is simple as follow:

var fs = require('fs')
module.exports = {
    devServer: {
        host: 'abc.local',
        port: 8081,
        https: true,
        key: fs.readFileSync("/Applications/MAMP/conf/apache/ssl/abc.local.key"),
        cert: fs.readFileSync("/Applications/MAMP/conf/apache/ssl/abc.local.crt"),
    }

}

As you can see, the key is to set https to true and point key and cert options to the files we have created previously.

When I run the app with npm run serve, you can see that the app is served over https and there is no certificate problem:

Create SSL Site At Your Localhost With MAMP/NodeJS In 5 Minutes 3

Conclusion

I don’t know about you but the day I discovered installing SSL for my local site this easy, my life changed. I no longer have to rely on options like Flywheel’s local just to get the https to work. Hopefully, this tutorial helps you has much it helped me. If you have any suggestions, please let me know in the comment below.

Posted on Leave a comment

Seven days challenge to learn one new topic each day

So I decided to improve my skills as a developer. I’m going to do a 7 days challenge to learn the new topics that I always wanted to learn but couldn’t arrange the time to do so. This is the first 7 days. I’m going to learn the following topics:

Day 1: PHP Composer

Day 2: PHP Autoload

Day 3: PHP Namespace

Day 4: PHP Generators

Day 5: PHPUnit

Day 6: PHP Hashing

Day 7: WordPress Nonce

Here are the additional topics I would like to learn in later days:

  • PHP namespaces
  • Cross Site Request Forgery

At the end of each day, I’m going to summarize all the things I learned in one article.

Posted on 6 Comments

Accessing Media Files (Audio, Video, Images…) From DigitalOcean Spaces Using Java

Accessing Media Files (Audio, Video, Images...) From DigitalOcean Spaces Using Java 4

Recently, I need to upgrade my English learning app on Android to use multiple servers. Previously, I used two servers already. However, the way I manage media files caused me a lot of headache. So, I decided to switch to DigitalOcean since they have servers around the world and the pricing is good ($5 for 250GB storage and 1TB monthly transfer, which is good).

The initial problem with DigitalOcean spaces

Coming from old-school servers, I thought I can upload the files to DigitalOcean spaces using FTP and access the files directly as I usually used. However, the first problem is you cannot upload to spaces using FTP and the second problem is in order to make a file accessible to public, you need to set it permission to public. If you have one or two files, that wouldn’t be a problem.

I have more than 18,000 files.

The solutions to uploading multiple files

It turned out that DigitalOcean spaces use Amazon s3 technologies. So, in order to upload to spaces, you need to have FileZilla Pro (paid) or CyberDuck(free). I chose FileZilla Pro because it allows you to resume failed transfers while CyberDuck doesn’t allow that (or I couldn’t find where is that option).

The solution to accessing files

As my app used by thousands of people, the media files need to be accessible to all of the users. Actually, it is very easy to generate a public accessible URL for any files (they are called objects) using the aws-android-sdk. In case you need a working sample code, here it is:

public class DigitalOcean implements MediaServer {
    private static final String KEY = "YOUR_KEY";
    private static final String SECRETS = "YOUR_SECRETS";
    private String endpoint, bucketName;
    private AmazonS3Client s3Client;

    @Override
    public String getEndpoint() {
        return endpoint;
    }

    @Override
    public String getType() {
        return "s3";
    }

    public DigitalOcean(String endpoint, String bucketName) {
        this.bucketName = bucketName;
        this.endpoint = endpoint;
        AWSCredentials myCredentials = new BasicAWSCredentials(KEY, SECRETS);
        s3Client = new AmazonS3Client(myCredentials);
        s3Client.setEndpoint(this.endpoint);
    }

    public String getMediaURL(String objectPath) {
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectPath);
        URL objectURL = s3Client.generatePresignedUrl(request);
        return objectURL.toString();
    }
}
 

As you can see, I created an object to generate URL to any files(objects). For example, here is a sample space url:

Accessing Media Files (Audio, Video, Images...) From DigitalOcean Spaces Using Java 5

The bucket name would be data-sample.

If your file, let call it song.mp3 located at /data-sample/media/song.mp3, the objectPath would be: /media/song.mp3.

If you run the method getMediaURL(), you will get the path to the file that is accessible to your users but you don’t have to mark the file public.

https://data-sample.sgp1.digitaloceanspaces.com/media/song.mp3?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180925T060309Z&X-Amz-SignedHeaders=host&X-Amz-Expires=899&X-Amz-Credential=BP5K25LRRQWYV2CMHZLL%2F20180925%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=6a21133ced60047cfba60053afcdf712997c474585ade2f0050bc853b0a4db89
Posted on Leave a comment

How To Filter Non Alphanumerics Characters From Your String And Its Application In Excel

How To Filter Non Alphanumerics Characters From Your String And Its Application In Excel 6

If you are like me, I have to deal with text a lot in my work. As a programmer, I need to find and match string. Recently, a friend of mine, who is an accountant gave me a list of books’ titles. Most of them are fine. However, there are some contains strange characters and she wanted to remove such titles.

How To Filter Non Alphanumerics Characters From Your String And Its Application In Excel 7

As you can see in the picture, there titles with @ and Chinese characters. Using filters doesn’t work because there are more than 1000 rows. That was when I said to myself: “I need a tool”.

So, I made one for this specific purpose: “to help my friend remove all the strange characters in her Excel workbook”.

Here is how the tool look like:

How To Filter Non Alphanumerics Characters From Your String And Its Application In Excel 8

As you can see, you can put the original text in the source string box, adjust a few options above and click on filter. The result will be shown in the Result string box:

How To Filter Non Alphanumerics Characters From Your String And Its Application In Excel 9

As you can see that all the rows that contain strange characters are removed.

However, what if you have some special characters that is allowed to appear in the title? No worries! You can put that into the Allowed characters box and separated them by spaces.

For example, It is OK for me to have the character @ in the title, I would put @ into the Allowed characters box. In addition, that title [email protected] contains the character dot (.) so you need to put that into the list of allowed characters too.

Let’s see what we’ll have:

How To Filter Non Alphanumerics Characters From Your String And Its Application In Excel 10

As you can see now, the title with . and @ is accepted.

There are also two checkboxes that allowed you to filter the text further. You can decide to allow numbers or spaces in the title by checking these checkboxes.

I put the full source code for the tool here:

https://github.com/datmt/Remove-Lines-Contain-NonAlphaNumeric-Characters

If you are not a programmer, you can download the application here to start using it:

Download the .jar file

If you have any suggestions, please let me know. Thank you very much!

Posted on Leave a comment

How To Resize and Copy Images Files To Android Drawable Folders Quickly

I’m not a full time Android developer. I make Android apps such as this. Android studio is great and I can develop my ideas quickly. However, there is one thing I don’t like is the way I have to deal with images. Every time I need to add an icon to my app, I need to resize that image to the following sizes:

  1. 144 x 144
  2. 96 x 96
  3. 72 x 72
  4. 48 x48

And put them in the following folders, respectively:

  1. drawable-xxhdpi
  2. drawable-xhdpi
  3. drawable-hdpi
  4. drawable-mdpi

The task is boring and tedious. So, I decided to make a tool to make this task less painful.

How does the tool work?

Let’s say you want to use a new icon like this in your app:

How To Resize and Copy Images Files To Android Drawable Folders Quickly 11

Now, instead of resize and copy the file 4 times, you just need to open the tool:

How To Resize and Copy Images Files To Android Drawable Folders Quickly 12

The first step is to select your /res folder which contains the drawable-..dpi folders. The Directory Chooser will make this step simple an easy.

Now, look at the checkboxes, they are self-explanatory. If for some reasons, you don’t want to copy the image to a particular folder, simply uncheck the checkbox in front of it.

Then, click on select Image to select your image. The image should be square and have resolution at lest 144 x 144 pixel to avoid pixelation.

If your image is in JPG format, you select JPG, if it is PNG, select PNG.

How To Resize and Copy Images Files To Android Drawable Folders Quickly 13

After that, you click on open to complete the process.

And that’s all. You don’t need to open your image editor to resize the images. With less time spent, you have your images in all drawable folders.

Further features

I made this tool out of my need. I think there are more improvements to be made. Here are some ideas:

  • Let user set the resolution (instead of fixed size as of now)
  • Let user select more folders, even add folders outside the /res folder

The app is free and the repo is open on github. You can download the source and the app here

I hope the app can save you some precious time. Let me know if you have any suggestions.