You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过Keycloak Rest API实现用户自助注册?

Hey there! I’ve messed around with Keycloak’s APIs plenty of times, so I totally get why you’re frustrated with all the examples leaning on the built-in login page—when you need a custom self-registration flow for your mobile app, that’s not helpful at all. Let’s walk through two solid ways to pull this off using Keycloak’s REST APIs, step by step.

1. Option 1: Directly Call Keycloak’s Public Registration Endpoint (Frontend/Client-Side)

This is the simplest approach if you don’t need extra backend logic—your mobile app can send the user’s registration data straight to Keycloak without going through your own server.

Step 1: Configure Your Keycloak Realm for Registration

  • Log into your Keycloak admin console, navigate to your target realm
  • Go to Realm SettingsLogin tab
  • Check the User registration box to enable self-registration
  • Adjust other settings to fit your app:
    • Toggle Verify email if you want users to confirm their email before logging in
    • Enable Email as username if you don’t want separate usernames and emails
    • Set password policies (under Realm SettingsPassword Policy) to enforce complexity requirements

Step 2: Build the Registration Request

Send a POST request to Keycloak’s registration endpoint:
POST /realms/{your-realm-name}/protocol/openid-connect/registrations

Request Headers

Content-Type: application/json

Request Body (Example)

Customize this based on your realm’s settings:

{
  "username": "mobile-user-001",
  "email": "user@yourapp.com",
  "firstName": "Alice",
  "lastName": "Smith",
  "password": "StrongPass123!",
  "emailVerified": false,
  "enabled": true
}

Note: If you enabled Email as username, you can omit the username field—Keycloak will auto-use the email address instead. If email verification is on, leave emailVerified as false so Keycloak sends a verification link.

Step 3: Handle the Response

  • Success: You’ll get a 201 Created status, with a response body containing basic user details like their Keycloak ID and username.
  • Errors: Keycloak returns 4xx status codes with clear error messages (e.g., Username already exists or Password does not match policy). Use these to show meaningful feedback to your users.
2. Option 2: Proxy Through Your Backend with the Keycloak Admin API

Use this if you need to run custom business logic during registration (like checking if the user is eligible, linking to your app’s internal database, etc.). This requires your backend to authenticate with Keycloak first using a service account.

Step 1: Create a Service Account Client in Keycloak

  • In your Keycloak admin console, go to ClientsCreate
  • Set a Client ID (e.g., app-registration-service), choose openid-connect as the protocol, and set Access Type to confidential
  • Save, then go to the Settings tab and enable Service Accounts Enabled
  • Head to the Service Account Roles tab, add the create-users and view-users roles (stick to the minimum permissions you need to avoid security risks)

Step 2: Get a Service Account Access Token

Your backend needs this token to call the Admin API. Send a POST request to Keycloak’s token endpoint:
POST /realms/{your-realm-name}/protocol/openid-connect/token

Request Headers

Content-Type: application/x-www-form-urlencoded

Request Body

grant_type=client_credentials
client_id=app-registration-service
client_secret={your-client-secret}

Grab the client_secret from the Credentials tab of your service account client.

You’ll get a response with an access_token—this is what you’ll use to authenticate Admin API calls.

Step 3: Call the Admin API to Create a User

Send a POST request to the Admin API’s users endpoint:
POST /admin/realms/{your-realm-name}/users

Request Headers

Content-Type: application/json
Authorization: Bearer {your-service-access-token}

Request Body (Example)

Note the different structure for passwords compared to the public registration endpoint:

{
  "username": "mobile-user-002",
  "email": "another-user@yourapp.com",
  "firstName": "Bob",
  "lastName": "Jones",
  "credentials": [
    {
      "type": "password",
      "value": "AnotherStrongPass456!",
      "temporary": false
    }
  ],
  "emailVerified": false,
  "enabled": true
}

Set temporary: true if you want users to reset their password on first login.

Step 4: Handle the Response

  • Success: A 201 Created status, with a Location header pointing to the new user’s API endpoint (contains their Keycloak ID).
  • Errors: Again, 4xx status codes with descriptive messages—use these to debug issues like duplicate usernames or insufficient permissions.
Critical Things to Keep in Mind
  • CORS for Frontend Calls: If you use Option 1, add your app’s domain to the Web Origins field in your Keycloak client settings (under Settings) to avoid cross-domain errors. Use * for development, but lock it down for production.
  • Password Policy Enforcement: Make sure your app’s frontend validates passwords against Keycloak’s policy before sending the request—this saves users from getting frustrating error messages after submitting.
  • Email Verification: If you enable this, configure Keycloak’s email server (under Realm SettingsEmail) so it can send verification links. Users won’t be able to log in until they confirm their email.
  • Security for Service Accounts: Never hardcode the client secret in your mobile app—keep it securely stored on your backend only.

内容的提问来源于stack exchange,提问作者SirajH

火山引擎 最新活动