Transcription
Opensource Identity & AccessManagement with Keycloak
Thomas Darimont FellowPivotal Spring Team AlumniOpen Source EnthusiastJava User Group SaarlandKeycloak Contributor for over 4 years@thomasdarimont@jugsaar
The Journey Keycloak Single Sign-on Securing Applications Keycloak in the Field
KeycloakOverview
https://www.keycloak.org
Project Java based Authentication & Authorization ServerStarted in 2013, broad adoption since 2015Apache License, Red Hat DevelopersKeycloak Community Free Version (current 7.0.0)Red Hat SSO Commercial OfferingVital Community with 320 Contributors 2.100 ForksVery robust, good documentation, many examples
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
Features Single Sign-on and Single Sign-outStandard Protocols OAuth 2.0, OIDC 1.0, SAML 2.0Flexible Authentication and AuthorizationMulti-Factor Authentication One-time PasswordsSocial Login Google, Facebook, Twitter,., Azure, ADFS, Auth0Provides centralized User ManagementSupports Directory ServicesCustomizable and ExtensibleEasy Setup and Integration
Main ConceptsKeys
KeycloakQuick TourAdmin Console
Admin Console
Self-Service Account Management
Technology Stack 7.0.0 RELEASEAdmin Console Angular JSPatternFlyBootstrapKeycloak Server WildflyJAX-RS (Resteasy)JPA (Hibernate)Infinispan (JGroups)FreemarkerJackson 2.xLiquibaseJBoss LoggingApache Directory APICommons HTTP Client
Server ArchitectureAccountAccountFrontendAdminCLISSO ProtocolsProtocol MapperClients, Users, AuthN,AuthZ, Policies, EST onsRealmsSettings.User StorageJPASAMLHTTP EndpointDirectory ogleFacebook.Database
Single Sign-on with KeycloakHow it works
Single Sign-on 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” Web, Mobile and Desktop Apps Support for Single Logout Logouts can be propagated to applications Applications can opt-in
Web SSO with OIDC*: Unauthenticated UserCode4Tokens?code .KeycloakApp 1?redirect uri .sso.acme.iologged inUnauthenticated User accesses App2App redirects to Keycloak for Login2aUser submits Credentials to Keycloak2bCredentials OK? Keycloak createsSSO Session and emits Cookies5(Access Refresh ID) Token31app.acme.iologged in25a2bBrowser4lstiaendreC312aUser*) OpenID Connect with OAuth 2.0 Authorization Code Grant FlowGenerates Code and redirects Userback to AppApp exchanges Code to Tokenswith Keycloak via separate Channel5App verifies received Tokens andassociates it with a session5aUser is now logged-in to App
Web SSO with OIDC: Authenticated UserCode.9Tokens108CodeKeycloaksso.acme.iologged in6Authenticated user accesses App 27App 2 redirects user to Keycloakfor login8Keycloak detects SSO Session,generates code, redirects to App 29App 2 exchanges code for tokenswith Keycloak via separate channel10App 2 verifies received tokens andassociates it with a sessionApp 27app2.acme.iologged in10aBrowser610a User is now logged-in to App 2User
Keycloak Tokens OAuth / OpenID Connect Signed self-contained JSON Web TokenClaims: KV-Pairs with User information MetadataIssued by Keycloak, signed with Realm Private KeyVerified by Client with Realm Public KeyLimited lifespan, can be revoked Essential Token Types Access-Token short-lived (Minutes ) used for accessing ResourcesRefresh-Token longer-lived (Hours ) used for requesting new TokensIDToken contains User information (OIDC)Offline-Token long-lived (Days ) “Refresh-Token” that “never” expires
JSON Web Tokens header-base64 . payload-base64 . signature-base64 NoteBase64 means EncodingEncoding ! Encryptionhttps://jwt.io
Keycloak JSON Web Token Examplehttps://jwt.io
Calling Backend Services with Access-Token1app.acme.iologged inBrowserAuthorization: Bearer eyJhbG.Keycloaksso.acme.io3bAppPublic KeyAuthenticated User accesses App2App uses Access-Token in HTTPHeader to access backend3Backend looks-up Realm PublicKey in cache with in Kid from JWT3aIf not found, fetch Public Key withKid from Keycloak2AccessToken6453bKeycloak returns Realm Public KeyBackend4Backend verifies signature ofAccess-Token with Realm Public Key5Backend Service grants access andreturns user data6App can now display user dataapi.acme.ioBearer-onlyKid13a3
Keycloak Integration Options OpenID Connect Keycloak Adapters Spring Security, Spring Boot, ServletFilter, Tomcat, Jetty, Undertow, Wildfly, JBoss EAP, NodeJS, JavaScript, Angular, AngularJS, Aurelia, CLI & Desktop Apps SAML Keycloak 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 Many more generic integrations see OIDC and SAML
Keycloak DemoSecuring Apps
Demo EnvironmentWeb based Single Sign-OnWS-ChatFrontendPlain JS AppFrontendSpring BootOIDC ConfidentialSpring BootOIDC ConfidentialJavascriptOIDC Public ClientSpring BootSAMLAuthorization: Bearer ACCESS TOKENBackendSpring BootOAUTH Bearer-only
Keycloak DemoSecuring Appsthomasdarimont/keycloak-docker-demo
Keycloak in the FieldHow can a Keycloak environment look like?
Demo EnvironmentDesktop AppJavaFXPlainJS AppJavaScriptFrontendSpring BootBackendSpring BootSAML AppSpring BootHTTPSDataflowsso.tdlabs.localDistributed CacheJGroups / InfinispanReverse ProxyLoad Balancer / WAFSSL KeycloakJMSActive MQJDBCLog MonitoringAlertsDashboardsPostgresPostgresMessage BrokerProvisioningMessages
Keycloak with Graylog ActiveMQ
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 a modern Identity Management
Thanks!Thomas Darimont@thomasdarimont
Links Keycloak WebsiteKeycloak DocsKeycloak BlogKeycloak User Mailing ListKeycloak Developer Mailing ListOpenID ConnectKeycloak Community Extensions SAMLJSON Web TokensAwesome KeycloakKeycloak Dockerized ExamplesKeycloak Quickstart ProjectsKeycloak Extension Playground
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 Extension Points Extensions via Service Provider InterfacesCustom Authentication MechanismsCustom “Required Actions”Custom User Storage (JDBC, REST, etc.)Event Listener (Provisioning, JMS)Credential Hashing MechanismsCustom REST EndpointsCustom Themes many more
Keycloak Extension Example
Custom Dashboard ExtensionPlease vote :) https://issues.jboss.org/browse/KEYCLOAK-1840
Supported Authentication Protocols OpenID Connect 1.0 Protocol based on OAuth 2.0Uses OAuth 2.0 tokens IDToken to encode IdentityTokens 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 CURL1Request new Tokens via Password Credentials Grant (Direct Access Grants in Keycloak)KC RESPONSE (curl -X POST rotocol/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' \)2Extract AccessTokenKC ACCESS TOKEN (echo KC RESPONSE jq -r .access token)# JGY3RMVHJqeWRxYkpISGZ0d29U .3Use AccessToken in Authorization Headercurl \-H "Authorization: Bearer KC ACCESS TOKEN" dos
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 Endpointclient id, username, password, grant type passwordKeycloak returns Tokens (Access-, ID-, Refresh-Token)Client needs to parse & validate tokensClient sees password Password Anti-Pattern KeycloakInstalled Adapter Enables OAuth2 authorization code flow for Desktop / CLI appsCode to Token exchange via short lived ServerSocket@localhostUses Keycloak Login via BrowserCan reuse existing SSO session
Using the KeycloakInstalled Adapter1Add Maven Dependency dependency groupId org.keycloak /groupId artifactId keycloak-installed-adapter /artifactId version {keycloak.version} /version /dependency 2Export keycloak.json for Client{ "realm": "acme","auth-server-url": d": "external","resource": "app-frontend-javafx","public-client": true, "use-resource-role-mappings": true }3Create KeycloakInstalledKeycloakInstalled keycloak new KeycloakInstalled();4Trigger Browser loginkeycloak.loginDesktop();5Read current ()6Read & use AccessToken stringString token keycloak.getTokenString(10, ", "Bearer " token);7Trigger Browser Logoutkeycloak.logout()
Security Assertion Markup Language 2.0 (SAML) Browser based “Web SSO” Web, Mobile and Desktop Apps Support for Sing