How to disable/enable Sign Ups for a specific application with Auth0? - auth0

Is there a way to disable or enable sign ups for a specific application which is independent of the “Disable Sign Ups”-toggle in the dashboard for login with passwordless email (Authentication/Passwordless/Email)?

Only partly.
It's possible via Pre-User-Registration Hook and/or or Rule with some caveats.
Pre-User-Registration Hooks :
https://auth0.com/docs/customize/hooks/extensibility-points/pre-user-registration
Something like this:
module.exports = function (user, context, cb) {
return cb(new PreUserRegistrationError('Denied user registration in Pre-User Registration Hook', 'You are not allowed to register.'));
}
};
Here you can just fail the registration at all times.
Problem with Hooks is that that the Pre-User-Registration Hook does not trigger for social connections / federation, only Database Connections and Passwordless.
Alternatively via Rule:
https://auth0.com/docs/customize/rules
This will always work, but the downside is that the user gets created in Auth0, they will just not be able to further proceed.
In the Rule you basically check the number of logins, if it's 0, you know that it's a new user, and block the login that follows right after user creation (signup) as well as any other time.
Example rule:
https://auth0.com/rules/disable-social-signup
Related earlier answer of mine regarding this, in the Auth0 forum:
https://community.auth0.com/t/disable-signup-from-auth0-ui-and-enable-social-login/29227/2

I just figured out I can create another 'Tenant' (from the dashboard) with a different setting for Sign Up from the dashboard :-)

You could implement a custom Universal Login SPA for sign-up/in that only allows users to sign-in. Pre-registration hook to safeguard against people bypassing the UX.

Related

Adding Cognito users from our application Users page

I have my own Users page in my application where user Admin can create a new user.
I do not want to let the user sign up by himself, but have the admin of the system add this user.
What do you think the flow for that should be ?
I thought about:
create a new user with username and temp password in the users page.
The user gets an email and presses a link to confirm the email.
The user goes to the login screen of my application and inserts the username and temp password.
the login page changes to Change password so the user will insert the password and confirm the password for him.
when pressing login the user logins to the system.
I cannot find a best practice for adding a new user from a built-in users page in the app.
Do you think my flow is reasonable?
Do you have any code that I can use for that?
This is pretty close to the flow which Cognito has for admin-created users by default when using the Amplify UI Authenticator component. The only difference is that the temporary password is sent to the user via email, so the admin never needs to see it.
To achieve this, you need to use the AdminCreateUser action. The way you do this will vary depending on the library you're using to communicate with Cognito. If it's Python, you can use boto3. If it's JS, you can use the AWS JS SDK. (Sample code in this GitHub comment.)
It's not required to use Amplify UI, you could write all the pages yourself. But it works well with very little effort and looks quite professional. So it should be the first thing you try. Here's another answer providing sample code for React.

How to disable AWS Cognito User Pool account created via Identity Provider?

Any Cognito User Pool gurus out there? I've been using Cognito for a while now but this one has me a bit stumped.
We allow users to sign up and sign in using social accounts like Facebook which are set up as Identity Providers in the User Pool.
Users need to complete a custom registration form before they can use the main app - we don't use the hosted UI for login or signup
One step of the custom registration process allows the user to indicate which social provider then want to use
This allows us to pull back the users email, first and last names from the social provider which is great - we use a cognito client and callback to do this currently
But in doing so, this provisions a user within the Userpool before the registration process is complete - in fact this makes sense- in order for Cognito to provide us the user info it needs to have called into the social providers /userinfo endpoint to populate the user data
So, the issue we now have is that whilst the user is half way through the registration process I have a confirmed user account - eg. before the user has completed the registration process
This is an issue because a user could sign into the the app using their social login without ever have completed the registration process
So as I see it I have two options:
PostConfirmation Lambda trigger which uses the cognito-idp SDK to disable the user just after it was confirmed
Don't use Cognito to obtain the user info like firstname, lastname, email, picture etc - however this would require us to write a solution for every current and future social provider which isn't something I'm keen on
Am I missing something obvious?
Thanks in advance!
I would say PostConfirmation Lambda trigger is a good approach - however instead use adminDisableProviderForUser to disable the user from signing in with the specified external (SAML or social) identity provider
adminDisableProviderForUser
You can later call adminLinkProviderForUser to link the existing user account in the user pool to the external identity provider.
adminLinkProviderForUser
An alternative solution is to prevent the user from signing in if they have not fully completed the registration process via a Pre Authentication Lambda Trigger checking for a unique identifier with respect to your completed registration process
The simplest solution in the end for us was a Pre Token Generation Trigger in Cognito like this:
exports.handler = async (event) => {
if(event.triggerSource==="TokenGeneration_HostedAuth") {
//check db/api etc to see if we have a valid registration stored for user
if(!hasCompletedRegistration) {
//throw auth exception which we can catch on the frontend to inform user
throw new Error("REGISTRATION_NOT_COMPLETE")
}
}
return event
};
For username/password sign ins the TriggerSource will be TokenGeneration_Authentication
For federated/social sign ins the TriggerSource will be TokenGeneration_HostedAuth

