Why use Keycloak
Keycloak is an open-source id supplier (IdP) utilizing single sign-on (SSO). An IdP is a device to create, keep, and handle id data for principals and to supply authentication companies for functions in a distributed community. Keycloak means that you can create a number of safety coverage domains referred to as realms to handle objects reminiscent of customers, functions, roles, and teams. It additionally allows you to register a number of customers for a similar software. Keycloak is both configured by a person interface referred to as Admin Console or CLI instructions.
A non-exhaustive record of use-cases contains:
- Integration in a Kubernetes Cluster for authentication
- Arrange Keycloak for enabling login with social networks
- Arrange Keycloak as id dealer for one more IdP
This text explains arrange Keycloak in an AWS EC2 occasion and make the id supplier publicly obtainable by the web.
1 Arrange the EC2 occasion
The principle objective of the article is to know arrange Keycloak in an AWS EC2 occasion and never launch an EC2 occasion on AWS. Nonetheless, three totally different strategies to configure and launch the EC2 occasion are described on this article to adapt to the readers’ consolation and to particularly present which sources are required. If you’re solely taken with establishing the sources as quick as potential and wish the scripts for idempotent replica, we advocate you skip elements 1.1 and 1.2 and go on to half 1.3.
1.1 Use the Internet Interface
1.1.1 Create the EC2 occasion the primary time
Launching the EC2 occasion by the net interface is the user-friendliest answer.
You may as well observe the official documentation on create an AWS EC2 occasion. Nonetheless, the next factors present the occasion configuration steps.
Log into your AWS account.
Go to the area which fits you finest, usually the closest to you.
Within the higher process bar kind EC2 and go to this service.
Click on on
Launch Occasion
.Select
Launch Occasion
once more.Keycloak in a Docker container doesn’t require loads of sources. Subsequently, we select a T2 micro occasion with the minimal disk area. Putting in Docker on an Amazon Linux AMI could be very straightforward and we subsequently use it.
Give the occasion a reputation.
In
Software and OS Photographs (Amazon Machine Picture)
select the free tierAmazon Linux 2 Kernel 5.10 AMI 2.0.20221103.3 x86_64 HVM gp2
AMI.
Select the free tier
t2.micro
kind in “Occasion kind”.If you have already got a key pair select it within the interface in any other case create one and click on on the kind
RSA
.In community settings SSH port 22 which is there by default permits us to log into the occasion from one other machine. Nonetheless, Keycloak hosted on our EC2 occasion wants entry to the general public web, we subsequently open both port 8080 and/or port 8443 with the TCP protocol. Set the supply to
Anyplace
; this enables all customers outdoors the digital non-public community (VPC) to entry the EC2 occasion. Click on onEdit
, thenAdd safety group rule
and add the small print talked about beforehand.
- Depart the storage how it’s to eight GB.
- In
Superior particulars
, there’s the likelihood to request a spot occasion for value saving, nevertheless, remember the fact that AWS can terminate the occasion at any second. On this similar part belowConsumer knowledge
add the next code to put in Docker and Postgres at launch. The explanation why we set up Postgres can be defined in a while.
#!/bin/bash
sudo yum replace -y
sudo amazon-linux-extras set up docker
sudo service docker begin
sudo amazon-linux-extras allow postgresql13
sudo yum set up postgresql postgresql-server -y
sudo postgresql-setup initdb
sudo systemctl begin postgresql
sudo systemctl allow postgresql
Should you overlook to stick this code in Consumer knowledge
earlier than launching the occasion, you’ll nonetheless be capable of run every code line individually within the created EC2 occasion afterwards.
1.1.2 Create and use a launch template
Create a launch template from the beforehand created occasion to simply reproduce the set-up.
As proven within the picture, click on on the occasion.
Then click on on
Actions
.And eventually click on on
Create Template from Occasion
.
The launch template has been created and subsequent time launch the occasion from this template by clicking on Launch occasion from template
within the EC2 dashboard web page as proven within the second picture of the article.
1.2 Use the AWS CLI instructions
If in case you have AWS CLI put in in your PC and are comfy with the CLI instructions, you might use them to arrange the occasion.
1.2.1 Arrange the occasion the primary time
Log in your AWS account with the next command after which give your credentials as defined within the official documentation
Give your entry key and personal entry key, then set your default area and select
json
because the default output format.Create a key for the EC2 occasion in your default area should you would not have one but.
aws ec2 create-key-pair --key-name <your_key_name> --query 'KeyMaterial' --output textual content > your_key_name.pem
Get your default VPC Id.
aws ec2 describe-vpcs | grep VpcId
Create a safety group.
aws ec2 create-security-group --group-name <security-group-name> --description "check the cli safety group" --vpc-id <your-vpc-id>
Open ports 22, and do the identical command for port 8080 and/or port 8443 by simply changing the port quantity.
aws ec2 authorize-security-group-ingress --group-id <sg-id> --protocol tcp --port 22 --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress --group-id <sg-id> --protocol tcp --port 8080 --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress --group-id <sg-id> --protocol tcp --port 8443 --cidr 0.0.0.0/0
Launch an EC2 occasion of kind T2 micro with an Amazon Linux AMI and with the Docker set up bash script. Paste the Docker set up code in a bash script and identify it the identical as in
user-data
of therun-instance
command.aws ec2 run-instances --image-id ami-01cae1550c0adea9c --count 1 --instance-type t2.micro --key-name <your-keyname> --security-group-ids <your-sg-id> --user-data file://<docker-install-file-name>
The next command creates a tag for the occasion regardless that it’s not obligatory.
aws ec2 create-tags --resources <InstanceID> --tags Key=Title,Worth=Keycloak
To terminate the occasion, use the next command:
aws ec2 terminate-instances --instance-ids <instance-id>
1.2.2 Utilizing a launch template for reproducibility
Let’s put in a template file all these settings from the prevailing occasion that has been created to breed the identical setup every time we launch the occasion.
First get the occasion Id with the next command.
aws ec2 describe-instances | grep "InstanceId"
Observe that in case you have a number of cases working on the similar time, you should have a number of Ids. You need to subsequently exclude the
| grep "InstanceId"
from the command and, within the lengthy description, look which occasion is anxious.Now extract all data to a json file by changing the
instance-id
.aws ec2 get-launch-template-data --instance-id <your-instance-id> --query "LaunchTemplateData" >> instance-data.json
With the obtained file, create a launch template.
aws ec2 create-launch-template --launch-template-name TemplateForWebServer --version-description Version1 --tag-specifications 'ResourceType=launch- template,Tags=[Key=purpose,Value=Keycloak]' --launch-template-data file://instance-data.json
Textual content in json format will seem on the console with the launch template Id.
If the launch template has already been created, get its Id with the next command.
aws ec2 describe-launch-template-versions
--versions "$Newest,$Default"
As soon as we’ve the launch template and its Id, launch the EC2 occasion as follows
aws ec2 run-instances --launch-template LaunchTemplateId=<launch-template-id>
1.3 Create the EC2 occasion with Terraform
One other solution to create all sources from scratch is to make use of Terraform. Terraform destroys all created sources with a easy command. On this case, it not solely deletes the EC2 occasion, but in addition the safety group. The consolation of the Terraform scripts under is that they’re relevant to all AWS customers and subsequently not custom-made for a particular one.
Remember the fact that the one ingredient that the scripts under don’t create is a brand new AWS SSH key for the occasion. Should you would not have one but, please check with the earlier AWS CLI command or go within the internet interface to create one and ensure it’s created in the identical area the place you wish to launch the EC2 occasion.
Verify if Terraform is put in, if not, discover the directions on the hashicorp web site and confirm that the model is superior to 1.2.8 with the command
terraform model
on the command line.Create a
important.tf
file and paste the next codeterraform required_version = ">= 1.2.8" useful resource "aws_default_vpc" "default" tags = Title = "Default VPC" useful resource "aws_security_group" "sg" identify = var.security_group_name description = "Enable inbound site visitors on port 8080 and 8443" vpc_id = aws_default_vpc.default.id ingress description = "open ssh port" from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] ingress description = "open port 8080" from_port = 8080 to_port = 8080 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] ingress description = "open port 8443" from_port = 8443 to_port = 8443 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] egress from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] tags = Title = var.security_group_name useful resource "aws_instance" "ec2" ami = "ami-01cae1550c0adea9c" instance_type = "t2.micro" key_name=var.keyname vpc_security_group_ids = [aws_security_group.sg.id] user_data = <<-EOF #!/bin/bash sudo yum replace -y sudo amazon-linux-extras set up docker sudo service docker begin sudo amazon-linux-extras allow postgresql13 sudo yum set up postgresql postgresql-server -y sudo postgresql-setup initdb sudo systemctl begin postgresql sudo systemctl allow postgresql EOF tags = Title = var.aws_instance_name output "instance_ip" worth = "$aws_instance.ec2.public_ip" description = "Public IP deal with" output "instance_dns" worth = "$aws_instance.ec2.public_dns" description = "Public DNS"
Now create a
suppliers.tf
file and paste the next code. Kind the AWS area the place the sources ought to be created and the place the SSH secret is situatedsupplier "aws" area = "<aws-region>"
Lastly create a
variables.tf
file, paste the next code and substitute the variable namesvariable "keyname" kind = string default = "<your-keyname>" variable "security_group_name" kind = string default = "<your-security-group-name>" variable "aws_instance_name" kind = string default = "<your-instance-name>"
As soon as the three recordsdata have been created let’s initialize the surroundings
Let’s test that no errors have been written within the recordsdata
Now launch the arrange
- Use the
terraform refresh
command to get the knowledge of the created sources once more. - Apply the
terraform destroy
command to destroy all sources created by terraform for the surroundings.
2 Log into the EC2 occasion
We both get the general public DNS identify or the general public IP deal with of the occasion outputted by the terraform script. Alternatively, apply the next command to get the general public DNS
aws ec2 describe-instances | grep "PublicDnsName"
If in case you have a number of ec2 cases, pass over the | grep "PublicDnsName"
and search the knowledge comparable to your EC2 occasion within the lengthy json script which is proven on the display screen.
If vital be certain that the SSH key isn’t publicly viewable
Log within the occasion by SSH, it could take a couple of minutes for the occasion to launch.
ssh -i "<key-name>" ec2-user@<Public-DNS-Title or Public-IP>
3 Create a Docker container with Keycloak
3.1 Demo instance in growth mode
Now we create a Docker container working Keycloak publicly for a demo objective.
To keep away from the
sudo
command for Docker, kind the code under, exit your occasion and log again in once moresudo usermod -aG docker $USER
Now let’s pull the picture. On the time of writing the most recent model is 20.0.3.
docker pull quay.io/keycloak/keycloak:newest
Run the container by enabling port 8080 contained in the container and on the occasion.
export KEYCLOAK_DEV_ADMIN_PASSWORD=<your password> docker run -d --name keycloak-dev -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=$KEYCLOAK_DEV_ADMIN_PASSWORD quay.io/keycloak/keycloak:newest start-dev
If we kind
docker ps
we see that the container is working on port 8080.
- Open the net browser with [ to entry the web page under.
Nonetheless, if we click on on Administration Console
we can’t log in as a result of the information stream between your EC2 occasion and the general public web is by default protected with SSL encryption in Keycloak.
And including https:// in entrance of the general public IP solely provides an error as follows
If we join with a machine inside our VPC, we can have entry to the console. On this instance, we disable the SSL/TLS requirement to have entry to Keycloak by the general public web.
To deactivate SSL/TLS let’s enter the container in interactive mode.
docker exec -it keycloak-dev bash
Within the container set the trail to make use of the
kcadm.sh
script.export PATH=$PATH:/choose/keycloak/bin
Then run the next command to set the server and the person of the grasp realm.
kcadm.sh config credentials --server --realm grasp --user admin --password <your password>
By typing the next command, we get the realm particulars outputted in json format and we see that the worth for
sslRequired
is about toexterior
on the backside of the image. This means that SSL/TLS is required outdoors of our VPC.kcadm.sh get realms/grasp
Disable the SSL/TLS requirement for the grasp realm.
kcadm.sh replace realms/grasp -s enabled=true -s sslRequired=none
Now on the browser click on on “Administration Console” once more and this time the login web page seems.
- Give the credentials and procure the next web page.
- If we go within the grasp realm to
Realm settings
,the tabRequire SSL
is now set toNone
.
Remember the fact that disabling the SSL/TLS requirement isn’t really helpful in manufacturing mode and/or should you cope with delicate knowledge.
Earlier than turning to the following part, cease the container with the command docker cease keycloak-dev
for the reason that new container would require the identical host port. Delete it with docker rm keycloak-dev
as it’s not getting used any longer.
3.2 Deploy Keycloak in manufacturing mode with a self-signed SSL/TLS certificates
You may marvel why we’ve put in Postgres with the person knowledge since we didn’t use it but. Keycloak comes with an in-memory database referred to as H2. Nonetheless, it’s inadequate for big knowledge and subsequently not really helpful to be used in manufacturing mode. That’s the reason why we put in an exterior database to connect with Keycloak. On this case we use Postgres, nevertheless you’ve got the selection to attach different databases reminiscent of Oracle or MySQL.
If in case you have not finished the demo instance in growth mode, carry out step 1 and a pair of of that part and proceed from right here on.
Verify that Postgres is working
sudo systemctl standing postgresql
Postgres has already a person created referred to as
postgres
. Let’s set the database password after which kindexit
to go away.sudo su - postgres psql -c "ALTER USER postgres WITH PASSWORD '<your password>';"
Open file
/var/lib/pgsql/knowledge/pg_hba.conf
withnano
orvim
as root person. Underneath part# IPv4 native connections:
, remark outhost all all 127.0.0.1/32 ident
and addhost all postgres 127.0.0.1/32 md5
. This motion allows solely the person postgres on the localhost to entry the database with a password. Postgres has no different objective than being utilized by Keycloak in our case. You could find extra about authentication strategies on the Postgres web site.
Restart Postgres.
sudo systemctl restart postgresql
Create a folder for the SSL certificats.
mkdir certificates cd certificates
Create the self-signed certificat and the important thing in pem format.
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
Set passwords and hostname. The database password should be similar because the one you’ve got set beforehand in Postgres.
export KEYCLOAK_ADMIN_PASSWORD=<your keycloak admin password> export DB_PASSWORD=<your db password> export KEYCLOAK_HOSTNAME=<your public ip>:8443
Create the container with the next command.
docker run -d --name keycloak-prod -v /residence/ec2-user/certificates:/certificates --network=host -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=$KEYCLOAK_ADMIN_PASSWORD quay.io/keycloak/keycloak:newest begin --features=token-exchange --https-certificate-file=/certificates/cert.pem --https-certificate-key-file=/certificates/key.pem --hostname=$KEYCLOAK_HOSTNAME --proxy=edge --db=postgres --db-url=jdbc:postgres://localhost:5432/postgres --db-username=postgres --db-password=$DB_PASSWORD
Right here we mount a quantity with the certificates to the container. Keycloak then shops them in a keystore with the choices
--https-certificate-file
and--https-certificate-key
. Extra about configuring TLS is on the Keycoak web site.We order the container to make use of the identical community because the host with
--network=host
. Subsequently we would not have to do any community configuration on the container. Keycloak makes use of by default port 8080 and 8443 for respectively http and https. Postgres is related by its default port 5432.Right here, we set the general public IP deal with as hostname as we wish the Admin Console to be viewable on the general public web. With the choice
--proxy=edge
, our server is working behind a TLS termination proxy. Learn the official documentation for additional data on this subject.The final choices within the command are obligatory to attach the Postgres database put in on the EC2 occasion to the container.
After about 30 seconds, open the net browser with [ to entry the web page under in Firefox
Since we used a self-signed certificates we get a warning message. In Firefox, click on on
Superior
and settle for the chance and the browser hyperlinks you then to the identical console seen above.
Now that we’ve entry to the Admin Console, we will use it for any additional operations reminiscent of creating shoppers or customers, which is defined within the Keycloak documentation.
Utilizing the CLI instructions
Using the CLI instructions first necessitates the configuration of the truststore.
Subsequently, enter the container like within the earlier part.
docker exec -it keycloak-prod bash
Set the trail for the executable recordsdata.
export PATH=$PATH:/choose/keycloak/bin
Create a
truststore.jks
file along with your pem certificates after which selected a password.cd /choose/keycloak keytool -import -alias root -keystore truststore.jks -file /certificates/cert.pem
Configure the truststore to make use of the
truststore.jks
filekcadm.sh config truststore --trustpass <trustsore password> ~/truststore.jks
Any longer, utilizing additional CLI instructions doesn’t differ from the demo instance in growth mode. You could find extra CLI instructions within the official documentation.
We now have lastly setup Keycloak in a Docker container on an EC2 occasion and it’s prepared for any additional operations.
Don’t forget to terminate all of your created sources as soon as they’re not being wanted.
#Keycloak #deployment #EC2