0% found this document useful (0 votes)
265 views42 pages

How To Secure Your Spring Apps With Keycloak: Thomas Darimont

The document discusses how to secure Spring applications with Keycloak, an open source identity and access management solution, including an overview of Keycloak's features for single sign-on, authentication, authorization, and securing applications using protocols like OAuth 2.0 and OpenID Connect along with JSON web tokens. It also provides a high-level look at Keycloak's architecture and how single sign-on works through browser-based flows that redirect users to Keycloak for authentication before accessing applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
265 views42 pages

How To Secure Your Spring Apps With Keycloak: Thomas Darimont

The document discusses how to secure Spring applications with Keycloak, an open source identity and access management solution, including an overview of Keycloak's features for single sign-on, authentication, authorization, and securing applications using protocols like OAuth 2.0 and OpenID Connect along with JSON web tokens. It also provides a high-level look at Keycloak's architecture and how single sign-on works through browser-based flows that redirect users to Keycloak for authentication before accessing applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

How to secure your Spring Apps with Keycloak

Thomas Darimont
@thomasdarimont
Thomas Darimont

• Fellow
• Spring Data Team Alumni
• Open Source Enthusiast
• Organizer Java User Group Saarland
• Keycloak Contributor for over 3 years
The Journey

• Keycloak
• Single Sign-on
• Securing Applications
• Keycloak in the field
Keycloak
Overview
Project

• Started in 2013, broad adoption since 2015


• Apache License, Red Hat Developers
• Latest stable version 5.0.0.Final ~ every 6 Weeks
• Commercial Offering Available → Red Hat SSO
• Vital Community with 300+ Contributors 1.700+ Forks
• Very robust, good documentation, many examples
Features

• Single Sign-on and Single Sign-out


• Standard Protocols OAuth 2.0, OIDC 1.0, SAML 2.0, Docker Auth
• Flexible Authentication and Authorization
• Multi-Factor Authentication One-time Password
• Social Login Google, Facebook, Twitter,...
• Provides centralized User Management
• Supports Directory Services
• Customizable and Extensible
• Easy Setup and Integration
Main Concepts
Keycloak
Quick Tour
Admin Console Login
Admin Console
Technology Stack 5.0.0.RELEASE

Admin Console
● Angular JS (1.6.x)
● PatternFly
● Bootstrap

Keycloak Server
● Wildfly 15.0.x
● JAX-RS (Resteasy)
● JPA (Hibernate)
● Infinispan (JGroups)
● Freemarker
● Jackson 2.x
● JBoss Logging
● Apache Directory API
● Commons HTTP Client
Server Architecture
Admin Account Login
INFO Account ODIC SAML
Console Frontend Frontend

Account Login SSO Protocols

REST API
Admin
Protocol Mapper

Realm

Keycloak2
2
Keycloak
Admin

Infinispan
Client

Infinispan
Keycloak1 Replication

Admin Clients, Users, AuthN, Sessions


CLI AuthZ, Policies, ... Realms
Settings
...
Identity User Storage
User Social
Events Brokering
Federation Login JPA
ODIC SAML

Directory Service HTTP Endpoint


Log Google
LDAP(S) Identity
Kerberos Facebook Database
Active Provider
Directory ...
Single Sign-on with Keycloak
How it works
Single Sign-on & Single Logout

• SSO ⇒ Login once to access all applications


• Standardized Protocols
• OpenID Connect 1.0 (OIDC)
• Security Assertion Markup Language 2.0 (SAML)
• Browser based “Web SSO”
• works for Web, Mobile and Desktop Apps
• Support for Single Logout
• Logouts can be propagated to clients
• Clients can opt-in
Web SSO with OIDC*: Unauthenticated User
Code
4
Tokens 1 Unauthenticated User accesses App
5
(Access | Refresh | ID) Token
2 App redirects to Keycloak for Login
3 ?code=...
Keycloak App 1 2a User submits Credentials to Keycloak
sso.acme.io ?redirect_uri=... app.acme.io
logged in logged in 2b Keycloak validates Credentials
2
2b 5a
3 Keycloak creates SSO Session
C

Cookies and redirects User to App


re
d

Browser
en
tia

4 App exchanges Code to Tokens


ls

with Keycloak via separate Channel


2a 1
5 App verifies received Tokens and
associates it with a session
User
5a User is now logged-in to App
Web SSO with OIDC: Authenticated User
Code
9 ...
Tokens
10 6 Authenticated user accesses App 2

8 7 App 2 redirects user to Keycloak