Keycloak - Multi/2FA Factor - OTP - QR Code - Custom Login Screen - Rest API

I have my own Login page where user enters username/password.
This username/password are used to login through Keycloak Rest API.
http://localhost:8080/auth/realms/Demo/protocol/openid-connect/token
input - {username,password,grant_type,client_secret,client_id}
And in response i get access token.
Now i wish to enable Authenticator (Google Authenticator). I have enabled it from backend. Now if user wishes to login thorugh my application, my login page i need to get below details.
1.) Somehow i need to include QR Code that appears on keycloak login page post username/password validation to show on my login screen for the first time login once user enter username/password. So do we have any API which return Keycloak QR code image in response.
2.) Subsequent login i will have OTP field, so need a REST api to pass OTP along with username/password.
Please help with REST API if keycloak has any. Integrating through Javascript.
Similar flow as described in use case 1 here
Just want to use keycloak as a database, doing all operation for me, input will be my screen. I do want redirection of URL's while login in and yet should be standalone deployed.
I've managed to implement this through the rest API of Keycloak. To realize this, you need to extend Keycloak yourself with a SPI. To do this create your own Java project and extend org.keycloak.services.resource.RealmResourceProvider and org.keycloak.services.resource.RealmResourceProviderFactory. You can find more information in the official docs (https://www.keycloak.org/docs/latest/server_development/#_extensions), github examples and other stack overflow posts how to do this.
Once you got this up and running you can implement it like this:
#GET
#Path("your-end-point-to-fetch-the-qr")
#Produces({MediaType.APPLICATION_JSON})
public YourDtoWithSecretAndQr get2FASetup(#PathParam("username") final String username) {
final RealmModel realm = this.session.getContext().getRealm();
final UserModel user = this.session.users().getUserByUsername(username, realm);
final String totpSecret = HmacOTP.generateSecret(20);
final String totpSecretQrCode = TotpUtils.qrCode(totpSecret, realm, user);
return new YourDtoWithSecretAndQr(totpSecret, totpSecretQrCode);
}
#POST
#Path("your-end-point-to-setup-2fa")
#Consumes("application/json")
public void setup2FA(#PathParam("username") final String username, final YourDtoWithData dto) {
final RealmModel realm = this.session.getContext().getRealm();
final UserModel user = this.session.users().getUserByUsername(username, realm);
final OTPCredentialModel otpCredentialModel = OTPCredentialModel.createFromPolicy(realm, dto.getSecret(), dto.getDeviceName());
CredentialHelper.createOTPCredential(this.session, realm, user, dto.getInitialCode(), otpCredentialModel);
}
The secret received with the GET must be send back with the POST. The initial code is the one from your 2FA app (e.g. Google Authenticator). The QR code is a string which can be displayed in an img with src 'data:image/png;base64,' + qrCodeString;
I know this is an old question, but I've recently been looking at something similar, and so thought it would be potentially valuable to share what I have found for others who may be looking into this and wondered what the possibilities are.
TL;DR
You can only really use the existing Keycloak actions to do this or embed the user account management page found at https://{keycloak server URL}/auth/realms/{realm name}/account in an iframe. That's it, I'm afraid. In my opinion it is currently best to just assign actions directly to accounts or use the Credential Reset emails to assign actions; both of these can be done via the Admin API if desired:
Send Credential Reset email containing assigned actions:
https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_executeactionsemail
Set actions directly on the account (include the actions in the requiredActions portion of the user JSON that you send in the body to the endpoint):
https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_updateuser
Background is that as part of a project that I have been working on we wanted to see if we could have an integrated way for users to set up their initial password and OTP device when a new account has been created for them, since the default method of sending them an email from Keycloak using the "Credential Reset" functionality has the limitations that a) it doesn't provide a link to the application itself unless you override the theme, and if you have multiple instances of the application for different users you have no way of knowing which instance to provide the link for, so may have to end up including a list of them, and b) it often doesn't feel truly native to the application, even with changes to the theme. If you're sensible though, I'd suggest you stop and just use this functionality - please see the TL;DR section above for details.
So, in short there is NO API endpoint for receiving a QR code to set up an OTP device. There are two places, however, where the QR code can be retrieved from - the OTP device setup screen when you log in as a user who has had a "Configure OTP" action assigned to their account, and the user's own account management screen.
The first option of the Configure OTP action screen is a non-starter. It only shows up when you log in, and so by definition the user has to log in to Keycloak via the Keycloak login page in order to trigger the page to be displayed. At this point you're already on a Keycloak page instead of one of your app's pages, and so unless you can get very creative with changes to these Keycloak pages via a custom theme, tapping into this page isn't really an option.
The second option is more interesting, but far from ideal. Every user who has logged in has access to an account management page that can be found at https://{keycloak server URL}/auth/realms/{realm name}/account. This page allows you to do things like change your name, password, etc. and it also allows you to add an OTP device if you don't already have one, or delete any existing OTP devices associated with your account. This OTP device tab of the account management page can be reached directly via https://{keycloak server URL}/auth/realms/{realm name}/account/totp.
As I mentioned, there isn't an API that you can access to view the QR code that shows up on this page. The only way it is accessible is via the GET request to https://{keycloak server URL}/auth/realms/{realm name}/account/totp, which returns the HTML for the page I've already mentioned. Okay great, so can we scrape the QR code programmatically and then put it in our own page on our application? Err, no, not really. You see, whilst a lot of the Keycloak API endpoints rightly allow you to send a bearer token (e.g. access token) in the authorization header to access and endpoint, this page will not accept a bearer token as a means of authentication/authorization. Instead it uses a session cookie that is locked down to the Keycloak URL. This cookie is set when you log in to your application via the Keycloak login page, and so is available to this account management page when you navigate to it, having already logged in, and since the account management page uses the same server and domain name as the original Keycloak login page, it has access to the cookie and can let you in. This cookie cannot be sent by your application to e.g. your own REST API to then programmatically call the account management page and scrape the QR code, because your application doesn't have access to it for good security reasons. This might be something you can change in Keycloak somewhere, but if there is I would strongly recommend against changing it.
So if we can't scrape the page from our own server, can we do something on the front-end? Well, as mentioned, your application doesn't have access to the session cookie but if you make a request (e.g. using fetch or axios) in your front-end JavaScript to the account management page then that request will send the cookie along with it, so that could work right? Umm, well actually you will get hit with an error message in this scenario due to CORS. CORS is Cross-Origin-Resource-Sharing and in order to allow the Keycloak page to be accessed then you would have to open up the settings on the server to allow it to be accessed from your website's address. I've seen some articles that look at how you can open up your CORS settings on Keycloak if you wish but I'd be very nervous about doing this. I don't know enough about the internals of Keycloak and how it operates to comment on how much of a security risk this is, but I certainly wouldn't recommend it. There some information here (Keycloak angular No 'Access-Control-Allow-Origin' header is present) on changing the "Web Origins" setting of your application's Keycloak client, but this opens up your application to some serious potential abuse. There is also the MAJOR issue that even if you scraped the QR code, the device isn't actually added to the user's account (even though it appears in the authenticator app) until you enter a code into the page that the QR code is on and click Save. Since there isn't an API endpoint that you can use to complete this operation, I therefore don't think that this option is viable either. I've tried out whether or not you can use the token retrieval endpoint at https://{keycloak server URL}/auth/realms/{realm name}/protocol/openid-connect/token to see if making a request with your username/password/otp code will somehow "register" your device and complete the process, but although you can get a token this way, and it doesn't complain about the otp code, it doesn't actually take any notice of the code because as far as it's concerned the user's account doesn't have a device registered with it. So we have to use the form on the account management page in order to complete this registration process.
So the final way of possibly doing this is.... an iframe. Sorry, yeah it's rubbish but that's all your left with. You can have the iframe point at your account management page, and because the user is logged in then they will be able to see the contents from your application's page. You can use relative positioning, fixed width and height and remove scroll bars to ensure that you ONLY show the QR code and the fields for the one time code, device name, and the Save/Cancel buttons. This, sadly, seems to be the only option at the moment, and due to how nasty and unreliable iframes can be in general - they certainly don't feel native to your application, and you'll need to override your Keycloak theme to get the page in question to look more like your app - I'd recommend steering clear of this and using the standard approach of using Keycloak actions and the Admin API instead.
If you've made it this far, congratulations, you win at Stack Overflow :-)

