Securing Applications and Services Guide Red Hat build of Keycloak 24.0 Red Hat Customer Content Services

Commands:
/realms/{realm-name}/.well-known/openid-configuration
/realms/{realm-name}/protocol/openid-connect/auth
/realms/{realm-name}/protocol/openid-connect/token
/realms/{realm-name}/protocol/openid-connect/userinfo
/realms/{realm-name}/protocol/openid-connect/logout
/realms/{realm-name}/protocol/openid-connect/certs
/realms/{realm-name}/protocol/openid-connect/token/introspect
/realms/{realm-name}/clients-registrations/openid-connect
/realms/{realm-name}/protocol/openid-connect/revoke
/realms/{realm-name}/protocol/openid-connect/auth/device
/realms/{realm-name}/protocol/openid-connect/ext/ciba/auth
curl -d "client_id=myclient" -d "client_secret=40cc097b-2a57-4c17-b36a-8fdf3fc2d578" -d "username=user" -d "password=password" -d "grant_type=password" "http://localhost:8080/realms/master/protocol/openid-connect/token"
npm install keycloak-js
import Keycloak from 'keycloak-js'; const keycloak = new Keycloak({ url: 'http://keycloak-serverUSD{kc_base_path}', realm: 'myrealm', clientId: 'myapp' }); try { const authenticated = await keycloak.init(); console.log(`User is USD{authenticated ? 'authenticated' : 'not authenticated'}`); } catch (error) { console.error('Failed to initialize adapter:', error); }
keycloak.init({ onLoad: 'check-sso', silentCheckSsoRedirectUri: `USD{location.origin}/silent-check-sso.html` });
<!doctype html> <html> <body> <script> parent.postMessage(location.href, location.origin); </script> </body> </html>
keycloak.init({ onLoad: 'login-required' });
async function fetchUsers() { const response = await fetch('/api/users', { headers: { accept: 'application/json', authorization: `Bearer USD{keycloak.token}` } }); return response.json(); }
try { await keycloak.updateToken(30); } catch (error) { console.error('Failed to refresh token:', error); } const users = await fetchUsers();
keycloak.init({ flow: 'implicit' })
keycloak.init({ flow: 'hybrid' });
keycloak.init({ adapter: 'cordova-native' });
<preference name="AndroidLaunchMode" value="singleTask" />
import Keycloak from 'keycloak-js'; import KeycloakCapacitorAdapter from 'keycloak-capacitor-adapter'; const keycloak = new Keycloak(); keycloak.init({ adapter: KeycloakCapacitorAdapter, });
import Keycloak, { KeycloakAdapter } from 'keycloak-js'; // Implement the 'KeycloakAdapter' interface so that all required methods are guaranteed to be present. const MyCustomAdapter: KeycloakAdapter = { login(options) { // Write your own implementation here. } // The other methods go here }; const keycloak = new Keycloak(); keycloak.init({ adapter: MyCustomAdapter, });
new Keycloak(); new Keycloak('http://localhost/keycloak.json'); new Keycloak({ url: 'http://localhost', realm: 'myrealm', clientId: 'myApp' });
try { const profile = await keycloak.loadUserProfile(); console.log('Retrieved user profile:', profile); } catch (error) { console.error('Failed to load user profile:', error); }
try { const refreshed = await keycloak.updateToken(5); console.log(refreshed ? 'Token was refreshed' : 'Token is still valid'); } catch (error) { console.error('Failed to refresh the token:', error); }
keycloak.onAuthSuccess = () => console.log('Authenticated!');
mkdir myapp && cd myapp
"dependencies": { "keycloak-connect": "file:keycloak-connect-24.0.10.tgz" }
const session = require('express-session'); const Keycloak = require('keycloak-connect'); const memoryStore = new session.MemoryStore(); const keycloak = new Keycloak({ store: memoryStore });
npm install express-session
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node server.js" },
npm run start
const kcConfig = { clientId: 'myclient', bearerOnly: true, serverUrl: 'http://localhost:8080', realm: 'myrealm', realmPublicKey: 'MIIBIjANB...' }; const keycloak = new Keycloak({ store: memoryStore }, kcConfig);
const keycloak = new Keycloak({ store: memoryStore, idpHint: myIdP }, kcConfig);
const session = require('express-session'); const memoryStore = new session.MemoryStore(); // Configure session app.use( session({ secret: 'mySecret', resave: false, saveUninitialized: true, store: memoryStore, }) ); const keycloak = new Keycloak({ store: memoryStore });
const keycloak = new Keycloak({ scope: 'offline_access' });
npm install express
const express = require('express'); const app = express();
app.use( keycloak.middleware() );
app.listen(3000, function () { console.log('App listening on port 3000'); });
const app = express(); app.set( 'trust proxy', true ); app.use( keycloak.middleware() );
app.get( '/complain', keycloak.protect(), complaintHandler );
app.get( '/special', keycloak.protect('special'), specialHandler );
app.get( '/extra-special', keycloak.protect('other-app:special'), extraSpecialHandler );
app.get( '/admin', keycloak.protect( 'realm:admin' ), adminHandler );
app.get('/apis/me', keycloak.enforcer('user:profile'), userProfileHandler);
app.get('/apis/me', keycloak.enforcer('user:profile', {response_mode: 'token'}), userProfileHandler);
app.get('/apis/me', keycloak.enforcer('user:profile', {response_mode: 'token'}), function (req, res) { const token = req.kauth.grant.access_token.content; const permissions = token.authorization ? token.authorization.permissions : undefined; // show user profile });
app.get('/apis/me', keycloak.enforcer('user:profile', {response_mode: 'permissions'}), function (req, res) { const permissions = req.permissions; // show user profile });
keycloak.enforcer('user:profile', {resource_server_id: 'my-apiserver'})
app.get('/protected/resource', keycloak.enforcer(['resource:view', 'resource:write'], { claims: function(request) { return { "http.uri": ["/protected/resource"], "user.agent": // get user agent from request } } }), function (req, res) { // access granted
function protectBySection(token, request) { return token.hasRole( request.params.section ); } app.get( '/:section/:page', keycloak.protect( protectBySection ), sectionHandler );
Keycloak.prototype.redirectToLogin = function(req) { const apiReqMatcher = /\/api\//i; return !apiReqMatcher.test(req.originalUrl || req.url); };
app.use( keycloak.middleware( { logout: '/logoff' } ));
https://example.com/logoff?redirect_url=https%3A%2F%2Fexample.com%3A3000%2Flogged%2Fout
app.use( keycloak.middleware( { admin: '/callbacks' } );
auth: token: realm: http://localhost:8080/realms/master/protocol/docker-v2/auth service: docker-test issuer: http://localhost:8080/realms/master
REGISTRY_AUTH_TOKEN_REALM: http://localhost:8080/realms/master/protocol/docker-v2/auth REGISTRY_AUTH_TOKEN_SERVICE: docker-test REGISTRY_AUTH_TOKEN_ISSUER: http://localhost:8080/realms/master
docker login localhost:5000 -u USDusername Password: ******* Login Succeeded
Authorization: bearer eyJhbGciOiJSUz
Authorization: basic BASE64(client-id + ':' + client-secret)
curl -X POST -d '{ "clientId": "myclient" }' -H "Content-Type:application/json" -H "Authorization: bearer eyJhbGciOiJSUz..." http://localhost:8080/realms/master/clients-registrations/default
String token = "eyJhbGciOiJSUz..."; ClientRepresentation client = new ClientRepresentation(); client.setClientId(CLIENT_ID); ClientRegistration reg = ClientRegistration.create() .url("http://localhost:8080", "myrealm") .build(); reg.auth(Auth.token(token)); client = reg.create(client); String registrationAccessToken = client.getRegistrationAccessToken();
export PATH=USDPATH:USDKEYCLOAK_HOME/bin kcreg.sh
c:\> set PATH=%PATH%;%KEYCLOAK_HOME%\bin c:\> kcreg
kcreg.sh config credentials --server http://localhost:8080 --realm demo --user user --client reg-cli kcreg.sh create -s clientId=my_client -s 'redirectUris=["http://localhost:8980/myapp/*"]' kcreg.sh get my_client
c:\> kcreg config credentials --server http://localhost:8080 --realm demo --user user --client reg-cli c:\> kcreg create -s clientId=my_client -s "redirectUris=[\"http://localhost:8980/myapp/*\"]" c:\> kcreg get my_client
kcreg.sh config truststore --trustpass USDPASSWORD ~/.keycloak/truststore.jks
c:\> kcreg config truststore --trustpass %PASSWORD% %HOMEPATH%\.keycloak\truststore.jks
kcreg.sh help
c:\> kcreg help
kcreg.sh config initial-token USDTOKEN kcreg.sh create -s clientId=myclient
kcreg.sh create -s clientId=myclient -t USDTOKEN
c:\> kcreg config initial-token %TOKEN% c:\> kcreg create -s clientId=myclient
c:\> kcreg create -s clientId=myclient -t %TOKEN%
kcreg.sh create -f client-template.json -s clientId=myclient -s baseUrl=/myclient -s 'redirectUris=["/myclient/*"]' -o
C:\> kcreg create -f client-template.json -s clientId=myclient -s baseUrl=/myclient -s "redirectUris=[\"/myclient/*\"]" -o
kcreg.sh get myclient
C:\> kcreg get myclient
kcreg.sh get myclient -e install > keycloak.json
C:\> kcreg get myclient -e install > keycloak.json
kcreg.sh get myclient > myclient.json vi myclient.json kcreg.sh update myclient -f myclient.json
C:\> kcreg get myclient > myclient.json C:\> notepad myclient.json C:\> kcreg update myclient -f myclient.json
kcreg.sh update myclient -s enabled=false -d redirectUris
C:\> kcreg update myclient -s enabled=false -d redirectUris
kcreg.sh update myclient --merge -d redirectUris -f mychanges.json
C:\> kcreg update myclient --merge -d redirectUris -f mychanges.json
kcreg.sh delete myclient
C:\> kcreg delete myclient