Keycloak Custom message on user temporary lock - keycloak

I am using Kyecloak:4.8.0, and have enabled Brute force attack for my realm.
Now whenever user provides wrong credentials for 3 times user will be locked temporarily.
But still user will see "Invalid username/password".
According to this thread Keycloak have done this intentionally:
https://issues.jboss.org/browse/KEYCLOAK-5284
But still i want to show user that his account has been locked.
Is there any way to customize this message?
I tried doing this by adding message in custom keycloak theme as below:
location: themes\adminlte\login\messages\messages_en.properties
accountTemporarilyDisabledMessage=Account is temporarily disabled, contact admin or try again later.
This change is not working.

After going through Keycloak base code what i found is: Keycloak uses Messages.INVALID_USER (invalidUserMessage) from properties which is written in AbstractFormAuthenticator class.
This class is at the end extended by UsernamePasswordForm now to change this to custom message i Wrote Custom Authenticator (Keycloak SPI) like below
public class CustomUsernameFormAuthenticator extends UsernamePasswordForm {
#Override
protected String tempDisabledError() {
return Messages.ACCOUNT_TEMPORARILY_DISABLED;
}
}
After this deploy spi Jar in keycloak and enable it in your realm.
And we are done :)

Related

How to enable 2FA using email using keycloak-admin-client in spring boot

My requirement is enable 2FA using email in Keycloak.
When enabled, if user tries to login through email & password ,after user is successfully authenticated ,time based token will be sent to email .
User will do this action from custom UI i.e in our product we have UI to enable/disable 2FA for user.
We are using Keycloak & we want to achieve this using Keycloak API.
I am using keycloak-admin-client to interact with Keycloak API but I did not find sufficient resources to achieve this using keycloak-admin-client.
I am looking a way using keycloak-admin-client how to enable 2FA for user.
Any help will be highly appreciated.
Thank You
You should add custom REST endpoints to Keycloak to be able to enable 2FA from your custom UI. We have done this before. It's not that much complicated, but it requires you to have a look at Keycloak source to see what it's doing when OTP gets activated. Some important classes to check/use are TotpBean, OTPCredentialModel and OTPPolicy.
In order to enable the 2FA, we needed to show the QR code image in our custom UI. So we added an endpoint to Keycloak that instantiates an instance of TotpBean. It's the one that gives you access to the QR code image and the secret value that are required to generate the equivalent string representation of the image so that it could be scanned/entered in the 2FA app (e.g. Google Authenticator). Here is an example of how such an endpoint would look like:
#GET
#Produces({MediaType.APPLICATION_JSON})
#Path("/o2p-enable-config/{email}")
#NoCache
public Response fetchOtpEnableConfig(#Email #PathParam("email") String email) {
UserModel user = session.users().getUserByEmail(email, realm);
TotpBean totp = new TotpBean(session, realm, user, session.getContext().getUri().getRequestUriBuilder());
return Response
.ok(new YouOTPResponseClass("data:image/png;base64, " + totp.getTotpSecretQrCode(), totp.getTotpSecret(), totp.getTotpSecretEncoded()))
.build();
}
Then on your own backend, you call this endpoint and send the user's email to it and receive the image and the secret value. You can just display the image as is in your UI and keep the secret value on your backend (e.g. in user's session). When user scans the image using the app and enters the totp value provided by the app in your custom UI, you send the totp value and the secret to another endpoint that you should add to the Keycloak. This second endpoint is the one that does that verification of the value and enables 2FA.
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Path("/enable-2fa/{email}")
#NoCache
public Response enable2Fa(#Email #PathParam("email") String email, OtpDetails optDetails) {
OTPPolicy policy = realm.getOTPPolicy();
String totp = optDetails.getTotp();
UserModel user = session.users().getUserByEmail(email, realm);
OTPCredentialModel credential = OTPCredentialModel.createFromPolicy(realm, optDetails.getSecret(), optDetails.getUserLabel());
if (CredentialValidation.validOTP(totp, credential, policy.getLookAheadWindow())) {
CredentialHelper.createOTPCredential(session, realm, user, totp, credential);
return Response.noContent().status(204).build();
} else {
return Response.status(BAD_REQUEST).build();
}
}
Keycloak supports multiple 2FA for each user. That's why it also has a property named label that allows user to name them so that it would be displayed in the 2FA login scenario with given name. You can also allow user to enter the label value in your custom UI and pass it to the second endpoint (or just pass an empty value to Keycloak if you're not going to allow your users to setup multiple 2FA).
I know it seems complicated, but it's actually not that much. The Keycloak domain model is well designed and when you get familiar with it, you can easily find what you need to do and wrap it in custom APIs. But always ensure that exposing a functionality would not compromise the overall security model of the system.
Take a look at keycloak two factor email authenticator provider
https://github.com/mesutpiskin/keycloak-2fa-email-authenticator
I agree that is necessary to write a custom provider for this use case.
Take a look at https://www.n-k.de/2020/12/keycloak-2fa-sms-authentication.html and https://www.youtube.com/watch?v=GQi19817fFk for a look at how to implement that.
That is an example via SMS, but via e-mail would be very similar, changing just the way of sending the code to the user.