Immediate login after successful registration on a plone site

I have a custom registration BrowserView where you have to extend some userdata (z3c.form with some fields including password). after successful saving these data i want the user to be logged in automaticaly and redirected to an other page in the site.
Thanks in advance for hints
So here's my working solution (thanks to mikko who pointed in the right direction):
authenticate your registration credentials in PAS
member = portal.acl_users.authenticate(username, password, portal.REQUEST)
for redirects it's neccessary to set the authentication cookie. You can do this with "updateCredentials" (see pas/plugins/cookie_handler)
if member:
portal.acl_users.updateCredentials(portal.REQUEST, portal.REQUEST.RESPONSE, username, password)
redirect to the next page
portal.REQUEST.RESPONSE.redirect(url)
If you want to extend the userdata for new members, and add new fields to the registration form, it's probably best to extend the utility that provides the default userdata schema and to do it in such a way that you seamlessly hook into the existing registration machinery.
There is an example product collective.examples.userdata which you can use0 and extend for this purpose. It also has good documentation that explains to you all the necessary steps.
http://plone.org/products/collective.examples.userdata

GITkit "Account Chooser" Questions

Has anyone successfully implemented the Google Identity Toolkit, an implementation of an Account Chooser. I followed the initial steps here, but I still have a few questions, as I don't quite know how to handle the entire data flow. I'm using Clojure / Compojure in the back-end:
http://havethunk.wordpress.com/2011/08/10/google-identity-toolkit-asp-net-mvc3/
http://code.google.com/apis/identitytoolkit/v1/acguide.html
A) don't quite understand how ID Provider authentication, fits into my data model
when implementing the callbackURL, what data should I expect, and
how's that session state managed by GITkit (and all Account Choosers)
B) Is there a way to set this up the 'callbackURL' for development.
the identity provider would need a URL that it can redirect back to
C) How can the GITkit / Account Chooser workflow let my users register an account that's native to my app?
Thanks in advance
The questions aren't entirely clear, but I've done an implementation of GITkit in ruby and can give you some pointers.
A) The callback URL is what handles the assertion from the identity providers. Rightnow GITKit only does OpenID, so the URL will contain an OpenID response either in the query parameters or as the POST body. You'll need to do a few things:
1) Call verifyAssertion in the gitkit API and pass the params/post body. This will return a JSON response that contains the user details (assuming assertion is valid). There are some other checks you should do as well
2) Decide what to do with the assertion. If it is an existing user, most likely you'll just establish a session and save the user ID. If it's a new user, you can either create a new account and start a session immediately, or defer that and redirect them to a signup page.
3) Render HTML/JS to notify the widget. There are different status codes and data you can return that changes the flow.
GITKit itself doesn't really manage session state, that's up to your app. Some of the reference implementations have code to help, but it's not part of the API. The widget does have some state that you can control with JS (add account, show as logged in, etc) and uses local storage in the browser.
The docs give some details and example code for how this should be implemented.
B) Of course. The URL is just configured in the javascript widget when you call setConfig() It can be set to localhost or any staging server for development. So long as your browser can reach it you're OK.
C) By "native", I assume you mean where they're signing up with just a username/password instead of using an IDP. If so, the user just has to enter their email address when logging in. If that email address matches a known IDP it'll attempt to authenticate with OpenID, otherwise if it's a new user it'll redirect to whatever signup page you configured in the widget. That signup page would just ask the user to create a password like you normally would. You should also return whether or not accounts are 'legacy' (password) accounts in the userStatus checks.
Hope that helps.
For anyone's future reference. I was able to resolve the issue. You can follow this thread of how's it's done in Clojure.
I got it working with Ring/Compojure, and another fellow showed me his solution in Webnoir.
HTH