PKCE Authentication Setup

PKCE Authentication Setup

The PKCE (Proof Key for Code Exchange) recipe allows you to quickly configure a secure authentication client for Single Page Applications (SPAs), mobile apps, and desktop applications.

What is PKCE?

PKCE is a security extension for OAuth 2.0 that prevents authorization code interception attacks. It’s essential for public clients (SPAs, mobile apps) that cannot securely store client secrets.

Why Use PKCE?

  • Enhanced Security: Prevents authorization code interception attacks
  • No Client Secrets: Safe for applications that run in untrusted environments
  • Industry Standard: Recommended by OAuth 2.0 best practices
  • Keycloak Native: Fully supported by Keycloak

Quick Start (3 Steps)

Step 1: Application Information

  1. Navigate to Applications in your Skycloak dashboard
  2. Click Add Application and select “Single Page Application” or “Mobile App”
  3. Enter your application details:
    • Client Name: A descriptive name (e.g., “My SPA Application”)
    • Application Type: Choose from:
      • Single Page Application (React, Vue, Angular, etc.)
      • Mobile/Native App (iOS, Android, React Native)
      • Desktop Application (Electron, etc.)

Step 2: Security & Redirect Configuration

Configure where users should be redirected after authentication:

  1. Redirect URIs (Required):

    • Add one or more valid redirect URIs
    • Example: https://myapp.example.com/callback
    • For development: http://localhost:3000/callback
    • Click Add another URI for multiple redirects
  2. PKCE Challenge Method:

    • S256 (Recommended): Uses SHA-256 hashing for maximum security
    • Plain: Less secure, only use for legacy support
  3. Additional Options:

    • ☑️ Require user consent: Users must approve data access
    • ☑️ Enable refresh tokens: Allow token refresh without re-authentication
    • Allow offline access: Enable when users need extended access

Step 3: Review & Apply

Review your configuration summary and click Create Application to create your PKCE-enabled client.

What Gets Configured

When you create the PKCE-enabled application, Skycloak automatically:

  1. ✅ Creates a public client (no client secret)
  2. ✅ Enables PKCE with your chosen method
  3. ✅ Enables Standard Flow (Authorization Code Flow)
  4. Disables Direct Access Grants (for security)
  5. ✅ Configures your redirect URIs
  6. ✅ Sets up user consent if enabled
  7. ✅ Enables refresh tokens if requested

After Creation

Once the application is created, you’ll receive:

  • Client ID: Use this in your application
  • Redirect URIs: Verify these match your application
  • PKCE Method: Confirm S256 or Plain

Next Steps

  1. Copy Your Client ID: You’ll need this for your application code
  2. Configure Your App: Use the redirect URI you specified
  3. Implement PKCE Flow: See implementation guides below
  4. Test Authentication: Verify the flow works correctly

Implementation Examples

JavaScript/TypeScript (React, Vue, Angular)

// Using @auth0/auth0-spa-js or similar library
import { createAuth0Client } from '@auth0/auth0-spa-js';

const auth0 = await createAuth0Client({
  domain: 'your-keycloak-domain.skycloak.io',
  clientId: 'your-client-id', // From recipe
  authorizationParams: {
    redirect_uri: 'https://yourapp.com/callback',
  },
  // PKCE is automatically handled by the library
});

// Login
await auth0.loginWithRedirect();

// Handle callback
await auth0.handleRedirectCallback();

React Native

import { authorize } from 'react-native-app-auth';

const config = {
  clientId: 'your-client-id', // From recipe
  redirectUrl: 'myapp://callback',
  serviceConfiguration: {
    authorizationEndpoint: 'https://your-keycloak-domain.skycloak.io/realms/your-realm/protocol/openid-connect/auth',
    tokenEndpoint: 'https://your-keycloak-domain.skycloak.io/realms/your-realm/protocol/openid-connect/token',
  },
  usePKCE: true,
};

const result = await authorize(config);

Configuration Monitoring

Skycloak automatically monitors your PKCE configuration for changes:

Status Indicators

  • ✅ Active: Configuration is correct and active
  • ⚠️ Needs Attention: Configuration may have changed

Common Configuration Issues

Configuration changes can occur when:

  • PKCE is manually disabled in Keycloak
  • PKCE method is changed from S256 to Plain
  • Client is changed from Public to Confidential
  • Standard Flow is disabled

Fixing Configuration Issues

If you notice configuration changes:

  1. Review the client settings in Keycloak admin console
  2. Re-enable PKCE with S256 method if disabled
  3. Ensure Standard Flow is enabled

Best Practices

Security

  • Always use S256: Never use Plain unless absolutely necessary
  • Use HTTPS: All production redirect URIs must use HTTPS
  • Specific URIs: Avoid wildcards in redirect URIs
  • Enable consent: Let users control data access
  • Rotate secrets: If you ever expose credentials, recreate the client

Development

  • 📝 Test locally: Use http://localhost URIs for development
  • 📝 Multiple environments: Create separate clients for dev/staging/prod
  • 📝 Document endpoints: Keep track of your redirect URIs
  • 📝 Monitor logs: Check Skycloak logs for authentication issues

Production

  • 🚀 Use CDN: Serve your SPA from a CDN with HTTPS
  • 🚀 Token storage: Use secure, httpOnly cookies when possible
  • 🚀 Session management: Implement proper logout and session timeout
  • 🚀 Error handling: Gracefully handle authentication failures

Troubleshooting

“Invalid redirect URI” error

Problem: Users see an error after login

Solution:

  1. Verify the redirect URI in your code matches exactly what’s configured
  2. Check for typos (trailing slashes matter!)
  3. Ensure HTTPS in production

“PKCE verification failed” error

Problem: Token exchange fails

Solution:

  1. Verify your library supports PKCE
  2. Check that code_verifier is generated correctly
  3. Ensure code_challenge_method matches (S256 vs Plain)

Client not found

Problem: Authentication fails to start

Solution:

  1. Verify you’re using the correct Client ID
  2. Check that you’re connecting to the right realm
  3. Confirm the client wasn’t deleted

FAQ

Can I change the configuration later?

Yes! You can manually edit the client settings in Keycloak admin console at any time.

What if I need a confidential client?

The PKCE setup creates public clients only. For confidential clients (server-side apps with client secrets), select “Backend/Server Application” when creating your application.

Can I use this for mobile apps?

Absolutely! PKCE was designed for mobile apps. Just:

  1. Choose “Mobile/Native App” in Step 1
  2. Use a custom URI scheme (e.g., myapp://callback)
  3. Configure your mobile app to handle the redirect

How do I fix configuration issues?

You can manually update the client settings in Keycloak admin console to restore the correct PKCE settings.

Can I have multiple redirect URIs?

Yes! Add as many redirect URIs as you need for different environments:

  • http://localhost:3000/callback (development)
  • https://staging.myapp.com/callback (staging)
  • https://myapp.com/callback (production)

Related Resources

Need Help?

If you encounter issues:

  1. Check the troubleshooting guide
  2. Review Skycloak logs in the dashboard
  3. Contact support with your Client ID (never share client secrets!)

Pro Tip: After applying the PKCE recipe, bookmark your client configuration page in Keycloak for quick access to settings and credentials.