Code for login
Keycloak App 2
sso.acme.io app2.acme.io 8 Keycloak detects SSO Session,
logged in logged in generates code, redirects to App 2
7
10a
9 App 2 exchanges code for tokens
with Keycloak via separate channel
Browser
10 App 2 verifies received tokens and
6
associates it with a session

10a User is now logged-in to App 2


User
Keycloak Tokens
• OAuth 2 / OpenID Connect
• Signed self-contained JSON Web Token
• Claims: Metadata + User information
• Issued by Keycloak, signed with Realm Private Key
• Verified with Realm Public Key
• Limited lifespan; can be revoked

• Essential Token Types


• Access-Token short-lived (Minutes) → used for accessing Resources
• Refresh-Token long-lived (Days) → used for requesting new Tokens
• Offline-Token special Refresh-Token that “never” expires
• IDToken contains information about User (OIDC)
JSON Web Tokens
<header-base64>.<payload-base64>.<signature-base64>

Note
Base64 means Encoding
Encoding != Encryption

https://jwt.io
Keycloak JSON Web Token Example
Calling Backend Services with Access-Token
1 Authenticated User accesses App
1
App
app.acme.io 2 App uses Access-Token in HTTP
Header to access backend
logged in
Browser
3 Backend looks-up Realm Public
2 5
Key in cache with in Kid from JWT
Authorization: Bearer eyJhbG... Access
Token 4 3a If not found, fetch Public Key with
Kid from Keycloak

Keycloak Backend 3b Keycloak returns Realm Public Key


3b Public Key api.acme.io
sso.acme.io Backend verifies signature of
Bearer-only 4
Access-Token with Realm Public Key
Kid 3a
3 Backend Service grants access and
5
returns user data
Keycloak Client Integrations
Keycloak Integration Options
• OpenID Connect Adapters
• Spring Security, Spring Boot, ServletFilter, Tomcat, Jetty, Undertow, Wildfly, JBoss EAP,…
• NodeJS, JavaScript, Angular, AngularJS, Aurelia, CLI & Desktop Apps…

• SAML Adapters
• ServletFilter, Tomcat, Jetty, Wildfly ...

• Reverse Proxies
• Keycloak Gatekeeper, dedicated Proxy, written in Go, injects auth info into HTTP headers
• Apache mod_auth_oidc for OpenID Connect
• Apache mod_auth_mellon for SAML

• Others see OIDC and SAML


Keycloak Demo Securing Apps
Demo Environment

Web based Single Sign-On

WS-Chat Frontend Plain JS App Frontend


Spring Boot Spring Boot Javascript Spring Boot
OIDC Confidential OIDC Confidential OIDC Public Client SAML

Authorization: Bearer $ACCESS_TOKEN

Backend
Spring Boot
OAUTH Bearer-only
Demo Securing Apps
thomasdarimont/keycloak-docker-demo
Let’s see Keycloak in action :)
Keycloak in the Field
How can a Keycloak environment look like?
Demo Environment
Desktop App PlainJS App Frontend Backend SAML App
JavaFX JavaScript Spring Boot Spring Boot Spring Boot

HTTPS Dataflow
sso.tdlabs.local Reverse Proxy
Distributed Cache
Load Balancer / WAF
JGroups / Infinispan
SSL Termination
HTTP(S)

GELF/JSON JMS
Graylog Keycloak
Keycloak Active MQ
Keycloak

JDBC

Log Monitoring Message Broker


Alerts Provisioning
Dashboards Postgres
Postgres Messages
Keycloak with Graylog+ActiveMQ in Action
Summary

• Easy to get started


• unzip & run, Keycloak Docker Images
• Provides many features out of the box
• SSO, Social Login, Federation, User Management,...
• Builds on proven and robust standards
• OAuth 2.0, OpenID Connect 1.0, SAML 2.0
• Very extensible and easy to integrate
• Many extension points & customization options
• A pivotal part of modern Identity Management
THANKS!
Q&A

Thomas Darimont
@thomasdarimont
Links

• Keycloak Website • SAML


• Keycloak Docs • JSON Web Tokens
• Keycloak Blog • Awesome Keycloak
• Keycloak User Mailing List • Keycloak Dockerized Examples
• Keycloak Developer Mailing List • Keycloak Quickstarts Example
Projects
• OpenID Connect
Tips for working with Keycloak

• Learn to configure Wildfly → Booktip: Wildfly Cookbook


