Keycloak : implement "reset password" (as admin) flow same as "forgot password" (as user) - keycloak

I would like to implement this authentication flow in Keycloak:
A user creates an account by typing only his email
The user is logged in and can access my service
2'. At the same time, an email is sent to him, allowing him to "finalize" his account
The user leaves his session -> to reuse my service, he must click in the received email
By clicking in the received email, the user defines his first password
The user is then logged in automatically (without going through a login page).
The objective of this flow is to be the simplest, to hook users who are not used to webapps.
The implementation I would do:
Create an account without password request: I customize the Keycloak Registration flow by disabling the Password Validation and Profile Validation rules
Programmatically, in my webapp, at the first connection of a user, via the REST Admin API, I trigger the email action UPDATE_PASSWORD
I get something that works, but:
A. The link received by email redirects to an intermediary page confirming the execution of actions ("Perform the following action (s)") - (similar to Keycloak Implement Reset password flow same as forgot password flow)
B. The user is then redirected to a login page, and not directly connected to the application.
When, as a normal user, I trigger a reset password request (through 'forget password' feature), the process is the one I want: by clicking on the email link, I go directly to the page allowing me to enter and confirm a new password, then I'm authenticated.
My question: Do you see a way to implement this 'simplified' flow?
My keycloak version : 11.0.2
Thank you !

I could remove the "info.ftl" page display, customizing the "ExecuteActionsActionTokenHandler", as explained here :
action-token-spi
You have to create a file :
src/main/resources/META-INF/services/org.keycloak.authentication.actiontoken.ActionTokenHandlerFactory
containing the name of the class you want to use instead :
com.example.ExecuteActionTokenHandlerFactory
Then you create that class com.example.ExecuteActionTokenHandlerFactory with the following code :
public class ExecuteActionTokenHandlerFactory extends ExecuteActionsActionTokenHandler {
#Override
public Response handleToken(ExecuteActionsActionToken token, ActionTokenContext<ExecuteActionsActionToken> tokenContext) {
AuthenticationSessionModel authSession = tokenContext.getAuthenticationSession();
String redirectUri = RedirectUtils.verifyRedirectUri(tokenContext.getUriInfo(), token.getRedirectUri(),
tokenContext.getRealm(), authSession.getClient());
if (redirectUri != null) {
authSession.setAuthNote(AuthenticationManager.SET_REDIRECT_URI_AFTER_REQUIRED_ACTIONS, "true");
authSession.setRedirectUri(redirectUri);
authSession.setClientNote(OIDCLoginProtocol.REDIRECT_URI_PARAM, redirectUri);
}
token.getRequiredActions().stream().forEach(authSession::addRequiredAction);
UserModel user = tokenContext.getAuthenticationSession().getAuthenticatedUser();
// verify user email as we know it is valid as this entry point would never have gotten here.
user.setEmailVerified(true);
String nextAction = AuthenticationManager.nextRequiredAction(tokenContext.getSession(), authSession, tokenContext.getClientConnection(), tokenContext.getRequest(), tokenContext.getUriInfo(), tokenContext.getEvent());
return AuthenticationManager.redirectToRequiredActions(tokenContext.getSession(), tokenContext.getRealm(), authSession, tokenContext.getUriInfo(), nextAction);
}
}
Actually it is the same implementation as the upper class, except we removed the following part :
if (tokenContext.isAuthenticationSessionFresh()) {
...
}
which means that if the user did not have a session, which happens when the user is reseting his password, he is redirected to that "info.ftl" page.

As a workaround for problem A, I customize info.ftl template page. I add an ugly inline script to click on the link, redirecting automatically to the update password page.
<#import "template.ftl" as layout>
(...)
<#elseif actionUri?has_content>
<p><a id="yolo" href="${actionUri}">${kcSanitize(msg("proceedWithAction"))?no_esc}</a></p>
<script>document.getElementById('yolo').click()</script>
(...)
It'll do the job until I found a cleaner solution.
At the moment, B problem remains.

Related

Laravel - Different $URL after verification Email

In my app, there are two types of users. A group of them, as admins, must register themselves, and the other can only be present after being invited by the admins. Both types of users get verification email. I want the page that these two types of users see, after click on button in verification email, is different. How can I do this?
Thanks for any help
If You are using laravel/ui for authentication you need to provide path where the user is to be taken based on type in your VerificationController which ensure where to redirect your user after it is verified.
you need to remove protected $redirectTo = RouteServiceProvider::HOME; and replace with below function
public function redirectTo()
{
if(auth()->user()->type == 'admin'){
return '/here';
}else{
retuurn 'there'
}
}
if you are using anything other than laravel/ui you can follow the same procedure and have to redirect manually to certain url

How to prevent waves Signer automatic logout if the user refreshes the page?

