ecl6ua
Last Updated: February 25, 2016
·
3.05K
· brunochauvet

Secure Jenkins with Apache basic authentication

If you are running your Jenkins instance on a server with open access, you probably want to secure it. Using an Apache web server with basic authentication is an efficient way of achieving this.

Assuming Jenkins runs using a default Linux distribution package on port 8080, add the following configuration to your Apache server:

<VirtualHost *:80>
ServerName jenkins.mydomain.com
ProxyPass        /   http://localhost:8080/
ProxyPassReverse /   http://localhost:8080/
ProxyPreserveHost on
    <Proxy *>
         AuthType basic
         AuthName "jenkins"
         AuthUserFile "/etc/apache2/.htpasswd"
         Require valid-user
    </Proxy>
</VirtualHost>

And then create an admin user in your .htpasswd file using command:

htpasswd /etc/apache2/.htpasswd admin

Make sure the password you enter matches the password of the admin user in Jenkins. Now when accessing http://jenkins.mydomain.com you will be prompted for the admin credentials and be automatically logged into Jenkins with your admin user. Pretty cool!

You can as well authenticate using a User ID and API Token. Very convenient if you want to setup a hook from your repository to trigger builds on commits. Let say you want to trigger builds from BitBucket on code push.
Create a user bitbucket in your Jenkins instance and retrieve its API Token and then configure the bitbucket user password in Apache configuration using its API Token:

htpasswd /etc/apache2/.htpasswd bitbucket

In your BitBucket project you can create a Jenkins hook using the endpoint: http://bitbucket:[API_Token]@jenkins.domain.com

The only drawback is that you have to create an Apache user for every Jenkins user.