I have an aurelia app configured to auth against auth0, and our auth0 tenant is configured with a connection to our Azure AD instance (which again redirects auth requests to our ADFS server).
The problem I'm seeing is that auth0 seems to remember the wrong username for the connection.
Here's my user:
"upn": "cyxx#domain.com",
"azure_id": "blabla",
"given_name": "Trond",
"family_name": "Hindenes",
"nickname": "cyxx#domain.com",
"tenantid": "1234",
"email": "Trond.Hindenes#domain.com",
As you can see, upn and email are not identical, and AzureAD uses the "upn" for logins. Everything works fine, except that auth0 "remembers" my login based my email address, and when it redirects me to azureAD it pre-fills the username field with my email address, not my upn.
So, my question: Is there any way to force auth0 (either in client settings or the javascript lock library) to send the correct attribute (upn) when redirecting users to AzureAD for logging on?
Currently, when Lock shows the "last time you logged with" message it uses a lastUsedUsername string provided by the server from the getSSOData endpoint as a label to identify the user.
That label is assigned the user.email or, if not available, the user.name, and cannot be changed. I understand that you are ok with this, but just to be clear you cannot alter it (you can remove the message altogether by setting the rememberLastLogin Lock option to false).
Now, if you wish to change the value that is sent to Azure AD, you can use auth.params.login_hint in the options. You can either put an empty string (to prevent Auth0 to send any hint to Azure AD) or put any value that you want (like the user's upn):
var options = {
auth: {
params: {
login_hint: '' // or anything you want
}
}
}
var lock = new Auth0Lock(..., ..., options);
The problem is that, as of now, there's really no good way to get the upn value from the user profile. But if you put an empty string Azure AD will show its own list of last used credentials, which might be good enough for your users.
Related
I am writing an App and am trying to leverage Google for A&A. The app itself relies on access to the users Google Calendar, and so initially I leveraged their updated OAUTH2 library for A&A.
Here is my flow:
User goes to the index.html which has "https://accounts.google.com/gsi/client" script and google.accounts.oauth2.initCodeClient is called with my client_id, scopes, redirect url
<script src="https://accounts.google.com/gsi/client"></script>
<script>
let client;
function initClient() {
client = google.accounts.oauth2.initCodeClient({
client_id: 'xxxxx-xxxx.apps.googleusercontent.com',
scope:
'https://www.googleapis.com/auth/userinfo.profile \
https://www.googleapis.com/auth/userinfo.email \
https://www.googleapis.com/auth/calendar.readonly \
https://www.googleapis.com/auth/calendar.events',
ux_mode: 'redirect',
redirect_uri: 'http://localhost:5000/oauth2callback',
});
}
// Request an access token
function getAuthCode() {
client.requestCode();
}
The user clicks the login button, which kicks off requestCode() and they begin the login flow. They login or select their google account, then besides the unapproved app screen, they get to the consent screen with my requested scopes.
After, they are redirected to my expressjs endpoint and using the "googleapis" library I exchange with id_token for the access and refresh tokens.
...
const { tokens } = await oauth2Client.getToken(req.query.code); //exchange code for tokens
const userInfo = (
await oauth2Client.verifyIdToken({
idToken: tokens.id_token,
audience: config.google.clientID,
})
).payload;
if (!indexBy.email[userInfo.email]) { // check if user exists
const newUser = {
name: userInfo.name,
email: userInfo.email,
o_id: userInfo.sub,
picture: userInfo.picture,
r_token: tokens.refresh_token,
};
...
Ok, all good.... but not quite. The problem is, that next time the user wants to login to the app, they go through the entire flow again, including the consent screen (again).
So, after going through more docs, even looking at examples from google. I was surprised and I noticed that many of those apps used the passport oauth2 plugin :( Something i've done in the past, but was hoping to avoid that with the recently updated Google client and nodejs libraries.
Ok, how to not prompt for consent screen on subsequent logins?
Maybe separate A&A, so first I use "Sign In With Google" for Authentication, then when I get the user info, check if the user is already registered (hence I have already saved the refresh token) and they start the app.
On the other hand, if they are new (not in existing app user collection), after authenticating, I will then call the OAUTH2 authorization redirect, so again they on Googles site, this time to do the scopes api confirmation.
So, first question, is that the best practice with most apps with leverage a Google API via OAuth? To first Authenticate, then possibility Authorize (as needed). Hopefully this will still work ok when things come up with expired/invalid refresh token (fingers crossed the default google library handles that).
When doing the Authorize for consent, can I pass something from the previous Authenticate flow so they don't need to do that again.
Or maybe when doing the Authenticate process (Google Identity Service), there is some flag or param so that if they have already consented, they don't have to do that again on subsequent logins.
Incase I wasn't clear, in a nutshell the question is: should I be doing Authenticate for login, separately from Authorization (oauth2 token). Or should I go right into the Authorization flow, which first Authenticates the user, and can I skip the Authorization consent screens if they've already done that. Or maybe there's another way which is the best practice.
Thanks for your attention.
Background info
Authentication is the act where by a user logs in into a system using their login and password. With authentication we know that the user is behind the machine. For this we use Open id connect, which was built on top of Oauth2. Open id connect returns and id_token which can be used to identify the user, it is often a jwt containing some claims to identify the subject or the user behind the Authentication.
The scope used for open id connect is profile and email. open id connect grants you consent to access a users profile information.
This is an example of the decrypted id token returned by google from a simple call using profile scope only. All this id token is telling you is who the user behind the machine is.
{
"iss": "https://accounts.google.com",
"azp": "4074087181.apps.googleusercontent.com",
"aud": "4074087181.apps.googleusercontent.com",
"sub": "1172004755672775346",
"at_hash": "pYlH4icaIx8PssR32_4qWQ",
"name": "Linda Lawton",
"picture": "https://lh3.googleusercontent.com/a-/AOh14GhroCYJp2P9xeYeYk1npchBPK-zbtTxzNQo0WAHI20=s96-c",
"given_name": "Linda",
"family_name": "Lawton",
"locale": "en",
"iat": 1655219027,
"exp": 1655222627
}
In the same call google also returned an access token. Now my call contained only the scope for profile, due to the fact that its open id connect. This means that I will only have access to the data that the profile scope would grant access to. In this case most of what is behind the Google people api.
Note: The user does not see a consent screen with open id connect, even though they are consenting to profile scope. It is assumed by signing into your account that the system you are logging into would have access to your profile info.
Authorization
Authorization is the process by which a user grants your application authorization to access their private user data. The user is shown a consent screen where they consent to your application accessing data defined by some scopes.
In the case of google calendar api there are serval
https://www.googleapis.com/auth/calendar See, edit, share, and permanently delete all the calendars you can access using Google Calendar
https://www.googleapis.com/auth/calendar.events View and edit events on all your calendars
https://www.googleapis.com/auth/calendar.events.readonly View events on all your calendars
https://www.googleapis.com/auth/calendar.readonly See and download any calendar you can access using your Google Calendar
https://www.googleapis.com/auth/calendar.settings.readonly View your Calendar settings
In this case you are only given an access token this is again Oauth2 it is authorization to access the users calendar data it is not authentication this is not related to login.
Your question
So, first question, is that the best practice with most apps with leverage a Google API via OAuth? To first Authenticate, then possibility Authorize (as needed).
You would do both at the same time.
When you authencation your user make sure to include your google calendar scope then the access token and refresh token returned will grant you access to google calendar.
I am going to assume that you have some kind of user system. When you store the user be sure to store the refresh token that is returned.
As far as Authentication goes i will assume you either have a remember me system which will set a cookie on their machine and remember the user so that you can then get the refresh token from their system the next time they come back.
If they did not chose to select a remember me option then will then have to login every time they visit your site but part of the login will return the "sub": "1172004755672775346", this is the users id on google system so you can use that in your database to match the user when they come back.
Your question is quite complex and will depend upon the type of system you have what it is designed to do as well as what programming language you are using. That being said I hope this very long answer clears things up a bit.
Question: How can I enforce existing users to set up 2FA in .Net Core 3.1 Identity?
I have seen a couple of answers here already, but I have issues with them as follows:
Redirect user to set up 2FA page on login if they do not have it set up. Problem with this is that the user can simply jump to a different url to avoid this, therefore it is not actually enforced.
Have some on executing filter that checks if the user has 2FA enbaled or not and if not redirect them to MFA set up page. The issue I have with this is that on every single navigation the server must go to the database to check whether the user has this field enabled, thus creating a significant performance hit on each request. I know one trip to the database may not sound like much but I have worked with applications where this was the norm and other things used this method, causing a pile up of pre action db queries. I want to avoid this kind of behavior unless absolutely necessary.
My current idea is to on login:
Check the users credentials but NOT log them in
userManager.CheckPasswordAsync(....)
If the credentials pass, check if the user has 2FA enabled or not. If they do, continue through login flow, if not:
Generate a user token:
userManager.GenerateUserTokenAsync(.......)
and store this along with the username in a server side cache. Then pass a key to the cached items with a redirect to the 2FA setup page, which will not have the [authorize] attribute set, allowing users not logged in to access it.
Before doing anything on the 2FA set up page, retrieve the cached items with the provied key andverify the token and username:
userManager.VerifyUserTokenAsync(......)
If this doesn't pass, return Unauthorized otherwise continue and get the current user from the supplied UserName in the url that was passed via a cache key. Also dump the cached items and key so that should the url be snatched by a dodgy browser extension it can't be used again.
Continue to pass a new cache key to new user tokens and usernames to each 2FA page to authenticate the user as they navigate.
Is this an appropriate use of user tokens? And is this approach secure enough? I'm concerned that having the user not logged in presents security issues, but I think it is necessary in order to avoid the previously mention problem of going to the database on every request to check 2FA, as with this method trying to navigate away will just redirect to login.
I implemented this via a Filter Method
I have a BasePageModel which all my pages inherit
public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
if (!User.Identity.IsAuthenticated)
{
await next.Invoke();
return;
}
var user = await UserManager.GetUserAsync(User);
var allowedPages = new List<string>
{
"Areas_Identity_Pages_Account_ConfirmEmail",
"Areas_Identity_Pages_Account_ConfirmEmailChange",
"Areas_Identity_Pages_Account_Logout",
"Areas_Identity_Pages_Account_Manage_EnableAuthenticator",
"Areas_Identity_Pages_Account_ResetPassword",
"Pages_AllowedPageX",
"Pages_AllowedPageY",
"Pages_Privacy"
};
var page = context.ActionDescriptor.PageTypeInfo.Name;
if (!user.TwoFactorEnabled && allowedPages.All(p => p != page))
{
context.Result = RedirectToPage("/Account/Manage/EnableAuthenticator", new { area = "Identity" });
}
else
{
await next.Invoke();
}
}
I then changed both the Disable2fa and ResetAuthenticator pages to redirect to the main 2fa page
public IActionResult OnGet() => RedirectToPage("./TwoFactorAuthentication");
And removed the reset/disable links from that page
I chose to implement a more modern and OAuth friendly solution (which is inline with .Net Core Identity).
Firstly, I created a custom claims principal factory that extends UserClaimsPrincipalFactory.
This allows us to add claims to the user when the runtime user object is built (I'm sorry I don't know the official name for this, but its the same thing as the User property you see on controllers).
In here I added a claim 'amr' (which is the standard name for authentication method as described in RFC 8176). That will either be set to pwd or mfa depending on whether they simply used a password or are set up with mfa.
Next, I added a custom authorize attribute that checks for this claim. If the claim is set to pwd, the authorization handler fails. This attribute is then set on all controllers that aren't to do with MFA, that way the user can still get in to set up MFA, but nothing else.
The only downside with this technique is the dev needs to remember to add that attribute to every non MFA controller, but aside from that, it works quite well as the claims are stored in the users' cookie (which isn't modifiable), so the performance hit is very small.
Hope this helps someone else, and this is what I read as a base for my solution:
https://damienbod.com/2019/12/16/force-asp-net-core-openid-connect-client-to-require-mfa/
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/mfa?view=aspnetcore-5.0#force-aspnet-core-openid-connect-client-to-require-mfa
Im creating a login for a CMS to a website for a small business using the React javascript framework. Obviously random people can't just register their own details so at present i am attempting to manually create the users (a max of 5 at present) within the cognito console. I have the majority of the authentication workflow established (using just the Auth library from Amplify) with INITIAL forced password reset, forced MFA TOTP authentication and successful access to the CMS on login. However the Forgotten Password functionality despite my best efforts just refuses to work and I believe I've narrowed it down to cognito itself.
Short of trying every damn combination of a user pool and created user to get this to work, I provide the following when creating a user from the cognito console -
1. Username (must be email)
2. Temporary Password
3. No phone or phone verification
4. Email and tick email verification
For the userpool conditions the following is the current working setup (minus the forgotten password functionality)
1. Email Address required for sign in
2. Standard attributes are given name, family name, phone number
3. MFA is required
4. Second factor is Time Based One Time Password
5. Email is selected as the attribute to be verified (which i believe to be a moot point as this is manually done when creating user)
6. No SMS role provided, required or necessary
7. I have verified an email address with SNS and have this entered in the FROM and REPLY-TO fields for email customization and have selected the use of using Amazon SES below these customization fields.
This is the entry point of my Authentication workflow, identifying where in the workflow the user is at and acting accordingly.
await Auth.signIn(email, password)
.then(user => {
setFetching(false);
switch (user.challengeName) {
case "NEW_PASSWORD_REQUIRED":
switchComponent("Verify", user);
break;
case "SMS_MFA":
case "SOFTWARE_TOKEN_MFA":
switchComponent("ConfirmSignIn", user);
break;
case "MFA_SETUP":
switchComponent("MFASetup", user);
break;
default:
history.push({ pathname: "/" });
break;
}
})
Everything works as it should for the most part. MFA workflow displays a nice QR Code for the user to utilize and confirm using their Authenticator of choice, NEW_PASSWORD_REQUIRED is submitted via the following -
const handleSubmit = async event => {
event.preventDefault();
if (noErrors()) {
setFetching(true);
await Auth.completeNewPassword(inputs.user, inputs.newPassword, {
email: inputs.email,
phone_number: inputs.phoneNumber,
given_name: inputs.givenName,
family_name: inputs.familyName
})
.then(() => {
setFetching(false);
switchComponent("MFASetup", inputs.user);
})
.catch(err => onShowDialog(err.message));
setFetching(false);
}
};
From what i can tell, nothing is out of the ordinary here. However any attempts to initialize the forgotten password flow after successfully authenticating past the REQUIRE_PASSWORD_RESET, even from the cognito console and i am presented with "Cannot reset password for the user as their is no registered/verified email or phone number", this is despite enabling the "verified email" when creating the user from the cognito console.
By using the aws command line I can force the verification however this to me is just infuriatingly unintuitive when the enabling of this when creating the user should take effect. Im at my wits end here and I have clients waiting for this software. Any help would be greatly appreciated in this instance. I apologize for any redundant content in this question I just want to make sure I cover everything the first time. Regards.
I am sure this is down to a lack of understanding.
I am trying to access the currently-logged in users claims, within an IdentityServer instance. I am finding that any claims I provide the user are only available to the setup clients, and not the IdentityServer itself.
My issue can be replicated by using any of the quick start samples provided by the IdentityServer4 team (QuickStart Samples)
I am building a site that will provide authentication, using IdentityServer4, and also provide some interface screens to manage your own profile. To facilitate this I will need access to the claims from within the IdentityServer site.
If we look at the test users on the quick starts, we have this user:
new TestUser
{
SubjectId = "1",
Username = "alice",
Password = "password",
Claims = new List<Claim>
{
new Claim("name", "Alice"),
new Claim("website", "https://alice.com")
}
},
We can see it has 2 claims; name and website.
Within the login controller, I also add another claim, just before signing in (by way of experimenting)
user.Claims.Add(new Claim("given_name", "bob"));
// issue authentication cookie with subject ID and username
await HttpContext.SignInAsync(user.SubjectId, user.Username, props);
When the QuickStart site and the MVC Client are running, I can successfully log in. The Secure page then shows me the claims below (after enabling AlwaysIncludeUserClaimsInIdToken)
However, if i visit the Grants section of the IdentityServer4 Quickstart, and inspect the current User I see an entirely different set of claims, shown below:
How, within IdentityServer4 Quickstart, can i access the same list of claims that were returned in the ID Token?
My specific reason is i will be storing an Active Directory UPM as one of the claims and will need access to this when the user is within any secure page in our Identity Server.
Ok - after a day of playing around, I realized there were other overrides for the HttpContext.SignInAsync() method.
Before, I had this - as per tutorial
await HttpContext.SignInAsync(user.SubjectId, user.Username, props);
Changing this to
await HttpContext.SignInAsync(user.SubjectId, user.Username, props, user.Claims.ToArray());
Gives me exactly what i was looking for.
Leaving this here on the off chance others have the same issue.
In this code snippet (firebase doc) they have mentioned do not use user.getUid() to authenticate with your backend server. use FirebaseUser.getToken() instead.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getToken() instead.
String uid = user.getUid();
}
getUid() // A unique user ID, intended as the user's unique key across all providers.
getToken() // The Firebase authentication token for this session.
My requirement is.
First I will register user with firebase authentication method (Email and password).
I will save String uid = user.getUid(); in my own backend server once registration is successful.
User credit information say user balance is saved in my own backend server as key user.getUid().
User sign-in with Email and password and ask for his balance.
I will get user.getUid() from firebase and match with my records, if match found returns balance to user.
They said getUid() is unique user id but Do NOT use this value to authenticate with your backend server.
Why so? Why can't we use getUid() to authenticate with your backend server??
The uid is a unique identifier for the user. So, while it identifies the user, it does not authenticate them.
A simple corollary is that my Stack Overflow ID is 209103. Knowing that, you can identify me. But to prove to Stack Overflow that you are Frank van Puffelen, requires that you know my credentials.
The ID of a user is quite often exposed in the interface. For example, if you click on my profile, you will see my ID. This is necessary for identifying me. If you would also use that same ID to authenticate, everyone who had seen your profile once could impersonate you on the site. Not a good idea when it comes to security.
Take your requirements as an example, if you using [GET] https://your-domain.com/api/users/$uid/balance to retrieve user's data, then this API is not secured at all, anybody could get other user's data with a random $uid.
As the comment(firebase doc) recommends, FirebaseUser.getToken() will get a JWT token, you should validate the token with firebase Admin SDK in your backend, and that is the data you could trust.
And the method client-side method should update to user.getIdToken() by now.
https://firebase.google.com/docs/auth/admin/verify-id-tokens is the reference for more detail.