Checking Usernames for conformance during registration

Can usernames be checked for conformance against a regex or similar during registration?
We don’t wan’t to allow usernames that contain special characters (e.g @), must not exceed a certain length, must be at least a minimum length, must not be special names (e.g. admin, sys), etc.
I noticed there are Password filters similar to this.
Can the server be easily extended to support this? If so, best approach?
thx in advance.

1 Like

Write an extension? Trigger it via an Authentication AuthType flow.

Probably the best place to customize the Registration flow and add a custom version of RegistrationUserProfile (keycloak/RegistrationUserCreation.java at master · keycloak/keycloak · GitHub) in the validate() method. That’s where other, similar validation is taking place for username and email.

Thanks for the guidance. I have added the functionality (which also includes peices to achieve pre-assigned Usernames during registration) and all is good. I’ll post a link to my github branch once I clean up the code so others can get an idea of what’s required.

PS. Along the way I noticed a couple of things, two of which seem odd and might be related. First, the session obtained from (FormContext)context.getSession() doesn’t hold values (via addAttribute() etc) beyond the current brower invocation (during registration process at least). So saving a value there will not be retrievable on the next form submission processing. i.e. the session doesn’t span browser interactions. But I thought it should (thats what Sessions are) - am I misunderstanding something here. It will take me a bit to write a standalone test case, but I have definiately confirmed this in my development environment (standalone setup). Second, all the URLs sent to the browser during registration (e.g. http://192.168.1.100:8080/auth/realms/Test/login-actions/registration?client_id=account&tab_id=DNVH0GHN2vE) contain a sessionID (DNVH0GHN2vE). This makes for ugly URLs and invalid ones too once the session has expired. For instance, a bookmarked URL that’s expired will report the session has expired everytime its used. Why not just set a cookie? Then the URLs would be valid whether the session has expired or not. Perhaps issues these are related? They both seem very peculiar.

@bpc Try using user session notes:

context.getAuthenticationSession().setUserSessionNote(name, value)

That will be retrievable in the next processing during the same authentication session.

@xgp Thx for tip. My workaround was to use a private static Map indexed by:

context.getAuthenticationSession().getTabId()

but I’ll switch to your suggestion.