I am following the Vladimir Zhuravlev "Getting Started with Waves Signer" example, I find to use Signer in my app, everything is going awesome, my problem is when after made an authorization and if the user refreshes the page it automatic logout, I want to prevent logout when refresh, it just must to do when the user clicks on logout.
User Authorisation
Waves Signer can be used to get the public data of an active user account from Waves.Exchange client.
The code:
try {
const userData = await waves.login(); // calling Waves Signer
event.target.classList.add("clicked");
event.target.innerHTML = `
authorized as <br>
${userData.address}`; // getting account address
} catch (e) {
console.error('login rejected') // handling user auth reject
}
});
Thank you for the question. Waves Signer is designed to operate with the user private data in a safe way. The login data is stored as a variable, this is why it's not available after reloading page. Unfortunately, there is no way to prevent logout when leaving the page.

Keycloak - direct user link registration

I have set up a web application with Keycloak in my local machine. Since Im using Keycloak as SSO implementation, I want in my web app that whenever SIGNUP button is click, user is directed into the registration page, and not going through the LOGIN page.
This is the example URL directed to the registration form, however, it contains a tab_id that is generated randomly like a session id.
https://site.test/auth/realms/custom/login-actions/authenticate?client_id=test&tab_id=qIdW92Bvwmk
I read about this link
Yes, as long as you use the "registrations" instead of "auth" in the
end of login ( AuthorizationEndpoint ) URL
But my endpoint in https://site.test/auth/realms/custom/.well-known/openid-configuration cannot be modified.
You can change the button link to this format -
http://<domain.com>/auth/realms/<realm-name>/protocol/openid-connect/registrations?client_id=<client_id>&response_type=code&scope=openid email&redirect_uri=http://<domain.com>/<redirect-path>&kc_locale=<two-digit-lang-code>
The registration page is exposed via an openid-connect endpoint, accessible in the same way as the standard auth screen. To construct the correct URL you can simply replace openid-connect/auth in the URL with openid-connect/registrations from the .well-known auth endpoint.
authEndpoint.replace("openid-connect/auth","openid-connect/registrations");
Using this endpoint the user will be directed to the registration screen instead of the login screen.
It is not documented or exposed via .well-known/openid-configuration, but you can see it in the source code:
public static UriBuilder registrationsUrl(UriBuilder baseUriBuilder) {
UriBuilder uriBuilder = tokenServiceBaseUrl(baseUriBuilder);
return uriBuilder.path(OIDCLoginProtocolService.class, "registrations");
}
For Keycloak 17 this worked for me:
http://<mykeycloakdomain.com>/realms//protocol/openid-connect/registrations?client_id=<myclient_id>&response_type=code&scope=openid+email&redirect_uri=https%3A%2F%2Fmywebsiteurl.com&kc_locale=

Checking if a user already signed up

I built a custom authentication system using FirebaseAuthentication tokens.
My signup / login flow should work like this:
User presses login button
My server generates the authentication token and sends it to the client
Check if the user already exists (in the 'Auth' table or in my database?)
If true: sign in using FIRAuth.auth()?.signIn(withCustomToken:...
If false: Show a form to to enter custom information (name, etc..)
sign using FIRAuth.auth()?.signIn(withCustomToken:...
save the custom information to my database
My question is: How can I find out if the user has already signed up?
Would a publicly accessible database with only uid's be the way to go?
This is fairly opinion based, but yes, I would use a standalone DB that stores each user's username who has signed up. Then all that is required is a quick web request through a PHP file querying for any rows returned with that username.
The firebase sign in method will feedback in asynchronous callback.
FIRAuth.auth()?.signInWithEmail(email, password: password, completion: { (user , error) in
if let error = error {
print(error.localizedDescription)
return
}
self.signedIn(user)
})
If you haven't sign up yet. The error will print out
There is no user record corresponding to this identifier. The user may have been deleted.

How get the notification ID when user enter in you app

I'm using the Facebook requestdialog to show my friend list and invite,this in a Facebook Web APP, using this:
function sendRequestViaMultiFriendSelector() {
FB.ui(
{
method: 'apprequests',
message: 'Selección de amigos a los que invitar a KugaBar'
}, requestCallback);
}
function requestCallback(data) {
console.log(data);
}
It works (ok).
But I need to identify the user when enter in my APP, you see the requestCallback data and see a "request", but when the users click on the notification and enter in the APP
I don't know how identify the request to detect if the user is accessing by the notification.
EDIT: OK I found it.
The param in the GET vars are "request_ids", but one problem appear, this param only come if the user previously have accepted the permissions, if the user clicks on the notification, and accept the permissions, hitting enter: this param doesn't exist, if the user enter again (not need to accept nothing) this param exists in the URL.
Are there any method to get this param in the first time the user enter?
Thanks
When the user first clicks on a request, you should get the request_id from the URL and store it in a cookie. When the user has completed logging in, check if the cookie exists and then update your record accordingly.
Notifications and Requests are NOT the same thing on Facebook. In your case you're talking about Requests. Request ids are passed to the app as a GET parameter 'request_ids' which is a comma separated list.
To be able to access this parameter after login dialog, you want to save your GET parameters from the original launch URL before redirecting to the OAuth dialog and pass them around in the redirect URL. This way you solved this problem for all of your future GET parameters.
If you're using PHP, the function you're looking for is http_build_query. I'd highly discourage from using a cookie to store one-time and easily accessible URL parameters.