Determine if Keycloak User has TOTP enabled

I have a Single-Page Web-Application authenticating against Keycloak and letting Users enable TOTP in their Keycloak-Account-Page.
However I want the Client-Application to determine after login, if the authenticated User has 2-factor-authentication/TOTP enabled or not.
Is it possible to map this (boolean) information into the Tokens or userinfo Endpoint ... I haven't found any User Property, that contains this information.
The only Place I found it, was in Admin-REST-API /auth/admin/realms/{realm}/users/{uuid}, but the Client/End-user won't and shouldn't have access there:
{
...
totp: true,
}
I don't think this is possible without customization.
You may want to add a custom protocol mapper and check for totp like this:
keyclaokSession.userCredentialManager().isConfiguredFor(realm, user, OTPCredentialModel.TYPE)
Here is a video that explains the first steps.

Keycloak - Adding an Additional Step to Login

I have a situation where during login, after a user has entered their username/password, they would get transferred to an additional page where they would have to enter an additional field (or select something from a select box)
Today, I use a simple session id over a cookie. When a user enters their credentials I create a session, and after they had entered the field in the additional page, I update the session.
I was wondering what would be the best way to achieve something like that in Keycloak. I would also like to include that additional field in the token.
I guess the obvious way would be to keep my login frontend as it is now and use the direct credentials grant API that Keycloak provides, but I would rather avoid that.
Please advise.
Clarifications: Each user in the system can belong to multiple organizations. That additional field corresponds to the organization that the user logs in to. All applications that interact with the token have to be aware of that organization field
According to your requirements i would suggest following:
Continue with UserStorageProvider implementation. Refer to following docs. Your implementation should also provide list of available companies for every user. You can expose this list as an UserModel attribute.
Implement custom required action (components like that runs after successfully passed credential challenges) that will get list of available companies from UserModel object of authenticated user. Offer this list to user as separate login form, so after user submits his choice it will be persisted in user session note. As example check out implementation for UpdateUserLocaleAction and javadoc for RequiredActionProvider. Here is example of logic for storing selected company:
#Override
public void requiredActionChallenge(RequiredActionContext context) {
List<String> availableCompanies = context.getUser().getAttribute("companies");
... // form rendering
}
#Override
public void processAction(RequiredActionContext context) {
String company = context.getHttpRequest().getFormParameters().getFirst("selected_company");
context.getAuthenticationSession().setUserSessionNote("company", company);
}
Add UserSessionNote oidc mapper to required client (or to shared client scope), so it will extract 'company' note saved by required action implementation from step 2
???
Profit

How to override login of flask-security?

I want to do some customization when a user logs in. The problem is that the project is using flask-security which implicitly handles user login.
I want to check some records of users in the database when users log in.
How can I override "login" function in flask-security?
I saw a similar post, and tried it but it's not working.
Plus, it is not exactly what I want to do.
I maybe need to stop the default behavior in case of some users.
So, is anyone having this kind of issue? How can I do it?
You can override the login form when you are setting up Flask-Security:
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore, login_form=CustomLoginForm)
Then create your custom login form class that extends the default LoginForm. And override the validate function to do stuff before or after the login attempt.
from flask_security.forms import LoginForm
class CustomLoginForm(LoginForm):
def validate(self):
# Put code here if you want to do stuff before login attempt
response = super(CustomLoginForm, self).validate()
# Put code here if you want to do stuff after login attempt
return response
"reponse" will be True or False based on if the login was successful or not. If you want to check possible errors that occurred during the login attempt see "self.errors"
Greetings,
Kevin ;)
after registering the flask security extension, you can create an endpoint with the exact same name/route and it should override the one registered by Flask-security.
If you are using blueprints, make sure you register your blueprint before registering Flask-security.

Password protecting Apigility admin UI without htpasswd

I was being searching to password protect apiglity admin ui without using htpasswd, but i did not got any information about. Can anybody help me out with this?
Thanks in advance
You don't need password protection for ApiGility UI. Access should only be allowed in the Dev environment.
php public/index.php development enable <- to enable the UI
php public/index.php development disable <- to disable the UI
If you consist of having password protection for it. Then you can add an event to the Application Module.php that check if the identified user is allowed to access that resource.
Edit - If you do want to protect something by password
The following code should be placed in the Module.php file. (In many cases under the Application module).
It call the event manager and attach action to the Dispatch event.
Every time the application reach the dispatch phase it will fire this event.
The action is passed as a call back so you can attach function, classes ans etc. In this example I passed a new class that have access to the MvcEvent ($e).
For example, that class can check if a user is logged in. If it is not then redirect him to /login.
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach(MvcEvent::EVENT_DISPATCH, array(new UserAccessChecker($e), 'getResponse'));
}
For the purpose of auth You should further investigate ACL & RABC