Содержание
- Ошибка AADSTS50020 — учетная запись пользователя из поставщика удостоверений не существует в клиенте
- Симптомы
- Причина 1. Используется неподдерживаемый тип учетной записи (мультитенантные и личные учетные записи)
- Решение. Изменение параметра аудитории входа в манифесте регистрации приложения
- Причина 2. Используется неправильная конечная точка (личные учетные записи и учетные записи организации)
- Решение. Используйте правильный URL-адрес для входа.
- Причина 3. Вход в неправильный клиент
- Решение. Выйдите, а затем снова войдите из другого браузера или сеанса частного браузера.
- Причина 4. Гостевой пользователь не был приглашен
- Решение. Приглашение гостевого пользователя
- Причина 5. Приложению требуется назначение пользователя
- Решение. Назначение доступа пользователям по отдельности или в составе группы
- Причина 6. Попытка использования потока учетных данных владельца ресурса для личных учетных записей
- Решение. Используйте конечную точку, относяющуюся к клиенту или организации
- Причина 7. Ранее удаленное имя пользователя было повторно создано администратором домашнего клиента.
- Вариант проверки 1. Проверьте, старше ли гостевой пользователь клиента ресурса, чем учетная запись пользователя домашнего клиента.
- Microsoft Graph
- MSOnline PowerShell
- Вариант проверки 2. Проверьте, отличается ли идентификатор гостевой альтернативной безопасности клиента ресурса от идентификатора сети пользователя домашнего клиента.
- Решение. Сброс состояния активации учетной записи гостевого пользователя
- Свяжитесь с нами для получения помощи
- User identity error code
- Making your own Custom Errors for Login Authentication ¶
Ошибка AADSTS50020 — учетная запись пользователя из поставщика удостоверений не существует в клиенте
Эта статья поможет устранить ошибку AADSTS50020 , которая возвращается, если гостевой пользователь из поставщика удостоверений (IdP) не может войти в клиент ресурсов в Azure Active Directory (Azure AD).
Симптомы
Когда гостевой пользователь пытается получить доступ к приложению или ресурсу в клиенте ресурса, вход завершается ошибкой и отображается следующее сообщение об ошибке:
AADSTS50020: учетная запись пользователя «user@domain.com» от поставщика удостоверений не существует в клиенте .
Когда администратор просматривает журналы входа в домашнем клиенте, запись с кодом ошибки «90072» указывает на сбой входа. В сообщении об ошибке говорится:
Учетная запись пользователя от поставщика удостоверений не существует в клиенте и не может получить доступ к приложению () в этом клиенте. Сначала учетную запись необходимо добавить в качестве внешнего пользователя в клиенте. Выйдите и снова войдите с другой учетной записью пользователя Azure Active Directory.
Причина 1. Используется неподдерживаемый тип учетной записи (мультитенантные и личные учетные записи)
Если для регистрации приложения задан тип учетной записи с одним клиентом, пользователи из других каталогов или поставщиков удостоверений не смогут войти в это приложение.
Решение. Изменение параметра аудитории входа в манифесте регистрации приложения
Чтобы убедиться, что регистрация приложения не является типом учетной записи с одним клиентом, выполните следующие действия.
В портал Azure найдите и выберите Регистрация приложений.
Выберите имя регистрации приложения.
На боковой панели выберите Манифест.
В коде JSON найдите параметр signInAudience .
Проверьте, содержит ли параметр одно из следующих значений:
- AzureADandPersonalMicrosoftAccount
- AzureADMultipleOrgs
- PersonalMicrosoftAccount
Если параметр signInAudience не содержит ни одного из этих значений, повторно создайте регистрацию приложения, выбрав правильный тип учетной записи. В настоящее время изменить signInAudience в манифесте невозможно.
Причина 2. Используется неправильная конечная точка (личные учетные записи и учетные записи организации)
Вызов проверки подлинности должен быть направлен на URL-адрес, соответствующий выбранному вами, если для поддерживаемого типа учетной записи регистрации приложения задано одно из следующих значений:
Учетные записи в любом каталоге организации (любой каталог Azure AD — мультитенантный)
Учетные записи в любом каталоге организации (любой каталог Azure AD — мультитенантный) и личные учетные записи Майкрософт (например, Skype, Xbox)
Только личные учетные записи Майкрософт
Если вы используете https://login.microsoftonline.com/ , пользователи из других организаций не смогут получить доступ к приложению. Необходимо добавить этих пользователей в качестве гостей в клиент, указанный в запросе. В этом случае предполагается, что проверка подлинности будет выполняться только в клиенте. Этот сценарий вызывает ошибку входа, если предполагается, что пользователи будут входить с помощью федерации с другим клиентом или поставщиком удостоверений.
Решение. Используйте правильный URL-адрес для входа.
Используйте соответствующий URL-адрес входа для конкретного типа приложения, как указано в следующей таблице:
Тип приложения | URL-адрес для входа |
---|---|
Мультитенантные приложения | https://login.microsoftonline.com/organizations |
Мультитенантные и личные учетные записи | https://login.microsoftonline.com/common |
Только личные учетные записи | https://login.microsoftonline.com/consumers |
В коде приложения примените это значение URL-адреса в параметре Authority . Дополнительные сведения о Authority см. в разделе параметры конфигурации приложений платформа удостоверений Майкрософт.
Причина 3. Вход в неправильный клиент
Когда пользователи пытаются получить доступ к приложению, они либо отправляют прямую ссылку на приложение, либо пытаются получить доступ через https://myapps.microsoft.com. В любой ситуации пользователи перенаправляются для входа в приложение. В некоторых случаях у пользователя уже может быть активный сеанс, который использует личную учетную запись, отличную от той, которая предназначена для использования. Или у них есть сеанс, использующий учетную запись организации, хотя они намеревались использовать личную гостевую учетную запись (или наоборот).
Чтобы убедиться, что в этом сценарии возникла проблема, найдите User account значения и Identity provider в сообщении об ошибке. Соответствуют ли эти значения ожидаемой комбинации? Например, пользователь выполнил вход с помощью учетной записи организации для вашего клиента, а не с помощью домашнего клиента? Или пользователь выполнил вход в live.com поставщик удостоверений с помощью личной учетной записи, отличной от ранее приглашенной учетной записи?
Решение. Выйдите, а затем снова войдите из другого браузера или сеанса частного браузера.
Попросите пользователя открыть новый закрытый сеанс браузера или попытаться получить доступ из другого браузера. В этом случае пользователи должны выйти из активного сеанса, а затем попытаться войти еще раз.
Причина 4. Гостевой пользователь не был приглашен
Гостевой пользователь, который пытался выполнить вход, не был приглашен в клиент.
Решение. Приглашение гостевого пользователя
Убедитесь, что вы выполните действия, описанные в статье Краткое руководство. Добавление гостевых пользователей в каталог в портал Azure, чтобы пригласить гостевого пользователя.
Причина 5. Приложению требуется назначение пользователя
Если ваше приложение является корпоративным приложением, требующим назначения пользователей, ошибка возникает, AADSTS50020 если пользователь не входит в список разрешенных пользователей, которым назначен доступ к приложению. Чтобы проверить, требуется ли для корпоративного приложения назначение пользователей, выполните следующие действия:
В портал Azure найдите и выберите Корпоративные приложения.
Выберите корпоративное приложение.
На боковой панели выберите Свойства.
Проверьте, задано ли для параметра Обязательное назначение значение Да.
Решение. Назначение доступа пользователям по отдельности или в составе группы
Используйте один из следующих параметров, чтобы назначить доступ пользователям:
Сведения о назначении доступа пользователя к приложению по отдельности см. в статье Назначение учетной записи пользователя корпоративному приложению.
Сведения о назначении пользователей, если они вошли в назначенную или динамическую группу, см. в статье Управление доступом к приложению.
Причина 6. Попытка использования потока учетных данных владельца ресурса для личных учетных записей
Если пользователь пытается использовать поток учетных данных владельца ресурса (ROPC) для личных учетных записей, возникает ошибка AADSTS50020 . Платформа удостоверений Майкрософт поддерживает ROPC только в Azure AD клиентах, а не в личных учетных записях.
Решение. Используйте конечную точку, относяющуюся к клиенту или организации
Используйте конечную точку клиента ( https://login.microsoftonline.com/ ) или конечную точку организации. Личные учетные записи, приглашенные в клиент Azure AD, не могут использовать ROPC. Дополнительные сведения см. в разделе Платформа удостоверений Майкрософт и учетные данные владельца ресурса OAuth 2.0.
Причина 7. Ранее удаленное имя пользователя было повторно создано администратором домашнего клиента.
Ошибка AADSTS50020 может возникнуть, если имя гостевого пользователя, который был удален в клиенте ресурса, повторно создано администратором домашнего клиента. Чтобы убедиться, что учетная запись гостевого пользователя в клиенте ресурсов не связана с учетной записью пользователя в домашнем клиенте, используйте один из следующих параметров:
Вариант проверки 1. Проверьте, старше ли гостевой пользователь клиента ресурса, чем учетная запись пользователя домашнего клиента.
Первый вариант проверки включает сравнение возраста гостевого пользователя клиента ресурса с учетной записью пользователя домашнего клиента. Эту проверку можно выполнить с помощью Майкрософт Graph или MSOnline PowerShell.
Microsoft Graph
Отправьте запрос API Graph MS для проверки даты создания пользователя следующим образом:
Затем проверьте дату создания гостевого пользователя в клиенте ресурсов с датой создания учетной записи пользователя в домашнем клиенте. Сценарий подтверждается, если гостевой пользователь был создан до создания учетной записи пользователя домашнего клиента.
MSOnline PowerShell
Модуль PowerShell MSOnline настроен как нерекомендуемый. Так как она также несовместима с PowerShell Core, убедитесь, что вы используете совместимую версию PowerShell, чтобы можно было выполнить следующие команды.
Выполните командлет PowerShell Get-MsolUser , чтобы проверить дату создания пользователя следующим образом:
Затем проверьте дату создания гостевого пользователя в клиенте ресурсов с датой создания учетной записи пользователя в домашнем клиенте. Сценарий подтверждается, если гостевой пользователь был создан до создания учетной записи пользователя домашнего клиента.
Вариант проверки 2. Проверьте, отличается ли идентификатор гостевой альтернативной безопасности клиента ресурса от идентификатора сети пользователя домашнего клиента.
Модуль PowerShell MSOnline настроен как нерекомендуемый. Так как она также несовместима с PowerShell Core, убедитесь, что вы используете совместимую версию PowerShell, чтобы можно было выполнить следующие команды.
Когда гостевой пользователь принимает приглашение, атрибут пользователя LiveID (уникальный идентификатор входа пользователя) сохраняется в AlternativeSecurityIds атрибуте key . Так как учетная запись пользователя была удалена и создана в домашнем NetID клиенте, значение учетной записи изменится для пользователя в домашнем клиенте. NetID Сравните значение учетной записи пользователя в домашнем клиенте со значением ключа, которое хранится в AlternativeSecurityIds гостевой учетной записи в клиенте ресурса, следующим образом:
В домашнем клиенте получите значение атрибута LiveID с помощью командлета Get-MsolUser PowerShell:
В клиенте ресурса преобразуйте значение атрибута key в AlternativeSecurityIds строку в кодировке Base64:
Преобразуйте строку в кодировке base64 в шестнадцатеричное значение с помощью интерактивного преобразователя (например , base64.guru).
Сравните значения из шагов 1 и 3, чтобы убедиться, что они отличаются. Учетная NetID запись пользователя в домашнем клиенте изменилась при удалении и повторном создании учетной записи.
Решение. Сброс состояния активации учетной записи гостевого пользователя
Сброс состояния активации учетной записи гостевого пользователя в клиенте ресурса. Затем можно сохранить объект гостевого пользователя, не удаляя, а затем повторно создать учетную запись гостя. Состояние активации можно сбросить с помощью портал Azure, Azure PowerShell или Майкрософт API Graph. Инструкции см. в разделе Сброс состояния активации для гостевого пользователя.
Свяжитесь с нами для получения помощи
Если у вас есть вопросы или вам нужна помощь, создайте запрос в службу поддержки или обратитесь за поддержкой сообщества Azure. Вы также можете отправить отзыв о продукте в службу поддержки сообщества Azure.
Источник
User identity error code
The Yii Framework is very powerful and it provides a lot of functionality right from the pre-built webapp. One of the nice things that is already established for you as a developer is the Login authentication. While the default configuration simply sets it up to run against an array of hard coded usernames and passwords, the Yii Blog Tutorial provides a how to in connecting that login authentication method to a database so you can run your logins against the registered users. Talk about sweet deal.
But beyond the tutorial, one of the common things that developers seem to want to do after customizing the login authentication of CUserIdentity, is to customize the error messages that are returned from the login portal. It’s a valid desire as many developers want to add a multitude of variables to their sign in process. A common example is if you use email validation by emailing a unique activation code. So logically you will run a check of if your user is active or not before allowing them to log in. But how do we modify the error message to signify to the user they need to activate that id?
That’s the goal of this tutorial. Let’s dive in.
There are actually several key things that need to be adjusted in order to make a custom error message for the login portal. They are simple but they will drive you nuts unless you can follow the code to establish just why you get the behaviour you do. This is something that not every developer is good at, especially if you don’t have a lot of experience coding in an object oriented fashion. So this tutorial will do a walkthrough of not only how to change those error messages, but also how to follow the code so you can figure those things out as you program.
We’ll start with taking a look at the UserIdentity Component because this is where it all starts. By default the following code is what you have within the UserIdenity class found in the Component folder hierarchy.
UserIdentity Component ¶
You can already see how there is multiple errorCode references there. However when you do a login and say enter the wrong user name (or really an invalid/unregistered one) you get a generic error code that doesn’t really clarify what the issue is. See below.
So how do we fix that?
Well we have to establish why it’s doing it in the first place. That starts by investigating the class responsible for outputting the form. In this case it links to the LoginForm. Now we could show the view code of the LoginForm but understanding MVC architecture, the error code settings will not be defined in the view. They could be set in the controller (which would be sitecontroller) but because an error value is just that, a value (thus a property of a class), there’s a good chance this setting is set in the model. So we take a look at the LoginForm model.
LoginForm Model ¶
If you follow the code you’ll find the following in the authenticate function:
There’s our error! So how can we customize this? If you try to make changes as it stands, assuming you don’t get any errors you will notice that you can only change that string there, you cannot add multiple types of errors (which is what we want). If you try to add multiple types of errors you generally get a non-responsive login form where it looks like it takes the values but does nothing. That would be because it’s actually spitting out an error to you (if the login is invalid) but doesn’t know how to tell you that because of the code adjustments made in the authenticate function.
So why can’t we add more than one error? This is because of how the relationship returns back from the method call being made there. If you take a look at the login function you see that it actually makes an if case to instantiate the class of UserIdentity, which is what processes the login. It also calls the authenticate function of UserIdentity (not to be confused with the authenticate function used as a validator in LoginForm) to see if the login attempt is successful. The point of the LoginForm authenticate function then is to determine if there are any errors. When you follow the code you can establish that our next step is to revisit the UserIdentity component.
Before we go, let’s look at the code of the if statement in the authenticate function of LoginForm one more time.
This is important to notice because what that evaluates as is, «if not this», implying that the result of _identity->authenticate() is a boolean (which it is). By looking in the UserIdentity component class we confirm this.
What shows there is that if the username or the password is wrong we have an «error» constant association. But when we return that error constant, how come we only get 1 error value? It’s because we are only passing a true or false condition. We need to modify this return to make it so it returns the actual value of the constant.
Now let’s go back to the LoginForm and look at our authenticate function there:
Tracing Back Inheritance ¶
We now have to modify the if statement. It’s a change that takes it from evaluating a boolean to evaluating an actual value. Before we do that however, we need to know what the values are! This unfortunately requires you to follow back each case of the inheritance to find out where things like the constant ERROR_NONE, ERROR_USERNAME_INVALID etc. are.
Based on where we see ERROR_NONE used we have to check out the UserIdentity class. When we see no definition of constants (by means of const NAME=VALUE), we have to look at the inheritance.
So UserItentity extends CUserIdentity, which we have to find that class. This class is part of the Yii framework so we have to investigate the Yii folders (outside of our webapp) to find what we want.
CUserIdentity can be found in /framework/web/auth/
When you open up the CUserIdentity.php file you won’t find any definition to the constants but you do find another Extension:
Now lucky for us the CBaseUserIdentity.php resides in the same folder, when we open that up we at last have finally found our constants:
Perfect! So now we know what those values are that are associated to the constants. We also learn that errorCode defaults to 100, implying an Unknown Identity error. That means we can go back to our LoginForm and fix the authenticate function.
Customizing the Errors ¶
Now a proper reference would use the constant variable declaration rather than the value but I choose to show you in the value form so you can corrolate what you’re evaluating (and thus what’s being returned from the authenticate function in UserIdentity). However if you wanted to put in the proper coding it would be defined just like it is shown in the LoginForm login function:
In our case we would be using UserIdentity::ERROR_USERNAME_INVALID or UserIdentity::ERROR_PASSWORD_INVALID like so:
Congratulations you have successfully changed the error messages to have multiple types of errors defined and displayed!
Making your own Custom Errors for Login Authentication ¶
But what about making your own error and thus own error message? That’s simple, now that we have the framework in place to customize and evaluate errors, we just need to define our own error.
We’ll take the Blog Tutorials example of UserIdentity to reference a database type login authentication and we’ll make a custom error for if a user account «isActive». This of course implies that you have a database field labeled isActive and that it contains a true or false value (1 or 0) in order to process.
The Blog Tutorial UserIdentity:
First we need to change this by defining our own constant. Then we need to change the logic flow by assessing the error to a value, in our case isActive to 0 (false) or 1 (true). Finally we need to make sure that we change the return statement to return the value of the error constant not just whether it passes or not.
Finally we need to go back to our LoginForm and change / add our custom error. Remember to switch in the constants as oppose to the numerical values. It’s just good practice.
The final result is:
One final thing to note is that the addError pulls an attribute value first, here you see ‘username’ or ‘password’. These reference to which field to show the error under. In our case with our custom value we know the user authenticates properly and exist in our DB, they just haven’t activated their account yet. As such we label the error to the ‘username’.
That’s it for the tutorial, I hope you learned a lot in understanding how to follow the logical flow of code assignments and debugging the functions, variables and classes in this case. I also hope this helps you put to good use how to modify your own custom errors into the login authentication process.
Источник
title | description | ms.date | author | ms.author | ms.editor | ms.reviewer | ms.service | ms.subservice | keywords |
---|---|---|---|---|---|---|---|---|---|
Error AADSTS50020 — User account from identity provider does not exist in tenant |
Troubleshoot scenarios in which a guest user unsuccessfully tries to sign in to the resource tenant and error code AADSTS50020 is returned. |
04/15/2022 |
DennisLee-DennisLee |
v-dele |
v-jsitser |
rrajan,haelshab,sungow |
active-directory |
app-mgmt |
Error AADSTS50020 — User account from identity provider does not exist in tenant
This article helps you troubleshoot error code AADSTS50020
that’s returned if a guest user from an identity provider (IdP) can’t sign in to a resource tenant in Azure Active Directory (Azure AD).
Symptoms
When a guest user tries to access an application or resource in the resource tenant, the sign-in fails, and the following error message is displayed:
AADSTS50020: User account ‘user@domain.com’ from identity provider {IdentityProviderURL} does not exist in tenant {ResourceTenantName}.
When an administrator reviews the sign-in logs on the home tenant, a «90072» error code entry indicates a sign-in failure. The error message states:
User account {email} from identity provider {idp} does not exist in tenant {tenant} and cannot access the application {appId}({appName}) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.
Cause 1: Used unsupported account type (multitenant and personal accounts)
If your app registration is set to a single-tenant account type, users from other directories or identity providers can’t sign in to that application.
Solution: Change the sign-in audience setting in the app registration manifest
To make sure that your app registration isn’t a single-tenant account type, perform the following steps:
-
In the Azure portal, search for and select App registrations.
-
Select the name of your app registration.
-
In the sidebar, select Manifest.
-
In the JSON code, find the signInAudience setting.
-
Check whether the setting contains one of the following values:
- AzureADandPersonalMicrosoftAccount
- AzureADMultipleOrgs
- PersonalMicrosoftAccount
If the signInAudience setting doesn’t contain one of these values, re-create the app registration by having the correct account type selected. You currently can’t change signInAudience in the manifest.
For more information about how to register applications, see Quickstart: Register an application with the Microsoft identity platform.
Cause 2: Used the wrong endpoint (personal and organization accounts)
Your authentication call must target a URL that matches your selection if your app registration’s supported account type was set to one of the following values:
-
Accounts in any organizational directory (Any Azure AD directory — Multitenant)
-
Accounts in any organizational directory (Any Azure AD directory — Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)
-
Personal Microsoft accounts only
If you use https://login.microsoftonline.com/<YourTenantNameOrID>
, users from other organizations can’t access the application. You have to add these users as guests in the tenant that’s specified in the request. In that case, the authentication is expected to be run on your tenant only. This scenario causes the sign-in error if you expect users to sign in by using federation with another tenant or identity provider.
Solution: Use the correct sign-in URL
Use the corresponding sign-in URL for the specific application type, as listed in the following table:
Application type | Sign-in URL |
---|---|
Multitenant applications | https://login.microsoftonline.com/organizations |
Multitenant and personal accounts | https://login.microsoftonline.com/common |
Personal accounts only | https://login.microsoftonline.com/consumers |
In your application code, apply this URL value in the Authority
setting. For more information about Authority
, see Microsoft identity platform application configuration options.
Cause 3: Signed in to the wrong tenant
When users try to access your application, either they’re sent a direct link to the application, or they try to gain access through https://myapps.microsoft.com. In either situation, users are redirected to sign in to the application. In some cases, the user might already have an active session that uses a different personal account than the one that’s intended to be used. Or they have a session that uses their organization account although they intended to use a personal guest account (or vice versa).
To make sure that this scenario is the issue, look for the User account
and Identity provider
values in the error message. Do those values match the expected combination or not? For example, did a user sign in by using their organization account to your tenant instead of their home tenant? Or did a user sign in to the live.com
identity provider by using a different personal account than the one that was already invited?
Solution: Sign out, then sign in again from a different browser or a private browser session
Instruct the user to open a new in-private browser session or have the user try to access from a different browser. In this case, users must sign out from their active session, and then try to sign in again.
Cause 4: Guest user wasn’t invited
The guest user who tried to sign in was not invited to the tenant.
Solution: Invite the guest user
Make sure that you follow the steps in Quickstart: Add guest users to your directory in the Azure portal to invite the guest user.
Cause 5: App requires user assignment
If your application is an enterprise application that requires user assignment, error AADSTS50020
occurs if the user isn’t on the list of allowed users who are assigned access to the application. To check whether your enterprise application requires user assignment:
-
In the Azure portal, search for and select Enterprise applications.
-
Select your enterprise application.
-
In the sidebar, select Properties.
-
Check whether the Assignment required option is set to Yes.
Solution: Assign access to users individually or as part of a group
Use one of the following options to assign access to users:
-
To individually assign the user access to the application, see Assign a user account to an enterprise application.
-
To assign users if they’re a member of an assigned group or a dynamic group, see Manage access to an application.
Cause 6: Tried to use a resource owner password credentials flow for personal accounts
If a user tries to use the resource owner password credentials (ROPC) flow for personal accounts, error AADSTS50020
occurs. The Microsoft identity platform supports ROPC only within Azure AD tenants, not personal accounts.
Solution: Use an endpoint that’s specific to the tenant or organization
Use a tenant-specific endpoint (https://login.microsoftonline.com/<TenantIDOrName>
) or the organization’s endpoint. Personal accounts that are invited to an Azure AD tenant can’t use ROPC. For more information, see Microsoft identity platform and OAuth 2.0 Resource Owner Password Credentials.
Cause 7: A previously deleted user name was re-created by the home tenant administrator
Error AADSTS50020
might occur if the name of a guest user who was deleted in a resource tenant is re-created by the administrator of the home tenant. To verify that the guest user account in the resource tenant isn’t associated with a user account in the home tenant, use one of the following options:
Verification option 1: Check whether the resource tenant’s guest user is older than the home tenant’s user account
The first verification option involves comparing the age of the resource tenant’s guest user against the home tenant’s user account. You can make this verification by using Microsoft Graph or MSOnline PowerShell.
Microsoft Graph
Issue a request to the MS Graph API to review the user creation date, as follows:
GET https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/createdDateTime
Then, check the creation date of the guest user in the resource tenant against the creation date of the user account in the home tenant. The scenario is confirmed if the guest user was created before the home tenant’s user account was created.
MSOnline PowerShell
[!NOTE]
The MSOnline PowerShell module is set to be deprecated.
Because it’s also incompatible with PowerShell Core, make sure that you’re using a compatible PowerShell version so that you can run the following commands.
Run the Get-MsolUser PowerShell cmdlet to review the user creation date, as follows:
Get-MsolUser -SearchString user@contoso.com | Format-List whenCreated
Then, check the creation date of the guest user in the resource tenant against the creation date of the user account in the home tenant. The scenario is confirmed if the guest user was created before the home tenant’s user account was created.
Verification option 2: Check whether the resource tenant’s guest alternative security ID differs from the home tenant’s user net ID
[!NOTE]
The MSOnline PowerShell module is set to be deprecated.
Because it’s also incompatible with PowerShell Core, make sure that you’re using a compatible PowerShell version so that you can run the following commands.
When a guest user accepts an invitation, the user’s LiveID
attribute (the unique sign-in ID of the user) is stored within AlternativeSecurityIds
in the key
attribute. Because the user account was deleted and created in the home tenant, the NetID
value for the account will have changed for the user in the home tenant. Compare the NetID
value of the user account in the home tenant against the key value that’s stored within AlternativeSecurityIds
of the guest account in the resource tenant, as follows:
-
In the home tenant, retrieve the value of the
LiveID
attribute using theGet-MsolUser
PowerShell cmdlet:Get-MsolUser -SearchString tuser1 | Select-Object -ExpandProperty LiveID
-
In the resource tenant, convert the value of the
key
attribute withinAlternativeSecurityIds
to a base64-encoded string:[convert]::ToBase64String((Get-MsolUser -ObjectId 01234567-89ab-cdef-0123-456789abcdef ).AlternativeSecurityIds.key)
-
Convert the base64-encoded string to a hexadecimal value by using an online converter (such as base64.guru).
-
Compare the values from step 1 and step 3 to verify that they’re different. The
NetID
of the user account in the home tenant changed when the account was deleted and re-created.
Solution: Reset the redemption status of the guest user account
Reset the redemption status of the guest user account in the resource tenant. Then, you can keep the guest user object without having to delete and then re-create the guest account. You can reset the redemption status by using the Azure portal, Azure PowerShell, or the Microsoft Graph API. For instructions, see Reset redemption status for a guest user.
[!INCLUDE Azure Help Support]
title | description | ms.date | author | ms.author | ms.editor | ms.reviewer | ms.service | ms.subservice | keywords |
---|---|---|---|---|---|---|---|---|---|
Error AADSTS50020 — User account from identity provider does not exist in tenant |
Troubleshoot scenarios in which a guest user unsuccessfully tries to sign in to the resource tenant and error code AADSTS50020 is returned. |
04/15/2022 |
DennisLee-DennisLee |
v-dele |
v-jsitser |
rrajan,haelshab,sungow |
active-directory |
app-mgmt |
Error AADSTS50020 — User account from identity provider does not exist in tenant
This article helps you troubleshoot error code AADSTS50020
that’s returned if a guest user from an identity provider (IdP) can’t sign in to a resource tenant in Azure Active Directory (Azure AD).
Symptoms
When a guest user tries to access an application or resource in the resource tenant, the sign-in fails, and the following error message is displayed:
AADSTS50020: User account ‘user@domain.com’ from identity provider {IdentityProviderURL} does not exist in tenant {ResourceTenantName}.
When an administrator reviews the sign-in logs on the home tenant, a «90072» error code entry indicates a sign-in failure. The error message states:
User account {email} from identity provider {idp} does not exist in tenant {tenant} and cannot access the application {appId}({appName}) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.
Cause 1: Used unsupported account type (multitenant and personal accounts)
If your app registration is set to a single-tenant account type, users from other directories or identity providers can’t sign in to that application.
Solution: Change the sign-in audience setting in the app registration manifest
To make sure that your app registration isn’t a single-tenant account type, perform the following steps:
-
In the Azure portal, search for and select App registrations.
-
Select the name of your app registration.
-
In the sidebar, select Manifest.
-
In the JSON code, find the signInAudience setting.
-
Check whether the setting contains one of the following values:
- AzureADandPersonalMicrosoftAccount
- AzureADMultipleOrgs
- PersonalMicrosoftAccount
If the signInAudience setting doesn’t contain one of these values, re-create the app registration by having the correct account type selected. You currently can’t change signInAudience in the manifest.
For more information about how to register applications, see Quickstart: Register an application with the Microsoft identity platform.
Cause 2: Used the wrong endpoint (personal and organization accounts)
Your authentication call must target a URL that matches your selection if your app registration’s supported account type was set to one of the following values:
-
Accounts in any organizational directory (Any Azure AD directory — Multitenant)
-
Accounts in any organizational directory (Any Azure AD directory — Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)
-
Personal Microsoft accounts only
If you use https://login.microsoftonline.com/<YourTenantNameOrID>
, users from other organizations can’t access the application. You have to add these users as guests in the tenant that’s specified in the request. In that case, the authentication is expected to be run on your tenant only. This scenario causes the sign-in error if you expect users to sign in by using federation with another tenant or identity provider.
Solution: Use the correct sign-in URL
Use the corresponding sign-in URL for the specific application type, as listed in the following table:
Application type | Sign-in URL |
---|---|
Multitenant applications | https://login.microsoftonline.com/organizations |
Multitenant and personal accounts | https://login.microsoftonline.com/common |
Personal accounts only | https://login.microsoftonline.com/consumers |
In your application code, apply this URL value in the Authority
setting. For more information about Authority
, see Microsoft identity platform application configuration options.
Cause 3: Signed in to the wrong tenant
When users try to access your application, either they’re sent a direct link to the application, or they try to gain access through https://myapps.microsoft.com. In either situation, users are redirected to sign in to the application. In some cases, the user might already have an active session that uses a different personal account than the one that’s intended to be used. Or they have a session that uses their organization account although they intended to use a personal guest account (or vice versa).
To make sure that this scenario is the issue, look for the User account
and Identity provider
values in the error message. Do those values match the expected combination or not? For example, did a user sign in by using their organization account to your tenant instead of their home tenant? Or did a user sign in to the live.com
identity provider by using a different personal account than the one that was already invited?
Solution: Sign out, then sign in again from a different browser or a private browser session
Instruct the user to open a new in-private browser session or have the user try to access from a different browser. In this case, users must sign out from their active session, and then try to sign in again.
Cause 4: Guest user wasn’t invited
The guest user who tried to sign in was not invited to the tenant.
Solution: Invite the guest user
Make sure that you follow the steps in Quickstart: Add guest users to your directory in the Azure portal to invite the guest user.
Cause 5: App requires user assignment
If your application is an enterprise application that requires user assignment, error AADSTS50020
occurs if the user isn’t on the list of allowed users who are assigned access to the application. To check whether your enterprise application requires user assignment:
-
In the Azure portal, search for and select Enterprise applications.
-
Select your enterprise application.
-
In the sidebar, select Properties.
-
Check whether the Assignment required option is set to Yes.
Solution: Assign access to users individually or as part of a group
Use one of the following options to assign access to users:
-
To individually assign the user access to the application, see Assign a user account to an enterprise application.
-
To assign users if they’re a member of an assigned group or a dynamic group, see Manage access to an application.
Cause 6: Tried to use a resource owner password credentials flow for personal accounts
If a user tries to use the resource owner password credentials (ROPC) flow for personal accounts, error AADSTS50020
occurs. The Microsoft identity platform supports ROPC only within Azure AD tenants, not personal accounts.
Solution: Use an endpoint that’s specific to the tenant or organization
Use a tenant-specific endpoint (https://login.microsoftonline.com/<TenantIDOrName>
) or the organization’s endpoint. Personal accounts that are invited to an Azure AD tenant can’t use ROPC. For more information, see Microsoft identity platform and OAuth 2.0 Resource Owner Password Credentials.
Cause 7: A previously deleted user name was re-created by the home tenant administrator
Error AADSTS50020
might occur if the name of a guest user who was deleted in a resource tenant is re-created by the administrator of the home tenant. To verify that the guest user account in the resource tenant isn’t associated with a user account in the home tenant, use one of the following options:
Verification option 1: Check whether the resource tenant’s guest user is older than the home tenant’s user account
The first verification option involves comparing the age of the resource tenant’s guest user against the home tenant’s user account. You can make this verification by using Microsoft Graph or MSOnline PowerShell.
Microsoft Graph
Issue a request to the MS Graph API to review the user creation date, as follows:
GET https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/createdDateTime
Then, check the creation date of the guest user in the resource tenant against the creation date of the user account in the home tenant. The scenario is confirmed if the guest user was created before the home tenant’s user account was created.
MSOnline PowerShell
[!NOTE]
The MSOnline PowerShell module is set to be deprecated.
Because it’s also incompatible with PowerShell Core, make sure that you’re using a compatible PowerShell version so that you can run the following commands.
Run the Get-MsolUser PowerShell cmdlet to review the user creation date, as follows:
Get-MsolUser -SearchString user@contoso.com | Format-List whenCreated
Then, check the creation date of the guest user in the resource tenant against the creation date of the user account in the home tenant. The scenario is confirmed if the guest user was created before the home tenant’s user account was created.
Verification option 2: Check whether the resource tenant’s guest alternative security ID differs from the home tenant’s user net ID
[!NOTE]
The MSOnline PowerShell module is set to be deprecated.
Because it’s also incompatible with PowerShell Core, make sure that you’re using a compatible PowerShell version so that you can run the following commands.
When a guest user accepts an invitation, the user’s LiveID
attribute (the unique sign-in ID of the user) is stored within AlternativeSecurityIds
in the key
attribute. Because the user account was deleted and created in the home tenant, the NetID
value for the account will have changed for the user in the home tenant. Compare the NetID
value of the user account in the home tenant against the key value that’s stored within AlternativeSecurityIds
of the guest account in the resource tenant, as follows:
-
In the home tenant, retrieve the value of the
LiveID
attribute using theGet-MsolUser
PowerShell cmdlet:Get-MsolUser -SearchString tuser1 | Select-Object -ExpandProperty LiveID
-
In the resource tenant, convert the value of the
key
attribute withinAlternativeSecurityIds
to a base64-encoded string:[convert]::ToBase64String((Get-MsolUser -ObjectId 01234567-89ab-cdef-0123-456789abcdef ).AlternativeSecurityIds.key)
-
Convert the base64-encoded string to a hexadecimal value by using an online converter (such as base64.guru).
-
Compare the values from step 1 and step 3 to verify that they’re different. The
NetID
of the user account in the home tenant changed when the account was deleted and re-created.
Solution: Reset the redemption status of the guest user account
Reset the redemption status of the guest user account in the resource tenant. Then, you can keep the guest user object without having to delete and then re-create the guest account. You can reset the redemption status by using the Azure portal, Azure PowerShell, or the Microsoft Graph API. For instructions, see Reset redemption status for a guest user.
[!INCLUDE Azure Help Support]
Comments
@chunsiongtan Thank you for trying out the Windows virtual desktops preview product . We thank you for your contribution and sharing the solution for an issue you encountered. We appreciate the contribution. Please let us know if you have any further query on this preview feature and we would love to help you.
Hi, I had this issue when trying to deploy using my Visual Studio MSDN subscription, which is a personal microsoft account.
Before starting the tutorial, make sure your AAD is correctly set up and create a user with global admin permissions. Create an office 365 tenant and associate it to your subscription with the new account having an E3/E5 licence.
Once you’ve done this, sign in to Azure Portal to reset the password and you’re ready to begin the tutorial.
Thank you for your contribution. Your understanding is correct . We need to make sure that the currently logged in session is from a work account and it has related licenses if a work account is testing virtual desktops. And if you are trying to provide an eternal user access to the virtual desktop published in your directory , you would need to first add the external user as a MSA (microsoft Account / live ID ) in your tenant .
We will close this issue now . We appreciate the contribution.
Thank you.
Which Version of MSAL are you using ?
MSAL 4.3.1
Platform
all
What authentication flow has the issue?
- Desktop / Mobile
- Interactive
Description
In UWP apps (possibly also in non-UWP), if you execute the following sequence, an AADSTS50020 is issued:
AcquireTokenInteractive()
[user logs in successfully to CompanyA.com]AcquireTokenSilent()
[this is required for the bug to appear]- Log out (see code below)
AcquireTokenInteractive()
[user tries to login into CompanyB.com]
The user should be able to log into CompanyB, however we get this error:
AADSTS50020: User account ‘[someemail]’ from identity provider ‘https://sts.windows.net/[some_guid]/’ does not exist in tenant ‘[some name]’ and cannot access the application ‘[some_guid]'(AppName) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.
Logout looks like this:
var accounts = await _graphApp.GetAccountsAsync(); while (accounts.Any()) { await _graphApp.RemoveAsync(accounts.FirstOrDefault()); accounts = await _graphApp.GetAccountsAsync(); }
Additional Information
- If you restart the app between steps 3 and 4, things work as expected (user can log into CompanyB).
- Adding
.WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
to the app builder does not resolve the problem.
I have provided a sample app to demonstrate this problem. You must supply your own AppId.
Which Version of MSAL are you using ?
MSAL 4.3.1
Platform
all
What authentication flow has the issue?
- Desktop / Mobile
- Interactive
Description
In UWP apps (possibly also in non-UWP), if you execute the following sequence, an AADSTS50020 is issued:
AcquireTokenInteractive()
[user logs in successfully to CompanyA.com]AcquireTokenSilent()
[this is required for the bug to appear]- Log out (see code below)
AcquireTokenInteractive()
[user tries to login into CompanyB.com]
The user should be able to log into CompanyB, however we get this error:
AADSTS50020: User account ‘[someemail]’ from identity provider ‘https://sts.windows.net/[some_guid]/’ does not exist in tenant ‘[some name]’ and cannot access the application ‘[some_guid]'(AppName) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.
Logout looks like this:
var accounts = await _graphApp.GetAccountsAsync(); while (accounts.Any()) { await _graphApp.RemoveAsync(accounts.FirstOrDefault()); accounts = await _graphApp.GetAccountsAsync(); }
Additional Information
- If you restart the app between steps 3 and 4, things work as expected (user can log into CompanyB).
- Adding
.WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
to the app builder does not resolve the problem.
I have provided a sample app to demonstrate this problem. You must supply your own AppId.
Microsoft Teams is indispensable in our work life these days. Nothing is more annoying than an error message like ‘aadsts50020’, when you need Microsoft Teams the most.
Tech Support 24/7
Ask a Tech Specialist Online
Connect with the Expert via email, text or phone. Include photos, documents, and more. Get step-by-step instructions from verified Tech Support Specialists.
On this page, you will find more information about the most common causes and most relevant solutions for the Microsoft Teams error ‘aadsts50020’. Do you need help straight away? Visit our support page.
Error information
How to solve Microsoft Teams error aadsts50020
We’ve created a list of solutions which you can follow if you want to solve this Microsoft Teams problem yourself. Do you need more help? Visit our support page if you need professional support with Microsoft Teams right away.
Tech Support 24/7
Ask a Tech Specialist Online
Connect with the Expert via email, text or phone. Include photos, documents, and more. Get step-by-step instructions from verified Tech Support Specialists.
Have you found a solution yourself, but it is not in the list? Share your solution in the comments below.
Need more help?
Do you need more help?
Tech experts are ready to answer your questions.
Ask a question
- Remove From My Forums
-
Question
-
Hi Team,
I am working on Asp.net based application and try to configuring single sign on with multi Tenant domain login but not working.
Error Message:
AADSTS50020: User account ‘abc@outlook.com’ from identity provider ‘live.com’ does not exist in tenant ‘xyz’ and cannot access the application ‘1b4fd1d3-2255-4318-af43-b2d813405280’ in that tenant. The account needs to be added as an external user in the
tenant first. Sign out and sign in again with a different Azure Active Directory user account.kindly look into this case.
Thanks in advance.
Answers
-
I was having the same problem, my issue is fixed after changing Tenant ID value from specific tenant ID to ‘common’ in OAuth service provider connection settings in Azure portal for Bot Configuration.
My app is asp.net bot, but if your app is UWP, you need to pass right AadAuthorityAudience value to MSAL call in your code , it should be 2 or 3.
//
// Summary:
// Specifies which Microsoft accounts can be used for sign-in with a given application.
// See https://aka.ms/msal-net-application-configuration
public enum AadAuthorityAudience
{
//
// Summary:
// The sign-in audience was not specified
None = 0,
//
// Summary:
// Users with a Microsoft work or school account in my organization’s Azure AD tenant
// (i.e. single tenant). Maps to https://[instance]/[tenantId]
AzureAdMyOrg = 1,
//
// Summary:
// Users with a personal Microsoft account, or a work or school account in any organization’s
// Azure AD tenant Maps to https://[instance]/common/
AzureAdAndPersonalMicrosoftAccount = 2,
//
// Summary:
// Users with a Microsoft work or school account in any organization’s Azure AD
// tenant (i.e. multi-tenant). Maps to https://[instance]/organizations/
AzureAdMultipleOrgs = 3,
//
// Summary:
// Users with a personal Microsoft account. Maps to https://[instance]/consumers/
PersonalMicrosoftAccount = 4
}I hope this helps
Snekithan
-
Marked as answer by
Thursday, October 24, 2019 4:46 AM
-
Marked as answer by