SlideShare a Scribd company logo
1 of 11
Download to read offline
A Detailed Guide to Securing React applications with
Keycloak
Digital technology has presented us with a myriad of applications at our disposal, and you would
almost always require proper authentication to gain authorized access to the application data by
having login/logout capability. If you think from a user perspective, we have several different
identities and credentials to manage for different applications we access. Having a single set of
credentials for all of our applications would be so convenient, isn’t it? This is what the Single
Sign-On (SSO) capability provides, and it is really important for the success of an Enterprise’s
Identity and Access Management (IAM).
Keycloak is an open-source platform developed and maintained by the RedHat Community.
This product makes the developer's job easy by enabling SSO for applications and authorized
access to services with less/no codes.
"Keycloak is an open source Identity and Access Management solution aimed at modern
applications and services. It makes it easy to secure applications and services with little to no
code."
Some of the Keycloak features, such as Identity Brokering, User Federation, Client Adapters,
Admin Console, Account Management Console, Standard Protocol, Authorization Services,
Documentation and Clustering Support further enhance business applications.
In this blog, we will see how we can use Keycloak to setup identity and access management in
a ​React application​ using Google as the identity provider.
GETTING STARTED WITH KEYCLOAK
In order to get started, we first need to setup Keycloak. You can follow the official getting started
guide ​here ​to have this setup.
Quick steps to get started with Keycloak:
1. Install and boot your keycloak server by downloading the server zip file, unzipping it and
booting it using standalone.bat in windows and standalone.sh in Linux
2. Once the server boots, you can open the server in your browser using
http://localhost:8080/auth​ and see the welcome page which shows that the server is
running.
3. First create the admin account, using which you can login to the master realm’s
administration console, from which you can create other realms and users and also
register your applications to be secured by Keycloak.
The realm is like a namespace for the configuration that allows you to manage the entire
metadata/configuration within different buckets called realms. By default you get the
master realm, which should be used for administration purposes only, and you should
avoid creating your configuration in the master. You can create multiple realms based on
your requirement and create your users and register your applications within them.
4. Next you can login to the admin console (http://localhost:8080/auth/admin/) using the
admin account details you created in step 3.
5. In the admin console, you can create a new Realm called ​demo ​from the Master
drop-down menu by clicking​ Add Realm ​option.
6. Now select the newly created Realm from the drop-down, you can perform the other
metadata setup.
7. Next, create a Client for your React application which you want to secure with Keycloak
Client ID: demo
Protocol: ‘OpenID-Connect/SAML’
Root Url: Application Hostname
8. Client configuration requires details like Protocol: SAML/OpenID, Resource Endpoint:
https://localhost:3000/ (Your application host details for the React app), Redirect URI:
After the auth completes where you want to redirect.
9. Include the identity provider by adding social networks like Google, using which you want
to facilitate sign-in by providing the google app client id and secret key.
10. For this, you need to add your application in the google developers
console(​https://console.developers.google.com/​).
a. Create a new google project.
b. Setup OAuth consent screen by selecting external/internal depending on the
level of google authentication you wish to apply.
c. Create credentials by providing the keycloak
url(http://localhost:8080/auth/realms/demo/broker/google/endpoint) as the
Authorised redirect URIs. This will give you the client id and secret key which you
will use in the next step for adding identity providers.
d. Add identity provider by using the client id and client secret you got from google
console for your new application.
With the keycloak server setup up and running, we can start with our react application.
PROCESS TO SETUP REACT APPLICATION WITH KEYCLOAK
Now we will see the steps of setting up react application with keycloak.
1. Let’s first create our application using the below command.
npx create-react-app react-keycloak-app
2. Install the keycloak-js dependency
npm install keycloak-js
3. The keycloak configuration can be saved as a json file under the public folder by
creating a resources subfolder.
The keycloak.json is as follows:
{
​"realm"​: ​"demo"​,
​"auth-server-url"​: ​"http://localhost:8080/auth"​,
​"ssl-required"​: ​"none"​,
​"resource"​: ​"demo"​,
​"public-client"​: ​true​,
​"verify-token-audience"​: ​true​,
​"use-resource-role-mappings"​: ​true​,
​"confidential-port"​: ​0
}
4. The logic to include the keycloak validation can be included in index.js before rendering
the application or it can be included in a specific route when the user needs to be
prompted for sign-in.
In this example, we will include the logic of keycloak initialization and refresh in the
index.js as shown below:
import​ ​Keycloak​ ​from​ ​'keycloak-js'​;
//Get the keycloak configuration
let​ ​keycloak​ = ​Keycloak​(​'./resources/keycloak.json'​);
//Initialization of the keycloak instance
keycloak​.​init​({ ​onLoad:​ ​'login-required'​ }).​success​((​authenticated​) ​=>​ {
​if​ (!​authenticated​) {
​window​.​location​.​reload​();
} ​else​ {
​console​.​info​(​"Authenticated"​);
}
​//React Render on authentication
​ReactDOM​.​render​(​<​App​ ​/>​, ​document​.​getElementById​(​'root'​));
​//store authentication tokens in sessionStorage for usage in app
​sessionStorage​.​setItem​(​'authentication'​, ​keycloak​.​token​);
​sessionStorage​.​setItem​(​'refreshToken'​, ​keycloak​.​refreshToken​);
//to regenerate token on expiry
setTimeout​(() ​=>​ {
​keycloak​.​updateToken​(​70​).​success​((​refreshed​) ​=>​ {
​if​ (​refreshed​) {
​console​.​debug​(​'Token refreshed'​ + ​refreshed​);
} ​else​ {
​console​.​warn​(​'Token not refreshed, valid for '
+ ​Math​.​round​(​keycloak​.​tokenParsed​.​exp​ +
keycloak​.​timeSkew​ - ​new​ ​Date​().​getTime​() / ​1000​) + ​' seconds'​);
}
}).​error​(() ​=>​ {
​console​.​error​(​'Failed to refresh token'​);
});
}, ​60000​)
}).​error​(() ​=>​ {
​console​.​error​(​"Authenticated Failed"​);
});
5. The React application can now be started using the npm start command. Open browser
and navigate to localhost:3000
You will get redirected to the below login screen
Click on the google button and provide your google credentials to be authenticated and
taken to the application page as shown below:
You can find the complete code on ​github
Conclusion
In this blog, we saw how to setup Keycloak server, configure it with Google as its identity
provider and use it to secure a simple React application. With keycloak you can setup multiple
identity providers from existing social networks or setup user defined authentication servers and
use it to secure all your ​React applications​ with ease.
Follow us on :
https://www.linkedin.com/company/walking-tree-technologies/
https://www.youtube.com/channel/UCH5y9upqT2M7uWwgRWjCWBg
https://www.facebook.com/walkingtreetech
https://twitter.com/walkingtreetech

More Related Content

What's hot

OpenId Connect Protocol
OpenId Connect ProtocolOpenId Connect Protocol
OpenId Connect ProtocolMichael Furman
 
Alphorm.com Formation Implémenter une PKI avec ADCS 2012 R2
Alphorm.com Formation Implémenter une PKI avec ADCS 2012 R2 Alphorm.com Formation Implémenter une PKI avec ADCS 2012 R2
Alphorm.com Formation Implémenter une PKI avec ADCS 2012 R2 Alphorm
 
An Introduction to OAuth2
An Introduction to OAuth2An Introduction to OAuth2
An Introduction to OAuth2Aaron Parecki
 
Building secure applications with keycloak
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak Abhishek Koserwal
 
Neil Saunders (Beamly) - Securing your AWS Infrastructure with Hashicorp Vault
Neil Saunders (Beamly) - Securing your AWS Infrastructure with Hashicorp Vault Neil Saunders (Beamly) - Securing your AWS Infrastructure with Hashicorp Vault
Neil Saunders (Beamly) - Securing your AWS Infrastructure with Hashicorp Vault Outlyer
 
User Management Life Cycle with Keycloak
User Management Life Cycle with KeycloakUser Management Life Cycle with Keycloak
User Management Life Cycle with KeycloakMuhammad Edwin
 
Keycloak for Science Gateways - SGCI Technology Sampler Webinar
Keycloak for Science Gateways - SGCI Technology Sampler WebinarKeycloak for Science Gateways - SGCI Technology Sampler Webinar
Keycloak for Science Gateways - SGCI Technology Sampler Webinarmarcuschristie
 
Security for oauth 2.0 - @topavankumarj
Security for oauth 2.0 - @topavankumarjSecurity for oauth 2.0 - @topavankumarj
Security for oauth 2.0 - @topavankumarjPavan Kumar J
 
How to migrate an application in IBM APIc, and preserve its client credential
How to migrate an application in IBM APIc, and preserve its client credentialHow to migrate an application in IBM APIc, and preserve its client credential
How to migrate an application in IBM APIc, and preserve its client credentialShiu-Fun Poon
 
IBM APIc API security protection mechanism
IBM APIc API security protection mechanismIBM APIc API security protection mechanism
IBM APIc API security protection mechanismShiu-Fun Poon
 
Azure key vault
Azure key vaultAzure key vault
Azure key vaultRahul Nath
 
Monitoring on Kubernetes using prometheus
Monitoring on Kubernetes using prometheusMonitoring on Kubernetes using prometheus
Monitoring on Kubernetes using prometheusChandresh Pancholi
 
Draft: building secure applications with keycloak (oidc/jwt)
Draft: building secure applications with keycloak (oidc/jwt)Draft: building secure applications with keycloak (oidc/jwt)
Draft: building secure applications with keycloak (oidc/jwt)Abhishek Koserwal
 
Cyberark training pdf
Cyberark training pdfCyberark training pdf
Cyberark training pdfAkhil Kumar
 

What's hot (20)

OpenId Connect Protocol
OpenId Connect ProtocolOpenId Connect Protocol
OpenId Connect Protocol
 
OAuth 2.0
OAuth 2.0OAuth 2.0
OAuth 2.0
 
Alphorm.com Formation Implémenter une PKI avec ADCS 2012 R2
Alphorm.com Formation Implémenter une PKI avec ADCS 2012 R2 Alphorm.com Formation Implémenter une PKI avec ADCS 2012 R2
Alphorm.com Formation Implémenter une PKI avec ADCS 2012 R2
 
OpenID Connect Explained
OpenID Connect ExplainedOpenID Connect Explained
OpenID Connect Explained
 
An Introduction to OAuth2
An Introduction to OAuth2An Introduction to OAuth2
An Introduction to OAuth2
 
Building secure applications with keycloak
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak
 
Neil Saunders (Beamly) - Securing your AWS Infrastructure with Hashicorp Vault
Neil Saunders (Beamly) - Securing your AWS Infrastructure with Hashicorp Vault Neil Saunders (Beamly) - Securing your AWS Infrastructure with Hashicorp Vault
Neil Saunders (Beamly) - Securing your AWS Infrastructure with Hashicorp Vault
 
Webauthn Tutorial
Webauthn TutorialWebauthn Tutorial
Webauthn Tutorial
 
User Management Life Cycle with Keycloak
User Management Life Cycle with KeycloakUser Management Life Cycle with Keycloak
User Management Life Cycle with Keycloak
 
Keycloak for Science Gateways - SGCI Technology Sampler Webinar
Keycloak for Science Gateways - SGCI Technology Sampler WebinarKeycloak for Science Gateways - SGCI Technology Sampler Webinar
Keycloak for Science Gateways - SGCI Technology Sampler Webinar
 
O365 to cisco cloud guide
O365 to cisco cloud guideO365 to cisco cloud guide
O365 to cisco cloud guide
 
Introduction to OAuth2.0
Introduction to OAuth2.0Introduction to OAuth2.0
Introduction to OAuth2.0
 
Kerberos protocol
Kerberos protocolKerberos protocol
Kerberos protocol
 
Security for oauth 2.0 - @topavankumarj
Security for oauth 2.0 - @topavankumarjSecurity for oauth 2.0 - @topavankumarj
Security for oauth 2.0 - @topavankumarj
 
How to migrate an application in IBM APIc, and preserve its client credential
How to migrate an application in IBM APIc, and preserve its client credentialHow to migrate an application in IBM APIc, and preserve its client credential
How to migrate an application in IBM APIc, and preserve its client credential
 
IBM APIc API security protection mechanism
IBM APIc API security protection mechanismIBM APIc API security protection mechanism
IBM APIc API security protection mechanism
 
Azure key vault
Azure key vaultAzure key vault
Azure key vault
 
Monitoring on Kubernetes using prometheus
Monitoring on Kubernetes using prometheusMonitoring on Kubernetes using prometheus
Monitoring on Kubernetes using prometheus
 
Draft: building secure applications with keycloak (oidc/jwt)
Draft: building secure applications with keycloak (oidc/jwt)Draft: building secure applications with keycloak (oidc/jwt)
Draft: building secure applications with keycloak (oidc/jwt)
 
Cyberark training pdf
Cyberark training pdfCyberark training pdf
Cyberark training pdf
 

Similar to A Detailed Guide to Securing React applications with Keycloak - WalkingTree Technologies

Microsoft identity platform and device authorization flow to use azure servic...
Microsoft identity platform and device authorization flow to use azure servic...Microsoft identity platform and device authorization flow to use azure servic...
Microsoft identity platform and device authorization flow to use azure servic...Sunil kumar Mohanty
 
SSL Setup for Oracle 10g AS
SSL Setup for Oracle 10g ASSSL Setup for Oracle 10g AS
SSL Setup for Oracle 10g ASEnkitec
 
Community call: Develop multi tenant apps with the Microsoft identity platform
Community call: Develop multi tenant apps with the Microsoft identity platformCommunity call: Develop multi tenant apps with the Microsoft identity platform
Community call: Develop multi tenant apps with the Microsoft identity platformMicrosoft 365 Developer
 
SoftLayer API 12032015
SoftLayer API  12032015SoftLayer API  12032015
SoftLayer API 12032015Nacho Daza
 
Configuring kerberos based sso in weblogic
Configuring kerberos based sso in weblogicConfiguring kerberos based sso in weblogic
Configuring kerberos based sso in weblogicHarihara sarma
 
Microsoft identity manoj mittal
Microsoft identity manoj mittalMicrosoft identity manoj mittal
Microsoft identity manoj mittalManoj Mittal
 
CCICI CIP 1.0 Testbed - Security access implementation and reference - v1.0
CCICI CIP 1.0 Testbed - Security access implementation and reference - v1.0CCICI CIP 1.0 Testbed - Security access implementation and reference - v1.0
CCICI CIP 1.0 Testbed - Security access implementation and reference - v1.0Krishna-Kumar
 
O auth2 with angular js
O auth2 with angular jsO auth2 with angular js
O auth2 with angular jsBixlabs
 
Microservice Protection With WSO2 Identity Server
Microservice Protection With WSO2 Identity ServerMicroservice Protection With WSO2 Identity Server
Microservice Protection With WSO2 Identity ServerAnupam Gogoi
 
java and javascript api dev guide
java and javascript api dev guidejava and javascript api dev guide
java and javascript api dev guideZenita Smythe
 
Azure from scratch part 2 By Girish Kalamati
Azure from scratch part 2 By Girish KalamatiAzure from scratch part 2 By Girish Kalamati
Azure from scratch part 2 By Girish KalamatiGirish Kalamati
 
How to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST FrameworkHow to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST FrameworkKaty Slemon
 
Windows azure active directory
Windows azure active directoryWindows azure active directory
Windows azure active directoryKrunal Trivedi
 
Spring security jwt tutorial toptal
Spring security jwt tutorial   toptalSpring security jwt tutorial   toptal
Spring security jwt tutorial toptaljbsysatm
 
OAuth with Salesforce - Demystified
OAuth with Salesforce - DemystifiedOAuth with Salesforce - Demystified
OAuth with Salesforce - DemystifiedCalvin Noronha
 
Implementation of ssl injava
Implementation of ssl injavaImplementation of ssl injava
Implementation of ssl injavatanujagrawal
 
Microservices security - jpmc tech fest 2018
Microservices security - jpmc tech fest 2018Microservices security - jpmc tech fest 2018
Microservices security - jpmc tech fest 2018MOnCloud
 
Google external login setup in ASP (1).pdf
Google external login setup in ASP  (1).pdfGoogle external login setup in ASP  (1).pdf
Google external login setup in ASP (1).pdffindandsolve .com
 

Similar to A Detailed Guide to Securing React applications with Keycloak - WalkingTree Technologies (20)

Microsoft identity platform and device authorization flow to use azure servic...
Microsoft identity platform and device authorization flow to use azure servic...Microsoft identity platform and device authorization flow to use azure servic...
Microsoft identity platform and device authorization flow to use azure servic...
 
SSL Setup for Oracle 10g AS
SSL Setup for Oracle 10g ASSSL Setup for Oracle 10g AS
SSL Setup for Oracle 10g AS
 
Community call: Develop multi tenant apps with the Microsoft identity platform
Community call: Develop multi tenant apps with the Microsoft identity platformCommunity call: Develop multi tenant apps with the Microsoft identity platform
Community call: Develop multi tenant apps with the Microsoft identity platform
 
SoftLayer API 12032015
SoftLayer API  12032015SoftLayer API  12032015
SoftLayer API 12032015
 
Configuring kerberos based sso in weblogic
Configuring kerberos based sso in weblogicConfiguring kerberos based sso in weblogic
Configuring kerberos based sso in weblogic
 
Microsoft identity manoj mittal
Microsoft identity manoj mittalMicrosoft identity manoj mittal
Microsoft identity manoj mittal
 
CCICI CIP 1.0 Testbed - Security access implementation and reference - v1.0
CCICI CIP 1.0 Testbed - Security access implementation and reference - v1.0CCICI CIP 1.0 Testbed - Security access implementation and reference - v1.0
CCICI CIP 1.0 Testbed - Security access implementation and reference - v1.0
 
O auth2 with angular js
O auth2 with angular jsO auth2 with angular js
O auth2 with angular js
 
Microservice Protection With WSO2 Identity Server
Microservice Protection With WSO2 Identity ServerMicroservice Protection With WSO2 Identity Server
Microservice Protection With WSO2 Identity Server
 
java and javascript api dev guide
java and javascript api dev guidejava and javascript api dev guide
java and javascript api dev guide
 
Azure from scratch part 2 By Girish Kalamati
Azure from scratch part 2 By Girish KalamatiAzure from scratch part 2 By Girish Kalamati
Azure from scratch part 2 By Girish Kalamati
 
How to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST FrameworkHow to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST Framework
 
Windows azure active directory
Windows azure active directoryWindows azure active directory
Windows azure active directory
 
Spring security jwt tutorial toptal
Spring security jwt tutorial   toptalSpring security jwt tutorial   toptal
Spring security jwt tutorial toptal
 
OAuth with Salesforce - Demystified
OAuth with Salesforce - DemystifiedOAuth with Salesforce - Demystified
OAuth with Salesforce - Demystified
 
Zero trust Architecture
Zero trust Architecture Zero trust Architecture
Zero trust Architecture
 
Implementation of ssl injava
Implementation of ssl injavaImplementation of ssl injava
Implementation of ssl injava
 
Microservices security - jpmc tech fest 2018
Microservices security - jpmc tech fest 2018Microservices security - jpmc tech fest 2018
Microservices security - jpmc tech fest 2018
 
Google external login setup in ASP (1).pdf
Google external login setup in ASP  (1).pdfGoogle external login setup in ASP  (1).pdf
Google external login setup in ASP (1).pdf
 
O auth 2
O auth 2O auth 2
O auth 2
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

A Detailed Guide to Securing React applications with Keycloak - WalkingTree Technologies

  • 1. A Detailed Guide to Securing React applications with Keycloak Digital technology has presented us with a myriad of applications at our disposal, and you would almost always require proper authentication to gain authorized access to the application data by having login/logout capability. If you think from a user perspective, we have several different identities and credentials to manage for different applications we access. Having a single set of credentials for all of our applications would be so convenient, isn’t it? This is what the Single Sign-On (SSO) capability provides, and it is really important for the success of an Enterprise’s Identity and Access Management (IAM). Keycloak is an open-source platform developed and maintained by the RedHat Community. This product makes the developer's job easy by enabling SSO for applications and authorized access to services with less/no codes.
  • 2. "Keycloak is an open source Identity and Access Management solution aimed at modern applications and services. It makes it easy to secure applications and services with little to no code." Some of the Keycloak features, such as Identity Brokering, User Federation, Client Adapters, Admin Console, Account Management Console, Standard Protocol, Authorization Services, Documentation and Clustering Support further enhance business applications. In this blog, we will see how we can use Keycloak to setup identity and access management in a ​React application​ using Google as the identity provider. GETTING STARTED WITH KEYCLOAK In order to get started, we first need to setup Keycloak. You can follow the official getting started guide ​here ​to have this setup. Quick steps to get started with Keycloak: 1. Install and boot your keycloak server by downloading the server zip file, unzipping it and booting it using standalone.bat in windows and standalone.sh in Linux 2. Once the server boots, you can open the server in your browser using http://localhost:8080/auth​ and see the welcome page which shows that the server is running.
  • 3. 3. First create the admin account, using which you can login to the master realm’s administration console, from which you can create other realms and users and also register your applications to be secured by Keycloak. The realm is like a namespace for the configuration that allows you to manage the entire metadata/configuration within different buckets called realms. By default you get the master realm, which should be used for administration purposes only, and you should avoid creating your configuration in the master. You can create multiple realms based on your requirement and create your users and register your applications within them. 4. Next you can login to the admin console (http://localhost:8080/auth/admin/) using the admin account details you created in step 3. 5. In the admin console, you can create a new Realm called ​demo ​from the Master drop-down menu by clicking​ Add Realm ​option.
  • 4. 6. Now select the newly created Realm from the drop-down, you can perform the other metadata setup. 7. Next, create a Client for your React application which you want to secure with Keycloak Client ID: demo Protocol: ‘OpenID-Connect/SAML’ Root Url: Application Hostname
  • 5. 8. Client configuration requires details like Protocol: SAML/OpenID, Resource Endpoint: https://localhost:3000/ (Your application host details for the React app), Redirect URI: After the auth completes where you want to redirect. 9. Include the identity provider by adding social networks like Google, using which you want to facilitate sign-in by providing the google app client id and secret key. 10. For this, you need to add your application in the google developers console(​https://console.developers.google.com/​).
  • 6. a. Create a new google project. b. Setup OAuth consent screen by selecting external/internal depending on the level of google authentication you wish to apply. c. Create credentials by providing the keycloak url(http://localhost:8080/auth/realms/demo/broker/google/endpoint) as the Authorised redirect URIs. This will give you the client id and secret key which you will use in the next step for adding identity providers. d. Add identity provider by using the client id and client secret you got from google console for your new application.
  • 7. With the keycloak server setup up and running, we can start with our react application. PROCESS TO SETUP REACT APPLICATION WITH KEYCLOAK Now we will see the steps of setting up react application with keycloak. 1. Let’s first create our application using the below command. npx create-react-app react-keycloak-app 2. Install the keycloak-js dependency npm install keycloak-js 3. The keycloak configuration can be saved as a json file under the public folder by creating a resources subfolder. The keycloak.json is as follows: {
  • 8. ​"realm"​: ​"demo"​, ​"auth-server-url"​: ​"http://localhost:8080/auth"​, ​"ssl-required"​: ​"none"​, ​"resource"​: ​"demo"​, ​"public-client"​: ​true​, ​"verify-token-audience"​: ​true​, ​"use-resource-role-mappings"​: ​true​, ​"confidential-port"​: ​0 } 4. The logic to include the keycloak validation can be included in index.js before rendering the application or it can be included in a specific route when the user needs to be prompted for sign-in. In this example, we will include the logic of keycloak initialization and refresh in the index.js as shown below: import​ ​Keycloak​ ​from​ ​'keycloak-js'​; //Get the keycloak configuration let​ ​keycloak​ = ​Keycloak​(​'./resources/keycloak.json'​); //Initialization of the keycloak instance keycloak​.​init​({ ​onLoad:​ ​'login-required'​ }).​success​((​authenticated​) ​=>​ { ​if​ (!​authenticated​) { ​window​.​location​.​reload​(); } ​else​ { ​console​.​info​(​"Authenticated"​); } ​//React Render on authentication
  • 9. ​ReactDOM​.​render​(​<​App​ ​/>​, ​document​.​getElementById​(​'root'​)); ​//store authentication tokens in sessionStorage for usage in app ​sessionStorage​.​setItem​(​'authentication'​, ​keycloak​.​token​); ​sessionStorage​.​setItem​(​'refreshToken'​, ​keycloak​.​refreshToken​); //to regenerate token on expiry setTimeout​(() ​=>​ { ​keycloak​.​updateToken​(​70​).​success​((​refreshed​) ​=>​ { ​if​ (​refreshed​) { ​console​.​debug​(​'Token refreshed'​ + ​refreshed​); } ​else​ { ​console​.​warn​(​'Token not refreshed, valid for ' + ​Math​.​round​(​keycloak​.​tokenParsed​.​exp​ + keycloak​.​timeSkew​ - ​new​ ​Date​().​getTime​() / ​1000​) + ​' seconds'​); } }).​error​(() ​=>​ { ​console​.​error​(​'Failed to refresh token'​); }); }, ​60000​) }).​error​(() ​=>​ { ​console​.​error​(​"Authenticated Failed"​); }); 5. The React application can now be started using the npm start command. Open browser and navigate to localhost:3000 You will get redirected to the below login screen
  • 10. Click on the google button and provide your google credentials to be authenticated and taken to the application page as shown below:
  • 11. You can find the complete code on ​github Conclusion In this blog, we saw how to setup Keycloak server, configure it with Google as its identity provider and use it to secure a simple React application. With keycloak you can setup multiple identity providers from existing social networks or setup user defined authentication servers and use it to secure all your ​React applications​ with ease. Follow us on : https://www.linkedin.com/company/walking-tree-technologies/ https://www.youtube.com/channel/UCH5y9upqT2M7uWwgRWjCWBg https://www.facebook.com/walkingtreetech https://twitter.com/walkingtreetech