• Keep your Tokens small → HTTP Header limits!
• Only put in the tokens what you really need → Full Scope Allowed = off
• Keycloak provides a Realm-scoped Admin Console
• http://kc-host:8080/auth/admin/my-realm/console
• Admin users need permissions for realm-management in my-realm
• Secure your Keycloak Installation!
• Keycloak exposes some undocumented Endpoints by default on server AND client!
• Inspect other Keycloak instances to learn what to hide
• Google Search for Keycloak Endpoints
• Shodan search for Keycloak
Keycloak Extensions
How to tech Keycloak new tricks?
Keycloak Extension Points

• Extensions via Service Provider Interfaces


• Custom Authentication Mechanisms
• Custom “Required Actions”
• Custom User Storage (JDBC, REST, etc.)
• Event Listener (Provisioning, JMS)
• Credential Hashing Mechanisms
• Custom REST Endpoints
• Custom Themes
• … many more
Keycloak Extension Example
Custom Dashboard Extension

Please vote :) https://issues.jboss.org/browse/KEYCLOAK-1840


Authentication & Authorization

• Authentication (AuthN)
• Determines who the user is
• Internal & Federated User Storage Kerberos, LDAP, Custom
• Customizable
• Authorization (AuthZ)
• Determines what the user is allowed to do
• Hierarchical Role-based Access Control (HRBAC)
• Authorization Services
• Flexible Access Control Management
• More Variants like ABAC, UBAC, CBAC supported
Supported Single Sign-on Protocols

• OpenID Connect 1.0


• Protocol based on OAuth 2.0
• Uses OAuth 2.0 tokens + IDToken to encode Identity
• Tokens are encoded as JSON Web Tokens (JWT)
• Requires secure channel HTTPS/TLS
• SAML 2.0 Security Assertion Markup Language
• Very mature standard & common in enterprise environments
• XML based protocol
• Uses XML signature and encryption
• Docker Registry v2 Authentication
Accessing the API Backend with CURL
1 Request new Tokens via Password Credentials Grant (Direct Access Grants in Keycloak)
KC_RESPONSE=$(curl -X POST \
http://sso.tdlabs.local:8899/u/auth/realms/acme/protocol/openid-connect/token \
-d 'grant_type=password' \
-d 'username=tester&password=test' \
-d 'client_id=app-frontend-springboot&client_secret=4822a740-20b9-4ff7-bbed-e664f4a70eb6' \
)

2 Extract AccessToken
KC_ACCESS_TOKEN=$(echo $KC_RESPONSE | jq -r .access_token)
# eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJGY3RMVHJqeWRxYkpISGZ0d29U ...

3 Use AccessToken in Authorization Header


curl \
-H "Authorization: Bearer $KC_ACCESS_TOKEN" \
http://apps.tdlabs.local:20000/todos/search/my-todos
Desktop Applications
• Two ways to integrate Desktop Applications
• Direct Access Grants - no SSO
• KeycloakInstalled Adapter - SSO

• Direct Access Grants


• Client sends HTTP POST request to Keycloaks /token Endpoint
• client_id, username, password, grant_type=password
• Keycloak returns Tokens (Access-, ID-, Refresh-Token)
• Client needs to parse & validate tokens
• Client sees password → Password Anti-Pattern
• KeycloakInstalled Adapter
• Enables OAuth2 authorization code flow for Desktop / CLI apps
• Code to Token exchange via short lived ServerSocket@localhost
• Uses Keycloak Login via Browser
• Can reuse existing SSO session
Using the KeycloakInstalled Adapter
1 Add Maven Dependency <dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-installed-adapter</artifactId>
<version>${keycloak.version}</version>
</dependency>
2 Export keycloak.json for Client { "realm": "acme",
"auth-server-url": "http://sso.tdlabs.local:8899/u/auth",
"ssl-required": "external",
"resource": "app-frontend-javafx",
"public-client": true, "use-resource-role-mappings": true }

3 Create KeycloakInstalled KeycloakInstalled keycloak = new KeycloakInstalled();

4 Trigger Browser login keycloak.loginDesktop();

5 Read current username keycloak.getIdToken().getPreferredUsername()

6 Read & use AccessToken string String token = keycloak.getTokenString(10, TimeUnit.SECONDS);


httpClient.header("Authorization", "Bearer " + token);
7 Trigger Browser Logout 41
keycloak.logout()
Keycloak OAuth / OpenID Connect Tokens

Token Types Claims Verification


• Access-Token • UserInfo + Metadata • Verify Signature with
• Refresh-Token • Signed self-contained JWT Realm Public Key
• Offline-Token • Limited Lifespan • Token Introspection
• ID-Token (OIDC) • May be revoked Endpoint

You might also like