Browse Source

Merge remote-tracking branch 'origin/rel-10.7' into auto-merge-forward/rel-10.7-to-dev-94

pull/26309/head
github-actions[bot] 1 month ago
parent
commit
75bf22738e
  1. 2
      docs/en/modules/elsa-pro.md
  2. 4
      modules/account/Volo.Abp.Account.abpmdl
  3. 1
      modules/account/Volo.Abp.Account.slnx
  4. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ar.json
  5. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/cs.json
  6. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/da.json
  7. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/de.json
  8. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/el.json
  9. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/en-GB.json
  10. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/en.json
  11. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/es-mx.json
  12. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/es.json
  13. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fa.json
  14. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fi.json
  15. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fr.json
  16. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hi.json
  17. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hr.json
  18. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hu.json
  19. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/is.json
  20. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/it.json
  21. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/nl.json
  22. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/pl-PL.json
  23. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/pt-BR.json
  24. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ro-RO.json
  25. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ru.json
  26. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sk.json
  27. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sl.json
  28. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sv.json
  29. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/tr.json
  30. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/vi.json
  31. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/zh-Hans.json
  32. 2
      modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/zh-Hant.json
  33. 22
      modules/account/src/Volo.Abp.Account.Web.IdentityServer/Pages/Account/IdentityServerSupportedLoginModel.cs
  34. 32
      modules/account/src/Volo.Abp.Account.Web/Pages/Account/AccountPageModel.cs
  35. 35
      modules/account/src/Volo.Abp.Account.Web/Pages/Account/Login.cshtml.cs
  36. 28
      modules/account/src/Volo.Abp.Account.Web/Pages/Account/Register.cshtml.cs
  37. 4
      modules/account/test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.abppkg
  38. 23
      modules/account/test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.csproj
  39. 40
      modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebIdentityServerTestModule.cs
  40. 181
      modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebTestBase.cs
  41. 46
      modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebTestModule.cs
  42. 81
      modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/AccountPageModel_SignInCheck_Tests.cs
  43. 34
      modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/IdentityServerSupportedLogin_NotAllowedUser_Tests.cs
  44. 78
      modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Login_ExternalLoginCallback_Tests.cs
  45. 113
      modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Login_NotAllowedUser_Tests.cs
  46. 64
      modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Register_Tests.cs
  47. 33
      modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/TestExternalLoginProvider.cs
  48. 47
      modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInManager.cs
  49. 25
      modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInResult.cs
  50. 15
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserManager.cs
  51. 1
      modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestModule.cs
  52. 130
      modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpSignInManager_PreSignInCheckWithoutPassword_Tests.cs
  53. 30
      modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/DisabledFakeExternalLoginProvider.cs
  54. 116
      modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/ExternalLoginProvider_Tests.cs
  55. 14
      modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/FakeExternalLoginProvider.cs
  56. 106
      modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidator.cs
  57. 213
      modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidatorExternalLogin_Tests.cs
  58. 118
      modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidatorPasswordChange_Tests.cs
  59. 31
      modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/DisabledTestExternalLoginProvider.cs
  60. 32
      modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/TestExternalLoginProvider.cs
  61. 2
      modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpErrorDescriptionConsts.cs
  62. 103
      modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/Controllers/TokenController.Password.cs
  63. 31
      modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/DisabledTestExternalLoginProvider.cs
  64. 287
      modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/OpenIddictPasswordGrantExternalLogin_Integration_Tests.cs
  65. 119
      modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/OpenIddictPasswordGrantPasswordChange_Integration_Tests.cs
  66. 34
      modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/TestExternalLoginProvider.cs

2
docs/en/modules/elsa-pro.md

@ -235,6 +235,8 @@ Then, you can log in to the Elsa Studio application with the host admin credenti
![elsa-login](../images/elsa-password-login.png)
The Elsa Identity login applies the sign-in checks of the ABP Identity module: inactive and locked out users can't log in, unconfirmed users can't log in if a confirmation is required, and failed attempts are counted for the account lockout. This login has no second step, so users that must change their password or require two-factor authentication can't log in with it either. It only issues an access token, users log in again when the access token expires. Use the code flow authentication below for these users or to refresh the tokens.
Once you have logged in, you can define and manage workflows and view their execution instances:
![elsa-main](../images/elsa-main-page.png)

4
modules/account/Volo.Abp.Account.abpmdl

@ -38,6 +38,10 @@
"path": "test/Volo.Abp.Account.Application.Tests/Volo.Abp.Account.Application.Tests.abppkg",
"folder": "test"
},
"Volo.Abp.Account.Web.Tests": {
"path": "test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.abppkg",
"folder": "test"
},
"Volo.Abp.Account.Blazor": {
"path": "src/Volo.Abp.Account.Blazor/Volo.Abp.Account.Blazor.abppkg",
"folder": "src"

1
modules/account/Volo.Abp.Account.slnx

@ -13,5 +13,6 @@
</Folder>
<Folder Name="/test/">
<Project Path="test/Volo.Abp.Account.Application.Tests/Volo.Abp.Account.Application.Tests.csproj" />
<Project Path="test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.csproj" />
</Folder>
</Solution>

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ar.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "تم قفل حساب المستخدم بسبب محاولات تسجيل الدخول غير الصالحة. يرجى الانتظار بعض الوقت والمحاولة مرة أخرى.",
"InvalidUserNameOrPassword": "اسم مستخدم أو كلمة مرور غير صالحة!",
"LoginIsNotAllowed": "لا يسمح لك بتسجيل الدخول! حسابك غير نشط أو يحتاج إلى تأكيد بريدك الإلكتروني/رقم هاتفك.",
"ExternalLoginPasswordChangeRequired": "لا يسمح لك بتسجيل الدخول! يجب تغيير كلمة المرور الخاصة بك، لكن ذلك غير ممكن عند تسجيل الدخول الخارجي. يرجى الاتصال بالمسؤول.",
"RegisteredButLoginIsNotAllowed": "تم إنشاء حسابك، لكن لا يسمح لك بتسجيل الدخول بعد!",
"SelfRegistrationDisabledMessage": "تم تعطيل التسجيل الذاتي لهذا التطبيق. يرجى الاتصال بمسؤول التطبيق لتسجيل مستخدم جديد.",
"LocalLoginDisabledMessage": "تسجيل الدخول المحلي معطّل لهذا التطبيق.",
"Login": "دخول",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/cs.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Tento účet byl uzamčen z důvodu neúspěšných přihlášení. Přihlaste se prosím později.",
"InvalidUserNameOrPassword": "Neplatné uživatelské jméno nebo heslo!",
"LoginIsNotAllowed": "Nemáte oprávnění se přihlásit! Váš účet je neaktivní nebo potřebuje potvrdit váš e -mail/telefonní číslo.",
"ExternalLoginPasswordChangeRequired": "Nemáte oprávnění se přihlásit! Vaše heslo musí být změněno, což ale při externím přihlášení není možné. Kontaktujte prosím svého správce.",
"RegisteredButLoginIsNotAllowed": "Váš účet byl vytvořen, ale zatím nemáte oprávnění se přihlásit!",
"SelfRegistrationDisabledMessage": "Vlastní registrace uživatele není povolena. K vytvoření účtu kontaktujte správce.",
"LocalLoginDisabledMessage": "Místní přihlášení je pro tuto aplikaci zakázáno.",
"Login": "Přihlásit",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/da.json

@ -10,6 +10,8 @@
"UserLockedOutMessage": "Brugerkontoen er blevet låst grundet forkerte login forsøg. Vent venligst og prøv igen.",
"InvalidUserNameOrPassword": "Forkert brugernavn eller kodeord!",
"LoginIsNotAllowed": "Du kan ikke logge ind! Du skal bekræfte den angivne email/telefonnummer.",
"ExternalLoginPasswordChangeRequired": "Du kan ikke logge ind! Dit kodeord skal ændres, men det er ikke muligt med et eksternt login. Kontakt venligst din administrator.",
"RegisteredButLoginIsNotAllowed": "Din konto er oprettet, men du kan ikke logge ind endnu!",
"SelfRegistrationDisabledMessage": "Selvregistrering er deaktiveret for denne applikation. Kontakt venligst applikationens administrator for at registrere en ny bruger.",
"LocalLoginDisabledMessage": "Lokalt login er deaktiveret for denne appliaktion.",
"Login": "Login",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/de.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Das Benutzerkonto wurde aufgrund ungültiger Anmeldeversuche gesperrt. Bitte warten Sie eine Weile und versuchen Sie es erneut.",
"InvalidUserNameOrPassword": "Ungültiger Benutzername oder Passwort!",
"LoginIsNotAllowed": "Sie dürfen sich nicht anmelden! Ihr Konto ist inaktiv oder muss Ihre E-Mail-/Telefonnummer bestätigen.",
"ExternalLoginPasswordChangeRequired": "Sie dürfen sich nicht anmelden! Ihr Passwort muss geändert werden, was bei einer externen Anmeldung jedoch nicht möglich ist. Bitte wenden Sie sich an Ihren Administrator.",
"RegisteredButLoginIsNotAllowed": "Ihr Konto wurde erstellt, aber Sie dürfen sich noch nicht anmelden!",
"SelfRegistrationDisabledMessage": "Die Selbstregistrierung ist für diese Anwendung deaktiviert. Bitte wenden Sie sich an den Anwendungsadministrator, um einen neuen Benutzer zu registrieren.",
"LocalLoginDisabledMessage": "Die lokale Anmeldung ist für diese Anwendung deaktiviert.",
"Login": "Anmelden",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/el.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Ο λογαριασμός χρήστη έχει κλειδωθεί λόγω μη έγκυρων προσπαθειών σύνδεσης. Περιμένετε λίγο και προσπαθήστε ξανά.",
"InvalidUserNameOrPassword": "Μη έγκυρο όνομα χρήστη ή κωδικός!",
"LoginIsNotAllowed": "Δεν επιτρέπεται να συνδεθείτε! Ο λογαριασμός σας είναι ανενεργός ή χρειάζεται να επιβεβαιώσετε το ηλεκτρονικού ταχυδρομείου/τον αριθμό τηλεφώνου σας.",
"ExternalLoginPasswordChangeRequired": "Δεν επιτρέπεται να συνδεθείτε! Ο κωδικός σας πρέπει να αλλάξει, αλλά αυτό δεν είναι δυνατό με εξωτερική σύνδεση. Επικοινωνήστε με τον διαχειριστή σας.",
"RegisteredButLoginIsNotAllowed": "Ο λογαριασμός σας δημιουργήθηκε, αλλά δεν επιτρέπεται να συνδεθείτε ακόμη!",
"SelfRegistrationDisabledMessage": "Η αυτοεγγραφή είναι απενεργοποιημένη για αυτήν την εφαρμογή. Επικοινωνήστε με τον διαχειριστή της εφαρμογής για να εγγραφείτε ως νέος χρήστης.",
"LocalLoginDisabledMessage": "Η τοπική σύνδεση είναι απενεργοποιημένη για αυτήν την εφαρμογή.",
"Login": "Σύνδεση",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/en-GB.json

@ -10,6 +10,8 @@
"UserLockedOutMessage": "The user account has been locked out due to invalid login attempts. Please wait a while and try again.",
"InvalidUserNameOrPassword": "Invalid username or password!",
"LoginIsNotAllowed": "You are not allowed to login! Your account is inactive or needs to confirm your email/phone number.",
"ExternalLoginPasswordChangeRequired": "You are not allowed to login! Your password must be changed, but this is not possible with an external login. Please contact your administrator.",
"RegisteredButLoginIsNotAllowed": "Your account has been created, but you are not allowed to login yet!",
"SelfRegistrationDisabledMessage": "Self-registration is disabled for this application. Please contact the application administrator to register a new user.",
"LocalLoginDisabledMessage": "Local login is disabled for this application.",
"Login": "Login",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/en.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "The user account has been locked out due to invalid login attempts. Please wait a while and try again.",
"InvalidUserNameOrPassword": "Invalid username or password!",
"LoginIsNotAllowed": "You are not allowed to log in! Your account is inactive or needs to confirm your email/phone number.",
"ExternalLoginPasswordChangeRequired": "You are not allowed to log in! Your password must be changed, but this is not possible with an external login. Please contact your administrator.",
"RegisteredButLoginIsNotAllowed": "Your account has been created, but you are not allowed to log in yet!",
"SelfRegistrationDisabledMessage": "Self-registration is disabled for this application. Please contact the application administrator to register a new user.",
"LocalLoginDisabledMessage": "Local login is disabled for this application.",
"Login": "Login",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/es-mx.json

@ -10,6 +10,8 @@
"UserLockedOutMessage": "La cuenta de usuario ha sido bloqueada debido a los intentos de inicio de sesión no válido. Por favor, espere un rato y vuelve a intentarlo.",
"InvalidUserNameOrPassword": "No válido nombre de usuario o la contraseña!",
"LoginIsNotAllowed": "¡No está permitido iniciar sesión! Su cuenta está inactiva o necesita confirmar su correo electrónico/número de teléfono.",
"ExternalLoginPasswordChangeRequired": "¡No está permitido iniciar sesión! Su contraseña debe cambiarse, pero esto no es posible con un inicio de sesión externo. Póngase en contacto con su administrador.",
"RegisteredButLoginIsNotAllowed": "¡Su cuenta ha sido creada, pero todavía no está permitido iniciar sesión!",
"SelfRegistrationDisabledMessage": "El autoregistro de usuario está deshabilitado para esta aplicación. Póngase en contacto con el administrador de la aplicación para registrar un nuevo usuario.",
"Login": "Iniciar sesión",
"Cancel": "Cancelar",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/es.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "La cuenta de usuario ha sido bloqueada debido a los intentos de inicio de sesión no válidos. Por favor, espere unos minutos y vuelve a intentarlo.",
"InvalidUserNameOrPassword": "El nombre de usuario o la contraseña no son válidos",
"LoginIsNotAllowed": "¡No está permitido iniciar sesión! Su cuenta está inactiva o necesita confirmar su correo electrónico/número de teléfono.",
"ExternalLoginPasswordChangeRequired": "¡No está permitido iniciar sesión! Su contraseña debe cambiarse, pero esto no es posible con un inicio de sesión externo. Póngase en contacto con su administrador.",
"RegisteredButLoginIsNotAllowed": "¡Su cuenta ha sido creada, pero todavía no está permitido iniciar sesión!",
"SelfRegistrationDisabledMessage": "El autoregistro de usuario está deshabilitado para esta aplicación. Póngase en contacto con el administrador de la aplicación para registrar un nuevo usuario.",
"LocalLoginDisabledMessage": "Inicio de sesión local ha sido deshabilitado para esta aplicación",
"Login": "Iniciar sesión",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fa.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "حساب کاربری به دلیل تلاش های نامعتبر ورود به سیستم قفل شده است. لطفاً کمی صبر کنید و دوباره امتحان کنید.",
"InvalidUserNameOrPassword": "نام کاربری یا گذرواژه نامعتبر است!",
"LoginIsNotAllowed": "شما اجازه ورود ندارید! باید شماره تلفن/ایمیل خود را تأیید کنید.",
"ExternalLoginPasswordChangeRequired": "شما اجازه ورود ندارید! گذرواژه شما باید تغییر کند، اما این کار با ورود خارجی امکان‌پذیر نیست. لطفاً با مدیر سیستم تماس بگیرید.",
"RegisteredButLoginIsNotAllowed": "حساب شما ایجاد شد، اما هنوز اجازه ورود ندارید!",
"SelfRegistrationDisabledMessage": "ثبت نام خودکار برای این برنامه غیرفعال است. لطفاً برای ثبت نام کاربر جدید با سرپرست برنامه تماس بگیرید.",
"LocalLoginDisabledMessage": "ورود محلی برای این برنامه غیرفعال است.",
"Login": "ورود کاربران",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fi.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Käyttäjätili on lukittu virheellisten kirjautumisyritysten vuoksi. Odota hetki ja yritä uudelleen.",
"InvalidUserNameOrPassword": "Väärä käyttäjänimi tai salasana!",
"LoginIsNotAllowed": "Et saa kirjautua sisään! Tilisi on passiivinen tai sinun on vahvistettava sähköpostiosoitteesi/puhelinnumerosi.",
"ExternalLoginPasswordChangeRequired": "Et saa kirjautua sisään! Salasanasi on vaihdettava, mutta se ei ole mahdollista ulkoisella kirjautumisella. Ota yhteyttä järjestelmänvalvojaan.",
"RegisteredButLoginIsNotAllowed": "Tilisi on luotu, mutta et saa vielä kirjautua sisään!",
"SelfRegistrationDisabledMessage": "Itserekisteröinti on poistettu käytöstä tälle sovellukselle. Rekisteröi uusi käyttäjä ottamalla yhteyttä sovelluksen järjestelmänvalvojaan.",
"LocalLoginDisabledMessage": "Paikallinen sisäänkirjautuminen on poistettu käytöstä tälle sovellukselle.",
"Login": "Kirjaudu sisään",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fr.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Le compte utilisateur a été verrouillé en raison de tentatives de connexion non valides. Veuillez patienter un instant et réessayer.",
"InvalidUserNameOrPassword": "Nom d'utilisateur ou mot de passe invalide!",
"LoginIsNotAllowed": "Vous n'êtes pas autorisé à vous connecter ! Votre compte est inactif ou doit confirmer votre e-mail/numéro de téléphone.",
"ExternalLoginPasswordChangeRequired": "Vous n'êtes pas autorisé à vous connecter ! Votre mot de passe doit être modifié, mais cela n'est pas possible avec une connexion externe. Veuillez contacter votre administrateur.",
"RegisteredButLoginIsNotAllowed": "Votre compte a été créé, mais vous n'êtes pas encore autorisé à vous connecter !",
"SelfRegistrationDisabledMessage": "L'auto-inscription est désactivée pour cette application. Veuillez contacter l'administrateur de l'application pour enregistrer un nouvel utilisateur.",
"LocalLoginDisabledMessage": "La connexion locale est désactivée pour cette application.",
"Login": "Connectez-vous",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hi.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "अमान्य लॉगिन प्रयासों के कारण उपयोगकर्ता खाता बंद कर दिया गया है। कृपया थोड़ी देर प्रतीक्षा करें और पुन: प्रयास करें।",
"InvalidUserNameOrPassword": "अमान्य उपयोगकर्ता नाम या पासवर्ड!",
"LoginIsNotAllowed": "आपको लॉगिन करने की अनुमति नहीं है! आपका खाता निष्क्रिय है या आपके ईमेल/फ़ोन नंबर की पुष्टि करने की आवश्यकता है।",
"ExternalLoginPasswordChangeRequired": "आपको लॉगिन करने की अनुमति नहीं है! आपका पासवर्ड बदला जाना आवश्यक है, लेकिन बाहरी लॉगिन के साथ यह संभव नहीं है। कृपया अपने व्यवस्थापक से संपर्क करें।",
"RegisteredButLoginIsNotAllowed": "आपका खाता बना दिया गया है, लेकिन आपको अभी लॉगिन करने की अनुमति नहीं है!",
"SelfRegistrationDisabledMessage": "इस आवेदन के लिए स्व-पंजीकरण अक्षम है। नया उपयोगकर्ता पंजीकृत करने के लिए कृपया एप्लिकेशन व्यवस्थापक से संपर्क करें।",
"LocalLoginDisabledMessage": "इस एप्लिकेशन के लिए स्थानीय लॉगिन अक्षम है।",
"Login": "लॉग इन करें",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hr.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Korisnički račun je zaključan zbog nevažećih pokušaja prijave. Pričekajte malo i pokušajte ponovo.",
"InvalidUserNameOrPassword": "Neispravno korisničko ime ili lozinka!",
"LoginIsNotAllowed": "Nemate dopuštenje za prijavu! Vaš račun nije aktivan ili treba potvrditi vašu e-poštu/broj telefona.",
"ExternalLoginPasswordChangeRequired": "Nemate dopuštenje za prijavu! Vaša lozinka mora se promijeniti, ali to nije moguće s vanjskom prijavom. Obratite se svom administratoru.",
"RegisteredButLoginIsNotAllowed": "Vaš račun je kreiran, ali još nemate dopuštenje za prijavu!",
"SelfRegistrationDisabledMessage": "Samoregistracija je onemogućena za ovu aplikaciju. Molimo kontaktirajte administratora aplikacije za registraciju novog korisnika.",
"LocalLoginDisabledMessage": "Lokalna prijava je onemogućena za ovu aplikaciju.",
"Login": "Prijavi se",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hu.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "A felhasználói fiókot érvénytelen bejelentkezési kísérletek miatt zároltuk. Kérjük, várjon egy kicsit, és próbálja újra.",
"InvalidUserNameOrPassword": "Érvénytelen felhasználónév vagy jelszó!",
"LoginIsNotAllowed": "A bejelentkezés nem engedélyezett! Fiókja inaktív, vagy meg kell erősítenie e -mail címét/telefonszámát.",
"ExternalLoginPasswordChangeRequired": "A bejelentkezés nem engedélyezett! A jelszavát meg kell változtatni, de ez külső bejelentkezéssel nem lehetséges. Kérjük, forduljon a rendszergazdához.",
"RegisteredButLoginIsNotAllowed": "A fiókja létrejött, de a bejelentkezés még nem engedélyezett!",
"SelfRegistrationDisabledMessage": "Ennél az alkalmazásnál az önregisztráció le van tiltva. Új felhasználó regisztrálásához vegye fel a kapcsolatot az alkalmazás rendszergazdájával.",
"LocalLoginDisabledMessage": "A helyi bejelentkezés le van tiltva ennél az alkalmazásnál.",
"Login": "Bejelntkezés",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/is.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Notandareikningnum hefur verið lokað vegna ógildra innskráningartilrauna. Bíddu aðeins og reyndu aftur.",
"InvalidUserNameOrPassword": "Ógilt notendanafn eða lykilorð!",
"LoginIsNotAllowed": "Þú hefur ekki leyfi til að skrá þig inn! Þú þarft að staðfesta netfangið þitt/símanúmer.",
"ExternalLoginPasswordChangeRequired": "Þú hefur ekki leyfi til að skrá þig inn! Breyta þarf lykilorðinu þínu, en það er ekki hægt með ytri innskráningu. Vinsamlegast hafðu samband við kerfisstjóra.",
"RegisteredButLoginIsNotAllowed": "Aðgangurinn þinn hefur verið stofnaður, en þú hefur ekki leyfi til að skrá þig inn ennþá!",
"SelfRegistrationDisabledMessage": "Sjálfsskráning er óvirk fyrir þetta forrit. Vinsamlegast hafðu samband við umsjónarmann hugbúnaðarins til að skrá nýjan notanda.",
"LocalLoginDisabledMessage": "Staðbundin innskráning er óvirk fyrir þetta forrit.",
"Login": "Skrá inn",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/it.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "L'account utente è stato bloccato a causa di troppi tentativi di accesso non validi. Attendi qualche istante e riprova.",
"InvalidUserNameOrPassword": "Username o password non validi!",
"LoginIsNotAllowed": "Non sei autorizzato ad accedere! Il tuo account non è attivo o devi confermare la tua e-mail/numero di telefono.",
"ExternalLoginPasswordChangeRequired": "Non sei autorizzato ad accedere! La tua password deve essere modificata, ma ciò non è possibile con un accesso esterno. Contatta il tuo amministratore.",
"RegisteredButLoginIsNotAllowed": "Il tuo account è stato creato, ma non sei ancora autorizzato ad accedere!",
"SelfRegistrationDisabledMessage": "L'auto-registrazione è disabilitata per questa applicazione. Contatta l'amministratore dell'applicazione per richiedere la registrazione.",
"LocalLoginDisabledMessage": "L'accesso locale è disabilitato per questa applicazione.",
"Login": "Accedi",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/nl.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Het gebruikersaccount is geblokkeerd vanwege ongeldige inlogpogingen. Wacht even en probeer het opnieuw.",
"InvalidUserNameOrPassword": "Ongeldige gebruikersnaam of wachtwoord!",
"LoginIsNotAllowed": "U mag niet inloggen! Uw account is inactief of moet uw e-mailadres/telefoonnummer bevestigen.",
"ExternalLoginPasswordChangeRequired": "U mag niet inloggen! Uw wachtwoord moet worden gewijzigd, maar dit is niet mogelijk met een externe login. Neem contact op met uw beheerder.",
"RegisteredButLoginIsNotAllowed": "Uw account is aangemaakt, maar u mag nog niet inloggen!",
"SelfRegistrationDisabledMessage": "Zelfregistratie is uitgeschakeld voor deze applicatie. Neem contact op met de applicatiebeheerder om een nieuwe gebruiker te registreren.",
"LocalLoginDisabledMessage": "Lokale aanmelding is uitgeschakeld voor deze applicatie.",
"Login": "Log in",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/pl-PL.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Konto użytkownika zostało zablokowane po nieudanych próbach zalogowania. Odczekaj chwilę i spróbuj ponownie.",
"InvalidUserNameOrPassword": "Niepoprawna nazwa użytkownika lub hasło!",
"LoginIsNotAllowed": "Nie możesz się zalogować! Twoje konto jest nieaktywne lub wymaga potwierdzenia adresu e-mail/numeru telefonu.",
"ExternalLoginPasswordChangeRequired": "Nie możesz się zalogować! Twoje hasło musi zostać zmienione, ale nie jest to możliwe przy logowaniu zewnętrznym. Skontaktuj się z administratorem.",
"RegisteredButLoginIsNotAllowed": "Twoje konto zostało utworzone, ale nie możesz się jeszcze zalogować!",
"SelfRegistrationDisabledMessage": "Rejestracja użytkowników jest wyłączona dla tej aplikacji. Skontaktuj się z administratorem aplikacji w celu rejestracji nowego użytkownika.",
"LocalLoginDisabledMessage": "Logowanie lokalne jest wyłączone dla tej aplikacji.",
"Login": "Zaloguj",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/pt-BR.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Esta conta de usuário está bloqueada devido a muitas tentativas de acesso. Por favor, espere alguns instantes e tente novamente.",
"InvalidUserNameOrPassword": "Usuário ou senha estão incorretos!",
"LoginIsNotAllowed": "Você não tem permissão para fazer o login! Sua conta está inativa ou precisa confirmar seu e-mail/número de telefone.",
"ExternalLoginPasswordChangeRequired": "Você não tem permissão para fazer o login! Sua senha precisa ser alterada, mas isso não é possível com um login externo. Entre em contato com o administrador.",
"RegisteredButLoginIsNotAllowed": "Sua conta foi criada, mas você ainda não tem permissão para fazer o login!",
"SelfRegistrationDisabledMessage": "Não é permitido que você crie uma nova conta neste site. Contate um administrador para que ele crie uma conta para você.",
"LocalLoginDisabledMessage": "O login local está desativado para este aplicativo.",
"Login": "Entrar",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ro-RO.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Contul a fost blocat din cauza incercărilor eşuate de autentificare. Vă rugăm să aşteptaţi şi să încercaţi din nou.",
"InvalidUserNameOrPassword": "Nume de utilizator sau parolă invalide!",
"LoginIsNotAllowed": "Nu ai voie să te autentifici! Contul dvs. este inactiv sau trebuie să vă confirme numărul de e-mail/telefon.",
"ExternalLoginPasswordChangeRequired": "Nu ai voie să te autentifici! Parola dvs. trebuie schimbată, dar acest lucru nu este posibil cu o autentificare externă. Vă rugăm să contactați administratorul.",
"RegisteredButLoginIsNotAllowed": "Contul dvs. a fost creat, dar încă nu aveți voie să vă autentificați!",
"SelfRegistrationDisabledMessage": "Înregistrarea personală este dezactivată pentru această aplicaţie. Vă rugăm să contactaţi administratorul aplicaţiei pentru a înregistra un nou utilizator.",
"LocalLoginDisabledMessage": "Autentificarea locală este dezactivată pentru această aplicaţie.",
"Login": "Autentificare",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ru.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Пользователь заблокирован из-за большого количества попыток входа. Пожалуйста, попробуйте позднее.",
"InvalidUserNameOrPassword": "Неправильные имя пользователя и/или пароль!",
"LoginIsNotAllowed": "Вам не разрешено входить в систему! Ваша учетная запись неактивна или вам необходимо подтвердить адрес электронной почты/номер телефона.",
"ExternalLoginPasswordChangeRequired": "Вам не разрешено входить в систему! Ваш пароль необходимо изменить, но это невозможно при внешнем входе. Обратитесь к администратору.",
"RegisteredButLoginIsNotAllowed": "Ваша учетная запись создана, но вам пока не разрешено входить в систему!",
"SelfRegistrationDisabledMessage": "Самостоятельная регистрация не предусмотрена. Пожалуйста, свяжитесь с администраром для получения доступа.",
"LocalLoginDisabledMessage": "Локальный вход отключен.",
"Login": "Войти",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sk.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Používateľské konto bolo uzamknuté z dôvodu neplatných pokusov o prihlásenie. Chvíľu počkajte a skúste to znova.",
"InvalidUserNameOrPassword": "Neplatné používateľské meno alebo heslo!",
"LoginIsNotAllowed": "Nemáte povolenie sa prihlásiť! Váš účet je neaktívny alebo potrebuje potvrdiť váš e -mail/telefónne číslo.",
"ExternalLoginPasswordChangeRequired": "Nemáte povolenie sa prihlásiť! Vaše heslo musí byť zmenené, čo však pri externom prihlásení nie je možné. Kontaktujte prosím svojho správcu.",
"RegisteredButLoginIsNotAllowed": "Váš účet bol vytvorený, ale zatiaľ nemáte povolenie sa prihlásiť!",
"SelfRegistrationDisabledMessage": "Samostatná registrácia je pre túto aplikáciu vypnutá. Ak chcete zaregistrovať nového používateľa, obráťte sa na správcu aplikácie.",
"LocalLoginDisabledMessage": "Lokálne prihlásenie je pre túto aplikáciu zakázané.",
"Login": "Prihlásiť",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sl.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Uporabniški račun je bil zaklenjen zaradi neveljavnih poskusov prijave. Počakajte nekaj časa in poskusite znova.",
"InvalidUserNameOrPassword": "Napačno uporabniško ime ali geslo!",
"LoginIsNotAllowed": "Ne smete se prijaviti! Vaš račun je neaktiven ali mora potrditi vaš e -poštni naslov/telefonsko številko.",
"ExternalLoginPasswordChangeRequired": "Ne smete se prijaviti! Vaše geslo je treba spremeniti, vendar to z zunanjo prijavo ni mogoče. Obrnite se na skrbnika.",
"RegisteredButLoginIsNotAllowed": "Vaš račun je bil ustvarjen, vendar se še ne smete prijaviti!",
"SelfRegistrationDisabledMessage": "Možnost lastne registracije uporabnika je onemogočena za to aplikacijo. Kontaktirajte skrbnika aplikacije, da registrirate novega uporabnika.",
"LocalLoginDisabledMessage": "Lokalna prijava za to aplikacijo je onemogočena.",
"Login": "Prijava",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sv.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Användarkontot har låsts på grund av ogiltiga inloggningsförsök. Vänligen vänta ett tag och försök igen.",
"InvalidUserNameOrPassword": "Ogiltigt användarnamn eller lösenord!",
"LoginIsNotAllowed": "Du kan inte logga in! Ditt konto är inaktivt eller så behöver du bekräfta din e-postadress eller ditt telefonnummer.",
"ExternalLoginPasswordChangeRequired": "Du kan inte logga in! Ditt lösenord måste ändras, men det är inte möjligt med en extern inloggning. Kontakta din administratör.",
"RegisteredButLoginIsNotAllowed": "Ditt konto har skapats, men du kan inte logga in ännu!",
"SelfRegistrationDisabledMessage": "Självregistrering är inaktiverat för denna applikation. Vänligen kontakta applikationsadministratören för att registrera en ny användare.",
"LocalLoginDisabledMessage": "Lokal inloggning är inaktiverad för denna applikation.",
"Login": "Logga in",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/tr.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Kullanıcı hesabı hatalı giriş denemeleri nedeniyle kilitlenmiştir. Lütfen bir süre bekleyip tekrar deneyin.",
"InvalidUserNameOrPassword": "Kullanıcı adı ya da şifre geçersiz!",
"LoginIsNotAllowed": "Giriş yapmanıza izin verilmiyor! Hesabınız etkin değil veya e-postanızı/telefon numaranızı onaylamanız gerekiyor.",
"ExternalLoginPasswordChangeRequired": "Giriş yapmanıza izin verilmiyor! Şifrenizin değiştirilmesi gerekiyor, ancak bu harici bir girişle mümkün değil. Lütfen yöneticinizle iletişime geçin.",
"RegisteredButLoginIsNotAllowed": "Hesabınız oluşturuldu, ancak henüz giriş yapmanıza izin verilmiyor!",
"SelfRegistrationDisabledMessage": "Bu uygulama için kullanıcıların kendi kendilerine kaydolmaları engellenmiştir. Yeni bir kullanıcı kaydetmek için lütfen uygulama yöneticisi ile iletişime geçin.",
"LocalLoginDisabledMessage": "Bu uygulama için local login devre dışı bırakılmıştır.",
"Login": "Giriş yap",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/vi.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "Tài khoản người dùng đã bị khóa do các nỗ lực đăng nhập không hợp lệ. Xin vui lòng chờ một lúc và thử lại.",
"InvalidUserNameOrPassword": "Sai tên tài khoản hoặc mật khẩu!",
"LoginIsNotAllowed": "Bạn không được phép đăng nhập! Tài khoản của bạn không hoạt động hoặc cần xác nhận email/số điện thoại của bạn.",
"ExternalLoginPasswordChangeRequired": "Bạn không được phép đăng nhập! Mật khẩu của bạn phải được thay đổi, nhưng không thể thực hiện việc này với đăng nhập bên ngoài. Vui lòng liên hệ với quản trị viên của bạn.",
"RegisteredButLoginIsNotAllowed": "Tài khoản của bạn đã được tạo, nhưng bạn chưa được phép đăng nhập!",
"SelfRegistrationDisabledMessage": "Tự đăng ký người dùng bị vô hiệu hóa cho ứng dụng này. Liên hệ với quản trị viên ứng dụng để đăng ký người dùng mới.",
"LocalLoginDisabledMessage": "Đăng nhập cục bộ bị vô hiệu hóa cho ứng dụng này.",
"Login": "Đăng nhập",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/zh-Hans.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "由于尝试登录无效,用户账户已被锁定。请稍候再试。",
"InvalidUserNameOrPassword": "用户名或密码无效!",
"LoginIsNotAllowed": "您不能登录!您的帐户未激活或需要确认您的电子邮件/电话号码。",
"ExternalLoginPasswordChangeRequired": "您不能登录!您的密码必须更改,但无法通过外部登录完成。请联系管理员。",
"RegisteredButLoginIsNotAllowed": "您的帐户已创建,但您暂时不能登录!",
"SelfRegistrationDisabledMessage": "应用程序未开放注册。请联系应用程序管理员注册新用户。",
"LocalLoginDisabledMessage": "应用程序禁用本地登录。",
"Login": "登录",

2
modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/zh-Hant.json

@ -11,6 +11,8 @@
"UserLockedOutMessage": "登入失敗,使用者帳號已被鎖定.請稍後再試.",
"InvalidUserNameOrPassword": "使用者名稱或密碼錯誤!",
"LoginIsNotAllowed": "無法登入!你的帳號未啟用或者需要驗證電子郵件地址/手機號碼.",
"ExternalLoginPasswordChangeRequired": "無法登入!你的密碼必須變更,但無法透過外部登入完成.請聯絡管理員.",
"RegisteredButLoginIsNotAllowed": "帳號已建立,但你暫時無法登入!",
"SelfRegistrationDisabledMessage": "應用程式未開放註冊,請聯絡管理員以加入新使用者.",
"LocalLoginDisabledMessage": "應用程式未開放本地帳戶登入.",
"Login": "登入",

22
modules/account/src/Volo.Abp.Account.Web.IdentityServer/Pages/Account/IdentityServerSupportedLoginModel.cs

@ -157,16 +157,32 @@ public class IdentityServerSupportedLoginModel : LoginModel
return Page();
}
if (result is AbpSignInResult { IsExternalLoginPasswordChangeRequired: true })
{
Alerts.Warning(L["ExternalLoginPasswordChangeRequired"]);
return Page();
}
if (result.IsNotAllowed)
{
var notAllowedUser = await UserManager.FindByNameAsync(LoginInput.UserNameOrEmailAddress) ??
await UserManager.FindByEmailAsync(LoginInput.UserNameOrEmailAddress);
var notAllowedUser = await UserManager.FindSharedUserByNameAsync(LoginInput.UserNameOrEmailAddress) ??
await UserManager.FindSharedUserByEmailAsync(LoginInput.UserNameOrEmailAddress);
if (notAllowedUser != null)
{
using (CurrentTenant.Change(notAllowedUser.TenantId))
{
await IdentityOptions.SetAsync();
if ((notAllowedUser.ShouldChangePasswordOnNextLogin ||
if (notAllowedUser.IsActive && await UserManager.IsLockedOutAsync(notAllowedUser))
{
Alerts.Warning(L["UserLockedOutMessage"]);
return Page();
}
// The password is only checked if the password change is the reason of the rejection.
// The user may be authenticated by an external login provider otherwise.
if (notAllowedUser.IsActive &&
await SignInManager.CanSignInAsync(notAllowedUser) &&
(notAllowedUser.ShouldChangePasswordOnNextLogin ||
await UserManager.ShouldPeriodicallyChangePasswordAsync(notAllowedUser)) &&
!await UserManager.CheckPasswordAsync(notAllowedUser, LoginInput.Password))
{

32
modules/account/src/Volo.Abp.Account.Web/Pages/Account/AccountPageModel.cs

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using Volo.Abp.Account.Localization;
@ -8,6 +9,7 @@ using Volo.Abp.AspNetCore.ExceptionHandling;
using Volo.Abp.AspNetCore.Mvc.UI.RazorPages;
using Volo.Abp.ExceptionHandling;
using Volo.Abp.Identity;
using Volo.Abp.Identity.AspNetCore;
using IdentityUser = Volo.Abp.Identity.IdentityUser;
namespace Volo.Abp.Account.Web.Pages.Account;
@ -35,6 +37,36 @@ public abstract class AccountPageModel : AbpPageModel
}
}
/// <summary>
/// Checks the user before signing in without asking for the credentials of the user.
/// </summary>
/// <returns>Null if the user is allowed to sign in, otherwise the result why the user is denied.</returns>
protected virtual async Task<SignInResult> CheckUserSignInAsync(IdentityUser user)
{
// The IdentityOptions property is hidden by the login page.
await LazyServiceProvider.LazyGetRequiredService<IOptions<IdentityOptions>>().SetAsync();
if (SignInManager is AbpSignInManager abpSignInManager)
{
return await abpSignInManager.CallPreSignInCheckAsync(user);
}
// The sign-in manager of the application may not be derived from AbpSignInManager.
if (!user.IsActive ||
user.ShouldChangePasswordOnNextLogin ||
await UserManager.ShouldPeriodicallyChangePasswordAsync(user) ||
!await SignInManager.CanSignInAsync(user))
{
return SignInResult.NotAllowed;
}
if (UserManager.SupportsUserLockout && await UserManager.IsLockedOutAsync(user))
{
return SignInResult.LockedOut;
}
return null;
}
protected virtual void CheckIdentityErrors(IdentityResult identityResult)
{
if (!identityResult.Succeeded)

35
modules/account/src/Volo.Abp.Account.Web/Pages/Account/Login.cshtml.cs

@ -128,16 +128,32 @@ public class LoginModel : AccountPageModel
return Page();
}
if (result is AbpSignInResult { IsExternalLoginPasswordChangeRequired: true })
{
Alerts.Warning(L["ExternalLoginPasswordChangeRequired"]);
return Page();
}
if (result.IsNotAllowed)
{
var notAllowedUser = await UserManager.FindByNameAsync(LoginInput.UserNameOrEmailAddress) ??
await UserManager.FindByEmailAsync(LoginInput.UserNameOrEmailAddress);
var notAllowedUser = await UserManager.FindSharedUserByNameAsync(LoginInput.UserNameOrEmailAddress) ??
await UserManager.FindSharedUserByEmailAsync(LoginInput.UserNameOrEmailAddress);
if (notAllowedUser != null)
{
using (CurrentTenant.Change(notAllowedUser.TenantId))
{
await IdentityOptions.SetAsync();
if ((notAllowedUser.ShouldChangePasswordOnNextLogin ||
if (notAllowedUser.IsActive && await UserManager.IsLockedOutAsync(notAllowedUser))
{
Alerts.Warning(L["UserLockedOutMessage"]);
return Page();
}
// The password is only checked if the password change is the reason of the rejection.
// The user may be authenticated by an external login provider otherwise.
if (notAllowedUser.IsActive &&
await SignInManager.CanSignInAsync(notAllowedUser) &&
(notAllowedUser.ShouldChangePasswordOnNextLogin ||
await UserManager.ShouldPeriodicallyChangePasswordAsync(notAllowedUser)) &&
!await UserManager.CheckPasswordAsync(notAllowedUser, LoginInput.Password))
{
@ -296,6 +312,19 @@ public class LoginModel : AccountPageModel
});
}
var signInCheckResult = await CheckUserSignInAsync(user);
if (signInCheckResult != null)
{
if (signInCheckResult.IsLockedOut)
{
Logger.LogWarning($"External login callback error: user is locked out!");
throw new UserFriendlyException("Cannot proceed because user is locked out!");
}
Logger.LogWarning($"External login callback error: user is not allowed!");
throw new UserFriendlyException("Cannot proceed because user is not allowed!");
}
if (await UserManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey) == null)
{
CheckIdentityErrors(await UserManager.AddLoginAsync(user, loginInfo));

28
modules/account/src/Volo.Abp.Account.Web/Pages/Account/Register.cshtml.cs

@ -43,6 +43,8 @@ public class RegisterModel : AccountPageModel
public bool IsExternalLoginOnly => EnableLocalRegister == false && ExternalProviders?.Count() == 1;
public string ExternalLoginScheme => IsExternalLoginOnly ? ExternalProviders?.SingleOrDefault()?.AuthenticationScheme : null;
protected bool IsRegisteredUserNotAllowedToSignIn { get; set; }
protected IAuthenticationSchemeProvider SchemeProvider { get; }
protected AbpAccountOptions AccountOptions { get; }
@ -137,6 +139,12 @@ public class RegisterModel : AccountPageModel
await RegisterLocalUserAsync();
}
if (IsRegisteredUserNotAllowedToSignIn)
{
Alerts.Warning(L["RegisteredButLoginIsNotAllowed"]);
return Page();
}
return await RedirectSafelyAsync(ReturnUrl, ReturnUrlHash);
}
catch (BusinessException e)
@ -161,10 +169,7 @@ public class RegisterModel : AccountPageModel
);
var user = await UserManager.GetByIdAsync(userDto.Id);
await SignInManager.SignInAsync(user, isPersistent: true);
// Clear the dynamic claims cache.
await IdentityDynamicClaimsPrincipalContributorCache.ClearAsync(user.Id, user.TenantId);
await SignInRegisteredUserAsync(user);
}
protected virtual async Task RegisterExternalUserAsync(ExternalLoginInfo externalLoginInfo, string userName, string emailAddress)
@ -190,7 +195,20 @@ public class RegisterModel : AccountPageModel
))).CheckErrors();
}
await SignInManager.SignInAsync(user, isPersistent: true, ExternalLoginAuthSchema);
await SignInRegisteredUserAsync(user, ExternalLoginAuthSchema);
}
protected virtual async Task SignInRegisteredUserAsync(IdentityUser user, string authenticationMethod = null)
{
if (await CheckUserSignInAsync(user) != null)
{
// The user is registered but has to sign in later, for example after confirming the email.
Logger.LogWarning($"The registered user is not allowed to sign in! (username: \"{user.UserName}\", id:\"{user.Id}\")");
IsRegisteredUserNotAllowedToSignIn = true;
return;
}
await SignInManager.SignInAsync(user, isPersistent: true, authenticationMethod);
// Clear the dynamic claims cache.
await IdentityDynamicClaimsPrincipalContributorCache.ClearAsync(user.Id, user.TenantId);

4
modules/account/test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.abppkg

@ -0,0 +1,4 @@
{
"role": "lib.test",
"projectId": "e7ac0de5-6c69-4e07-8d24-6082c3dd9c1b"
}

23
modules/account/test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.csproj

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace />
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="Shouldly" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.extensibility.execution" />
<PackageReference Include="xunit.runner.visualstudio" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Volo.Abp.Account.Web\Volo.Abp.Account.Web.csproj" />
<ProjectReference Include="..\..\src\Volo.Abp.Account.Web.IdentityServer\Volo.Abp.Account.Web.IdentityServer.csproj" />
<ProjectReference Include="..\Volo.Abp.Account.Application.Tests\Volo.Abp.Account.Application.Tests.csproj" />
</ItemGroup>
</Project>

40
modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebIdentityServerTestModule.cs

@ -0,0 +1,40 @@
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using NSubstitute;
using Volo.Abp.IdentityServer;
using Volo.Abp.Modularity;
namespace Volo.Abp.Account.Web;
[DependsOn(
typeof(AbpAccountWebTestModule),
typeof(AbpAccountWebIdentityServerModule)
)]
public class AbpAccountWebIdentityServerTestModule : AbpModule
{
public override void PreConfigureServices(ServiceConfigurationContext context)
{
// The other tests of the assembly run in the same process, so the static claim types are not changed.
PreConfigure<AbpIdentityServerBuilderOptions>(options =>
{
options.UpdateAbpClaimTypes = false;
options.UpdateJwtSecurityTokenHandlerDefaultInboundClaimTypeMap = false;
options.AddDeveloperSigningCredential = false;
});
}
public override void ConfigureServices(ServiceConfigurationContext context)
{
// There is no authorize request in the tests.
var interaction = Substitute.For<IIdentityServerInteractionService>();
interaction.GetAuthorizationContextAsync(Arg.Any<string>()).Returns((AuthorizationRequest)null);
context.Services.Replace(ServiceDescriptor.Singleton(interaction));
// IdentityServer decorates the authentication service, the substitute of the tests is used instead.
context.Services.RemoveAll<IAuthenticationService>();
context.Services.AddSingleton(Substitute.For<IAuthenticationService>());
}
}

181
modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebTestBase.cs

@ -0,0 +1,181 @@
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
using Volo.Abp.Account.Localization;
using Volo.Abp.Account.Web.Pages.Account;
using Volo.Abp.AspNetCore.Mvc.UI.Alerts;
using Volo.Abp.Identity;
using Volo.Abp.Identity.Settings;
using Volo.Abp.Modularity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Settings;
using Volo.Abp.Testing;
using Volo.Abp.Uow;
using IdentityRole = Volo.Abp.Identity.IdentityRole;
using IdentityUser = Volo.Abp.Identity.IdentityUser;
namespace Volo.Abp.Account.Web;
public enum RestrictedUserState
{
Inactive,
LockedOut,
RequiresConfirmation,
MustChangePassword,
PasswordExpired
}
public abstract class AbpAccountWebTestBase : AbpAccountWebTestBase<AbpAccountWebTestModule>
{
}
public abstract class AbpAccountWebTestBase<TStartupModule> : AbpIntegratedTest<TStartupModule>
where TStartupModule : IAbpModule
{
protected const string Password = "1q2w3E*";
protected const string ExternalLoginProvider = "TestProvider";
protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options)
{
options.UseAutofac();
}
// The sign-in manager of an application, replaced like it is documented for ASP.NET Core Identity.
protected static void ReplaceSignInManager(IServiceCollection services)
{
new IdentityBuilder(typeof(IdentityUser), typeof(IdentityRole), services).AddSignInManager<TestSignInManager>();
}
protected void SetSetting(string name, string value)
{
((TestSettingStore)GetRequiredService<ISettingStore>()).GlobalValues[name] = value;
}
protected async Task<IdentityUser> CreateUserAsync(Guid? tenantId = null, params RestrictedUserState[] states)
{
if (states.Contains(RestrictedUserState.RequiresConfirmation))
{
SetSetting(IdentitySettingNames.SignIn.RequireConfirmedEmail, "true");
}
if (states.Contains(RestrictedUserState.PasswordExpired))
{
SetSetting(IdentitySettingNames.Password.ForceUsersToPeriodicallyChangePassword, "true");
SetSetting(IdentitySettingNames.Password.PasswordChangePeriodDays, "1");
}
using (GetRequiredService<ICurrentTenant>().Change(tenantId))
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin())
{
var userManager = GetRequiredService<IdentityUserManager>();
var userName = "user-" + Guid.NewGuid().ToString("N");
var user = new IdentityUser(Guid.NewGuid(), userName, userName + "@abp.io", tenantId);
user.SetEmailConfirmed(!states.Contains(RestrictedUserState.RequiresConfirmation));
(await userManager.CreateAsync(user, Password)).CheckErrors();
foreach (var state in states)
{
switch (state)
{
case RestrictedUserState.Inactive:
user.SetIsActive(false);
break;
case RestrictedUserState.LockedOut:
(await userManager.SetLockoutEnabledAsync(user, true)).CheckErrors();
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors();
break;
case RestrictedUserState.MustChangePassword:
user.SetShouldChangePasswordOnNextLogin(true);
break;
case RestrictedUserState.PasswordExpired:
user.SetLastPasswordChangeTime(DateTimeOffset.UtcNow.AddDays(-30));
break;
}
}
(await userManager.UpdateAsync(user)).CheckErrors();
await uow.CompleteAsync();
return user;
}
}
/// <summary>
/// Creates the page like it is created for a request.
/// </summary>
/// <param name="serviceProvider">The services of the request</param>
/// <param name="externalLoginPrincipal">The principal of the external login, if the request is a callback of it</param>
protected TPage CreatePage<TPage>(IServiceProvider serviceProvider, ClaimsPrincipal externalLoginPrincipal = null)
where TPage : AccountPageModel
{
var httpContext = new DefaultHttpContext { RequestServices = serviceProvider };
serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext = httpContext;
var authenticationService = serviceProvider.GetRequiredService<IAuthenticationService>();
authenticationService.AuthenticateAsync(Arg.Any<HttpContext>(), Arg.Any<string>()).Returns(AuthenticateResult.NoResult());
if (externalLoginPrincipal != null)
{
var properties = new AuthenticationProperties();
properties.Items["LoginProvider"] = ExternalLoginProvider;
authenticationService.AuthenticateAsync(Arg.Any<HttpContext>(), IdentityConstants.ExternalScheme).Returns(
AuthenticateResult.Success(new AuthenticationTicket(externalLoginPrincipal, properties, IdentityConstants.ExternalScheme)));
}
var page = serviceProvider.GetRequiredService<TPage>();
var modelState = new ModelStateDictionary();
var actionContext = new ActionContext(httpContext, new RouteData(), new PageActionDescriptor(), modelState);
page.PageContext = new PageContext(actionContext)
{
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), modelState)
};
page.TempData = new TempDataDictionary(httpContext, Substitute.For<ITempDataProvider>());
page.Url = new UrlHelper(actionContext);
return page;
}
protected bool IsSignedIn()
{
return GetRequiredService<IAuthenticationService>().ReceivedCalls().Any(call =>
call.GetMethodInfo().Name == nameof(IAuthenticationService.SignInAsync) &&
(string)call.GetArguments()[1] == IdentityConstants.ApplicationScheme);
}
protected static string[] GetAlerts(IServiceProvider serviceProvider)
{
return serviceProvider.GetRequiredService<IAlertManager>().Alerts.Select(x => x.Text).ToArray();
}
protected string L(string name)
{
return GetRequiredService<IStringLocalizer<AccountResource>>()[name];
}
}
public class TestSignInManager : SignInManager<IdentityUser>
{
public TestSignInManager(
UserManager<IdentityUser> userManager,
IHttpContextAccessor contextAccessor,
IUserClaimsPrincipalFactory<IdentityUser> claimsFactory,
IOptions<IdentityOptions> optionsAccessor,
ILogger<SignInManager<IdentityUser>> logger,
IAuthenticationSchemeProvider schemes,
IUserConfirmation<IdentityUser> confirmation)
: base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes, confirmation)
{
}
}

46
modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebTestModule.cs

@ -0,0 +1,46 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using NSubstitute;
using Volo.Abp.Modularity;
using Volo.Abp.Settings;
namespace Volo.Abp.Account.Web;
[DependsOn(
typeof(AbpAccountApplicationTestModule),
typeof(AbpAccountWebModule)
)]
public class AbpAccountWebTestModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddSingleton(Substitute.For<IWebHostEnvironment>());
context.Services.Replace(ServiceDescriptor.Singleton(Substitute.For<IAuthenticationService>()));
context.Services.Replace(ServiceDescriptor.Singleton<ISettingStore, TestSettingStore>());
}
}
public class TestSettingStore : ISettingStore
{
public Dictionary<string, string> GlobalValues { get; } = new();
public Task<string> GetOrNullAsync(string name, string providerName, string providerKey)
{
return Task.FromResult(GetOrNull(name, providerName));
}
public Task<List<SettingValue>> GetAllAsync(string[] names, string providerName, string providerKey)
{
return Task.FromResult(names.Select(name => new SettingValue(name, GetOrNull(name, providerName))).ToList());
}
private string GetOrNull(string name, string providerName)
{
return providerName == GlobalSettingValueProvider.ProviderName ? GlobalValues.GetOrDefault(name) : null;
}
}

81
modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/AccountPageModel_SignInCheck_Tests.cs

@ -0,0 +1,81 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp.Identity.AspNetCore;
using Volo.Abp.Uow;
using Xunit;
using IdentityUser = Volo.Abp.Identity.IdentityUser;
namespace Volo.Abp.Account.Web.Pages.Account;
// Some pages sign in a user without asking for the credentials of the user, for example after the registration.
public abstract class AccountPageModel_SignInCheck_TestBase : AbpAccountWebTestBase
{
[Fact]
public async Task Should_Allow_User()
{
(await CheckUserSignInAsync()).ShouldBeNull();
}
[Theory]
[InlineData(RestrictedUserState.Inactive)]
[InlineData(RestrictedUserState.RequiresConfirmation)]
[InlineData(RestrictedUserState.MustChangePassword)]
[InlineData(RestrictedUserState.PasswordExpired)]
public async Task Should_Not_Allow_Restricted_User(RestrictedUserState state)
{
(await CheckUserSignInAsync(state)).ShouldBe(SignInResult.NotAllowed);
}
[Fact]
public async Task Should_Not_Allow_Locked_Out_User()
{
(await CheckUserSignInAsync(RestrictedUserState.LockedOut)).ShouldBe(SignInResult.LockedOut);
}
protected async Task<SignInResult> CheckUserSignInAsync(params RestrictedUserState[] states)
{
var user = await CreateUserAsync(states: states);
using var scope = ServiceProvider.CreateScope();
var page = CreatePage<TestAccountPageModel>(scope.ServiceProvider);
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin())
{
var result = await page.CheckAsync(user);
await uow.CompleteAsync();
return result;
}
}
}
public class AccountPageModel_SignInCheck_Tests : AccountPageModel_SignInCheck_TestBase
{
[Fact]
public void Should_Use_AbpSignInManager()
{
GetRequiredService<SignInManager<IdentityUser>>().ShouldBeAssignableTo<AbpSignInManager>();
}
}
public class AccountPageModel_SignInCheck_ReplacedSignInManager_Tests : AccountPageModel_SignInCheck_TestBase
{
protected override void AfterAddApplication(IServiceCollection services)
{
ReplaceSignInManager(services);
}
[Fact]
public void Should_Use_Replaced_SignInManager()
{
GetRequiredService<SignInManager<IdentityUser>>().ShouldBeOfType<TestSignInManager>();
}
}
public class TestAccountPageModel : AccountPageModel
{
public Task<SignInResult> CheckAsync(IdentityUser user)
{
return CheckUserSignInAsync(user);
}
}

34
modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/IdentityServerSupportedLogin_NotAllowedUser_Tests.cs

@ -0,0 +1,34 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp.MultiTenancy;
using Xunit;
namespace Volo.Abp.Account.Web.Pages.Account;
// The login page is replaced by the login page of IdentityServer.
public class IdentityServerSupportedLogin_NotAllowedUser_Tests : Login_NotAllowedUser_TestBase<AbpAccountWebIdentityServerTestModule>
{
[Fact]
public void Should_Use_Login_Page_Of_IdentityServer()
{
using var scope = ServiceProvider.CreateScope();
CreatePage<LoginModel>(scope.ServiceProvider).ShouldBeOfType<IdentityServerSupportedLoginModel>();
}
}
// The user of a tenant logs in on the host side.
public class IdentityServerSupportedLogin_NotAllowedUser_SharedUser_Tests : IdentityServerSupportedLogin_NotAllowedUser_Tests
{
protected override Guid? UserTenantId { get; } = Guid.NewGuid();
protected override void AfterAddApplication(IServiceCollection services)
{
base.AfterAddApplication(services);
services.Configure<AbpMultiTenancyOptions>(options =>
{
options.IsEnabled = true;
options.UserSharingStrategy = TenantUserSharingStrategy.Shared;
});
}
}

78
modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Login_ExternalLoginCallback_Tests.cs

@ -0,0 +1,78 @@
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp.Identity;
using Volo.Abp.Uow;
using Xunit;
using IdentityUser = Volo.Abp.Identity.IdentityUser;
namespace Volo.Abp.Account.Web.Pages.Account;
// The external login is not linked to a user yet, the user is found by the email of the external login.
public class Login_ExternalLoginCallback_Tests : AbpAccountWebTestBase
{
[Fact]
public async Task Should_Sign_In_User_That_Is_Found_By_Email()
{
var user = await CreateUserAsync();
var providerKey = Guid.NewGuid().ToString("N");
await CallbackAsync(user, providerKey);
IsSignedIn().ShouldBeTrue();
(await FindByLoginAsync(providerKey))?.Id.ShouldBe(user.Id);
}
[Theory]
[InlineData(RestrictedUserState.Inactive)]
[InlineData(RestrictedUserState.LockedOut)]
[InlineData(RestrictedUserState.RequiresConfirmation)]
[InlineData(RestrictedUserState.MustChangePassword)]
[InlineData(RestrictedUserState.PasswordExpired)]
public async Task Should_Not_Sign_In_Restricted_User_That_Is_Found_By_Email(RestrictedUserState state)
{
var user = await CreateUserAsync(states: state);
var providerKey = Guid.NewGuid().ToString("N");
await Should.ThrowAsync<UserFriendlyException>(() => CallbackAsync(user, providerKey));
IsSignedIn().ShouldBeFalse();
(await FindByLoginAsync(providerKey)).ShouldBeNull();
}
private async Task CallbackAsync(IdentityUser user, string providerKey)
{
var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier, providerKey),
new Claim(ClaimTypes.Email, user.Email)
}, IdentityConstants.ExternalScheme));
using var scope = ServiceProvider.CreateScope();
var page = CreatePage<LoginModel>(scope.ServiceProvider, principal);
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin())
{
await page.OnGetExternalLoginCallbackAsync("/");
await uow.CompleteAsync();
}
}
private async Task<IdentityUser> FindByLoginAsync(string providerKey)
{
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin())
{
return await GetRequiredService<IdentityUserManager>().FindByLoginAsync(ExternalLoginProvider, providerKey);
}
}
}
public class Login_ExternalLoginCallback_ReplacedSignInManager_Tests : Login_ExternalLoginCallback_Tests
{
protected override void AfterAddApplication(IServiceCollection services)
{
ReplaceSignInManager(services);
}
}

113
modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Login_NotAllowedUser_Tests.cs

@ -0,0 +1,113 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp.Identity;
using Volo.Abp.Modularity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
using Xunit;
namespace Volo.Abp.Account.Web.Pages.Account;
// The page has no step to change the password, so a user that has to change the password is not allowed to log in.
public abstract class Login_NotAllowedUser_TestBase<TStartupModule> : AbpAccountWebTestBase<TStartupModule>
where TStartupModule : IAbpModule
{
protected virtual Guid? UserTenantId => null;
protected override void AfterAddApplication(IServiceCollection services)
{
services.Configure<AbpIdentityOptions>(options =>
{
options.ExternalLoginProviders.Add<TestExternalLoginProvider>(TestExternalLoginProvider.Name);
});
}
[Fact]
public async Task Should_Check_Password_Of_User_That_Has_To_Change_Password()
{
var user = await CreateUserAsync(UserTenantId, RestrictedUserState.MustChangePassword);
(await LoginAsync(user.UserName, "wrong-password")).ShouldBe(new[] { L("InvalidUserNameOrPassword") });
(await LoginAsync(user.UserName, Password)).ShouldBe(new[] { L("LoginIsNotAllowed") });
}
[Fact]
public async Task Should_Show_Locked_Out_Message_For_Locked_Out_User_That_Has_To_Change_Password()
{
var user = await CreateUserAsync(UserTenantId, RestrictedUserState.MustChangePassword, RestrictedUserState.LockedOut);
(await LoginAsync(user.UserName, "wrong-password")).ShouldBe(new[] { L("UserLockedOutMessage") });
}
// The user may be authenticated by an external login provider, the local password is not the reason of the rejection.
[Fact]
public async Task Should_Not_Check_Password_Of_Unconfirmed_User_That_Has_To_Change_Password()
{
var user = await CreateUserAsync(UserTenantId, RestrictedUserState.MustChangePassword, RestrictedUserState.RequiresConfirmation);
(await LoginAsync(user.UserName, "wrong-password")).ShouldBe(new[] { L("LoginIsNotAllowed") });
}
// The password of the external login provider can not be changed by the application.
[Fact]
public async Task Should_Not_Allow_External_Login_User_That_Has_To_Change_Password()
{
var user = await CreateUserAsync(UserTenantId, RestrictedUserState.MustChangePassword);
(await LoginAsync(user.UserName, TestExternalLoginProvider.Password)).ShouldBe(new[] { L("ExternalLoginPasswordChangeRequired") });
}
[Fact]
public async Task Should_Show_Locked_Out_Message_For_Locked_Out_External_Login_User_That_Has_To_Change_Password()
{
var user = await CreateUserAsync(UserTenantId, RestrictedUserState.MustChangePassword, RestrictedUserState.LockedOut);
(await LoginAsync(user.UserName, TestExternalLoginProvider.Password)).ShouldBe(new[] { L("UserLockedOutMessage") });
}
[Fact]
public async Task Should_Not_Allow_Unconfirmed_External_Login_User_That_Has_To_Change_Password()
{
var user = await CreateUserAsync(UserTenantId, RestrictedUserState.MustChangePassword, RestrictedUserState.RequiresConfirmation);
(await LoginAsync(user.UserName, TestExternalLoginProvider.Password)).ShouldBe(new[] { L("LoginIsNotAllowed") });
}
private async Task<string[]> LoginAsync(string userName, string password)
{
using var scope = ServiceProvider.CreateScope();
var page = CreatePage<LoginModel>(scope.ServiceProvider);
page.LoginInput = new LoginModel.LoginInputModel { UserNameOrEmailAddress = userName, Password = password };
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin())
{
await page.OnPostAsync("Login");
await uow.CompleteAsync();
}
IsSignedIn().ShouldBeFalse();
return GetAlerts(scope.ServiceProvider);
}
}
public class Login_NotAllowedUser_Tests : Login_NotAllowedUser_TestBase<AbpAccountWebTestModule>
{
}
// The user of a tenant logs in on the host side.
public class Login_NotAllowedUser_SharedUser_Tests : Login_NotAllowedUser_Tests
{
protected override Guid? UserTenantId { get; } = Guid.NewGuid();
protected override void AfterAddApplication(IServiceCollection services)
{
base.AfterAddApplication(services);
services.Configure<AbpMultiTenancyOptions>(options =>
{
options.IsEnabled = true;
options.UserSharingStrategy = TenantUserSharingStrategy.Shared;
});
}
}

64
modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Register_Tests.cs

@ -0,0 +1,64 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp.Identity;
using Volo.Abp.Identity.Settings;
using Volo.Abp.Uow;
using Xunit;
namespace Volo.Abp.Account.Web.Pages.Account;
public class Register_Tests : AbpAccountWebTestBase
{
[Fact]
public async Task Should_Sign_In_Registered_User()
{
var (result, alerts) = await RegisterAsync();
result.ShouldNotBeOfType<PageResult>();
alerts.ShouldBeEmpty();
IsSignedIn().ShouldBeTrue();
}
[Fact]
public async Task Should_Show_Message_If_Registered_User_Is_Not_Allowed_To_Sign_In()
{
SetSetting(IdentitySettingNames.SignIn.RequireConfirmedEmail, "true");
var (result, alerts) = await RegisterAsync();
result.ShouldBeOfType<PageResult>();
alerts.ShouldBe(new[] { L("RegisteredButLoginIsNotAllowed") });
IsSignedIn().ShouldBeFalse();
}
private async Task<(IActionResult Result, string[] Alerts)> RegisterAsync()
{
var userName = "user-" + Guid.NewGuid().ToString("N");
using var scope = ServiceProvider.CreateScope();
var page = CreatePage<RegisterModel>(scope.ServiceProvider);
page.Input = new RegisterModel.PostInput { UserName = userName, EmailAddress = userName + "@abp.io", Password = Password };
page.ReturnUrl = "/";
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin())
{
var result = await page.OnPostAsync();
await uow.CompleteAsync();
(await GetRequiredService<IdentityUserManager>().FindByNameAsync(userName)).ShouldNotBeNull();
return (result, GetAlerts(scope.ServiceProvider));
}
}
}
public class Register_ReplacedSignInManager_Tests : Register_Tests
{
protected override void AfterAddApplication(IServiceCollection services)
{
ReplaceSignInManager(services);
}
}

33
modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/TestExternalLoginProvider.cs

@ -0,0 +1,33 @@
using System;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
namespace Volo.Abp.Account.Web;
// Authenticates the existing users with a password that is not their local password.
public class TestExternalLoginProvider : IExternalLoginProvider, ITransientDependency
{
public const string Name = "Test";
public const string Password = "External!9Aa";
public Task<bool> TryAuthenticateAsync(string userName, string plainPassword)
{
return Task.FromResult(plainPassword == Password);
}
public Task<IdentityUser> CreateUserAsync(string userName, string providerName)
{
throw new NotSupportedException();
}
public Task UpdateUserAsync(IdentityUser user, string providerName)
{
return Task.CompletedTask;
}
public Task<bool> IsEnabledAsync()
{
return Task.FromResult(true);
}
}

47
modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInManager.cs

@ -19,6 +19,11 @@ public class AbpSignInManager : SignInManager<IdentityUser>
protected ICurrentTenant CurrentTenant { get; }
protected IOptions<IdentityOptions> IdentityOptionsAccessor { get; }
/// <summary>
/// Set while <see cref="CallPreSignInCheckWithoutPasswordAsync"/> checks a user with a shared password.
/// </summary>
protected bool IsPasswordChangePeriodIgnored { get; set; }
public AbpSignInManager(
IdentityUserManager userManager,
IHttpContextAccessor contextAccessor,
@ -57,7 +62,8 @@ public class AbpSignInManager : SignInManager<IdentityUser>
var externalLoginProvider = (IExternalLoginProvider)Context.RequestServices
.GetRequiredService(externalLoginProviderInfo.Type);
if (await externalLoginProvider.TryAuthenticateAsync(userName, password))
if (await externalLoginProvider.IsEnabledAsync() &&
await externalLoginProvider.TryAuthenticateAsync(userName, password))
{
user = await FindByNameAsync(userName);
if (user == null)
@ -89,6 +95,20 @@ public class AbpSignInManager : SignInManager<IdentityUser>
using (CurrentTenant.Change(user.TenantId))
{
await IdentityOptionsAccessor.SetAsync();
var error = await PreSignInCheck(user);
if (error != null)
{
if (user.IsActive &&
(user.ShouldChangePasswordOnNextLogin || await IdentityUserManager.ShouldPeriodicallyChangePasswordAsync(user)))
{
// The password change is checked before the confirmation and the lockout of the user.
return await base.PreSignInCheck(user) ?? AbpSignInResult.ExternalLoginPasswordChangeRequired;
}
return error;
}
return await SignInOrTwoFactorAsync(user, isPersistent);
}
}
@ -211,6 +231,29 @@ public class AbpSignInManager : SignInManager<IdentityUser>
return await PreSignInCheck(user);
}
/// <summary>
/// Checks a user that is signed in without validating the password of this user, for example
/// the user of another tenant or a linked user.
/// With shared user accounts, the periodic password change is not checked: the password is synchronized
/// to the other users of the account, but the time of the last password change is only set for the user
/// that changed the password.
/// </summary>
/// <param name="user">The user</param>
/// <returns>Null if the user should be allowed to sign in, otherwise the SignInResult why they should be denied.</returns>
public virtual async Task<SignInResult> CallPreSignInCheckWithoutPasswordAsync(IdentityUser user)
{
var isPasswordChangePeriodIgnored = IsPasswordChangePeriodIgnored;
IsPasswordChangePeriodIgnored = IdentityUserManager.IsUserSharingEnabled();
try
{
return await PreSignInCheck(user);
}
finally
{
IsPasswordChangePeriodIgnored = isPasswordChangePeriodIgnored;
}
}
protected override async Task<SignInResult> PreSignInCheck(IdentityUser user)
{
if (!user.IsActive)
@ -225,7 +268,7 @@ public class AbpSignInManager : SignInManager<IdentityUser>
return SignInResult.NotAllowed;
}
if (await IdentityUserManager.ShouldPeriodicallyChangePasswordAsync(user))
if (!IsPasswordChangePeriodIgnored && await IdentityUserManager.ShouldPeriodicallyChangePasswordAsync(user))
{
return SignInResult.NotAllowed;
}

25
modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInResult.cs

@ -0,0 +1,25 @@
using Microsoft.AspNetCore.Identity;
namespace Volo.Abp.Identity.AspNetCore;
public class AbpSignInResult : SignInResult
{
/// <summary>
/// The user is authenticated by an external login provider but has to change the password,
/// which can't be done with the password of the external login provider.
/// </summary>
public static AbpSignInResult ExternalLoginPasswordChangeRequired { get; } = new AbpSignInResult
{
IsNotAllowed = true,
IsExternalLoginPasswordChangeRequired = true
};
public bool IsExternalLoginPasswordChangeRequired { get; protected set; }
public override string ToString()
{
return IsExternalLoginPasswordChangeRequired
? nameof(ExternalLoginPasswordChangeRequired)
: base.ToString();
}
}

15
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserManager.cs

@ -689,9 +689,14 @@ public class IdentityUserManager : UserManager<IdentityUser>, IDomainService
throw new AbpIdentityResultException(IdentityResult.Failed(ErrorDescriber.InvalidUserName(userName)));
}
public virtual bool IsUserSharingEnabled()
{
return MultiTenancyOptions.Value.UserSharingStrategy == TenantUserSharingStrategy.Shared;
}
public virtual async Task<IdentityUser> FindSharedUserByEmailAsync(string email)
{
if (MultiTenancyOptions.Value.UserSharingStrategy == TenantUserSharingStrategy.Isolated)
if (!IsUserSharingEnabled())
{
return await base.FindByEmailAsync(email);
}
@ -722,7 +727,7 @@ public class IdentityUserManager : UserManager<IdentityUser>, IDomainService
public virtual async Task<IdentityUser> FindSharedUserByNameAsync(string userName)
{
if (MultiTenancyOptions.Value.UserSharingStrategy == TenantUserSharingStrategy.Isolated)
if (!IsUserSharingEnabled())
{
return await base.FindByNameAsync(userName);
}
@ -753,7 +758,7 @@ public class IdentityUserManager : UserManager<IdentityUser>, IDomainService
public virtual async Task<IdentityUser> FindSharedUserByLoginAsync(string loginProvider, string providerKey)
{
if (MultiTenancyOptions.Value.UserSharingStrategy == TenantUserSharingStrategy.Isolated)
if (!IsUserSharingEnabled())
{
return await base.FindByLoginAsync(loginProvider, providerKey);
}
@ -783,7 +788,7 @@ public class IdentityUserManager : UserManager<IdentityUser>, IDomainService
public virtual async Task<IdentityUser> FindSharedUserByPasskeyIdAsync(byte[] credentialId)
{
if (MultiTenancyOptions.Value.UserSharingStrategy == TenantUserSharingStrategy.Isolated)
if (!IsUserSharingEnabled())
{
return await base.FindByPasskeyIdAsync(credentialId);
}
@ -813,7 +818,7 @@ public class IdentityUserManager : UserManager<IdentityUser>, IDomainService
public virtual async Task<IdentityUser> FindSharedUserByIdAsync(string userId)
{
if (MultiTenancyOptions.Value.UserSharingStrategy == TenantUserSharingStrategy.Isolated)
if (!IsUserSharingEnabled())
{
return await base.FindByIdAsync(userId);
}

1
modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestModule.cs

@ -29,6 +29,7 @@ public class AbpIdentityAspNetCoreTestModule : AbpModule
Configure<AbpIdentityOptions>(options =>
{
options.ExternalLoginProviders.Add<FakeExternalLoginProvider>(FakeExternalLoginProvider.Name);
options.ExternalLoginProviders.Add<DisabledFakeExternalLoginProvider>(DisabledFakeExternalLoginProvider.Name);
});
Configure<AbpClaimsPrincipalFactoryOptions>(options =>

130
modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpSignInManager_PreSignInCheckWithoutPassword_Tests.cs

@ -0,0 +1,130 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Shouldly;
using Volo.Abp.Identity.Settings;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Settings;
using Volo.Abp.Uow;
using Xunit;
namespace Volo.Abp.Identity.AspNetCore;
public class AbpSignInManager_PreSignInCheckWithoutPassword_Tests : AbpIdentityAspNetCoreTestBase
{
[Theory]
[InlineData(TenantUserSharingStrategy.Isolated, false)]
[InlineData(TenantUserSharingStrategy.Shared, true)]
public async Task Should_Only_Check_Password_Change_Period_If_Password_Is_Not_Shared(TenantUserSharingStrategy strategy, bool isAllowed)
{
var result = await CheckUserWithExpiredPasswordAsync(strategy);
if (isAllowed)
{
result.ShouldBeNull();
}
else
{
result.ShouldBe(SignInResult.NotAllowed);
}
}
[Fact]
public async Task Should_Not_Allow_User_That_Should_Change_Password_On_Next_Login()
{
var result = await CheckUserWithExpiredPasswordAsync(TenantUserSharingStrategy.Shared, (_, user) =>
{
user.SetShouldChangePasswordOnNextLogin(true);
return Task.CompletedTask;
});
result.ShouldBe(SignInResult.NotAllowed);
}
[Fact]
public async Task Should_Not_Allow_Locked_Out_User()
{
var result = await CheckUserWithExpiredPasswordAsync(TenantUserSharingStrategy.Shared, async (userManager, user) =>
{
(await userManager.SetLockoutEnabledAsync(user, true)).CheckErrors();
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors();
});
result.ShouldBe(SignInResult.LockedOut);
}
// Only the password change period is skipped, the other checks of a customized sign-in manager still run.
[Fact]
public async Task Should_Run_Custom_Pre_Sign_In_Check()
{
var result = await CheckUserWithExpiredPasswordAsync(
TenantUserSharingStrategy.Shared,
signInManager: ActivatorUtilities.CreateInstance<RejectingSignInManager>(ServiceProvider));
result.ShouldBe(SignInResult.NotAllowed);
}
private async Task<SignInResult> CheckUserWithExpiredPasswordAsync(
TenantUserSharingStrategy strategy,
Func<IdentityUserManager, IdentityUser, Task> configureUser = null,
AbpSignInManager signInManager = null)
{
GetRequiredService<IOptions<AbpMultiTenancyOptions>>().Value.UserSharingStrategy = strategy;
TestSettingValueProvider.AddSetting(IdentitySettingNames.Password.ForceUsersToPeriodicallyChangePassword, true.ToString());
TestSettingValueProvider.AddSetting(IdentitySettingNames.Password.PasswordChangePeriodDays, 1.ToString());
try
{
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin())
{
var userManager = GetRequiredService<IdentityUserManager>();
var userName = "expired-" + Guid.NewGuid().ToString("N");
var user = new IdentityUser(Guid.NewGuid(), userName, userName + "@abp.io");
(await userManager.CreateAsync(user, "1q2w3E*")).CheckErrors();
user.SetLastPasswordChangeTime(DateTimeOffset.UtcNow.AddDays(-2));
if (configureUser != null)
{
await configureUser(userManager, user);
}
(await userManager.UpdateAsync(user)).CheckErrors();
var result = await (signInManager ?? GetRequiredService<AbpSignInManager>()).CallPreSignInCheckWithoutPasswordAsync(user);
await uow.CompleteAsync();
return result;
}
}
finally
{
TestSettingValueProvider.AddSetting(IdentitySettingNames.Password.ForceUsersToPeriodicallyChangePassword, false.ToString());
}
}
}
// A sign-in manager with a custom rule that rejects the user after the checks of the base class.
public class RejectingSignInManager : AbpSignInManager
{
public RejectingSignInManager(
IdentityUserManager userManager,
IHttpContextAccessor contextAccessor,
IUserClaimsPrincipalFactory<IdentityUser> claimsFactory,
IOptions<IdentityOptions> optionsAccessor,
ILogger<SignInManager<IdentityUser>> logger,
IAuthenticationSchemeProvider schemes,
IUserConfirmation<IdentityUser> confirmation,
IOptions<AbpIdentityOptions> options,
ISettingProvider settingProvider,
ICurrentTenant currentTenant)
: base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes, confirmation, options, settingProvider, currentTenant)
{
}
protected override async Task<SignInResult> PreSignInCheck(IdentityUser user)
{
return await base.PreSignInCheck(user) ?? SignInResult.NotAllowed;
}
}

30
modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/DisabledFakeExternalLoginProvider.cs

@ -0,0 +1,30 @@
using System;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
namespace Volo.Abp.Identity.AspNetCore;
public class DisabledFakeExternalLoginProvider : IExternalLoginProvider, ITransientDependency
{
public const string Name = "DisabledFake";
public Task<bool> TryAuthenticateAsync(string userName, string plainPassword)
{
throw new InvalidOperationException("A disabled external login provider should not be used.");
}
public Task<IdentityUser> CreateUserAsync(string userName, string providerName)
{
throw new InvalidOperationException("A disabled external login provider should not be used.");
}
public Task UpdateUserAsync(IdentityUser user, string providerName)
{
throw new InvalidOperationException("A disabled external login provider should not be used.");
}
public Task<bool> IsEnabledAsync()
{
return Task.FromResult(false);
}
}

116
modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/ExternalLoginProvider_Tests.cs

@ -1,6 +1,9 @@
using System.Linq;
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Shouldly;
using Volo.Abp.Uow;
using Xunit;
namespace Volo.Abp.Identity.AspNetCore;
@ -36,6 +39,117 @@ public class ExternalLoginProvider_Tests : AbpIdentityAspNetCoreTestBase
await CheckUserAsync();
}
[Fact]
public async Task Should_Not_SignIn_With_ExternalLoginProvider_If_User_Not_Active()
{
await CreateExternalUserAsync(async (userManager, user) =>
{
user.SetIsActive(false);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var result = await GetResponseAsStringAsync(
"api/signin-test/password?userName=ext_user&password=abc"
);
result.ShouldBe("NotAllowed");
}
[Fact]
public async Task Should_Not_SignIn_With_ExternalLoginProvider_If_User_Should_Change_Password()
{
await CreateExternalUserAsync(async (userManager, user) =>
{
user.SetShouldChangePasswordOnNextLogin(true);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var result = await GetResponseAsStringAsync(
"api/signin-test/password?userName=ext_user&password=abc"
);
result.ShouldBe("ExternalLoginPasswordChangeRequired");
}
[Fact]
public async Task Should_Not_SignIn_With_ExternalLoginProvider_If_User_Locked_Out()
{
await CreateExternalUserAsync(async (userManager, user) =>
{
(await userManager.SetLockoutEnabledAsync(user, true)).CheckErrors();
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors();
});
var result = await GetResponseAsStringAsync(
"api/signin-test/password?userName=ext_user&password=abc"
);
result.ShouldBe("LockedOut");
}
[Fact]
public async Task Should_Not_SignIn_With_ExternalLoginProvider_If_Locked_Out_User_Should_Change_Password()
{
await CreateExternalUserAsync(async (userManager, user) =>
{
user.SetShouldChangePasswordOnNextLogin(true);
(await userManager.SetLockoutEnabledAsync(user, true)).CheckErrors();
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors();
});
var result = await GetResponseAsStringAsync(
"api/signin-test/password?userName=ext_user&password=abc"
);
result.ShouldBe("LockedOut");
}
[Fact]
public async Task Should_Require_TwoFactor_With_ExternalLoginProvider_If_User_TwoFactor_Enabled()
{
await CreateExternalUserAsync(async (userManager, user) =>
{
(await userManager.SetTwoFactorEnabledAsync(user, true)).CheckErrors();
}, "ext_2fa_user");
var result = await GetResponseAsStringAsync(
"api/signin-test/password?userName=ext_2fa_user&password=abc"
);
result.ShouldBe("RequiresTwoFactor");
}
[Fact]
public async Task Should_Not_SignIn_With_Disabled_ExternalLoginProvider()
{
var result = await GetResponseAsStringAsync(
"api/signin-test/password?userName=disabled_ext_user&password=abc"
);
result.ShouldBe("Failed");
(await GetRequiredService<IdentityUserManager>().FindByNameAsync("disabled_ext_user")).ShouldBeNull();
}
private async Task CreateExternalUserAsync(
Func<IdentityUserManager, IdentityUser, Task> configureUser,
string userName = "ext_user")
{
var result = await GetResponseAsStringAsync(
$"api/signin-test/password?userName={userName}&password=abc"
);
result.ShouldBe("Succeeded");
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin())
{
var userManager = GetRequiredService<IdentityUserManager>();
var user = await userManager.FindByNameAsync(userName);
await configureUser(userManager, user);
await uow.CompleteAsync();
}
}
private async Task CheckUserAsync()
{
var userRepository = GetRequiredService<IIdentityUserRepository>();

14
modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/FakeExternalLoginProvider.cs

@ -31,7 +31,7 @@ public class FakeExternalLoginProvider : ExternalLoginProviderBase, ITransientDe
public override Task<bool> TryAuthenticateAsync(string userName, string plainPassword)
{
return Task.FromResult(
userName == "ext_user" && plainPassword == "abc"
(userName == "ext_user" || userName == "ext_2fa_user") && plainPassword == "abc"
);
}
@ -42,6 +42,18 @@ public class FakeExternalLoginProvider : ExternalLoginProviderBase, ITransientDe
protected override Task<ExternalLoginUserInfo> GetUserInfoAsync(string userName)
{
if (userName == "ext_2fa_user")
{
// TwoFactorEnabled is not set, so the two factor state of the user is left untouched.
return Task.FromResult(
new ExternalLoginUserInfo("ext_2fa_user@test.com")
{
EmailConfirmed = true,
ProviderKey = "456"
}
);
}
if (userName != "ext_user")
{
throw new ArgumentException();

106
modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidator.cs

@ -30,6 +30,8 @@ namespace Volo.Abp.IdentityServer.AspNetIdentity;
public class AbpResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
public const string ExternalLoginPasswordChangeRequired = "ExternalLoginPasswordChangeRequired";
protected SignInManager<IdentityUser> SignInManager { get; }
protected IdentityUserManager UserManager { get; }
protected IdentitySecurityLogManager IdentitySecurityLogManager { get; }
@ -88,7 +90,8 @@ public class AbpResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
var externalLoginProvider = (IExternalLoginProvider)scope.ServiceProvider
.GetRequiredService(externalLoginProviderInfo.Type);
if (await externalLoginProvider.TryAuthenticateAsync(context.UserName, context.Password))
if (await externalLoginProvider.IsEnabledAsync() &&
await externalLoginProvider.TryAuthenticateAsync(context.UserName, context.Password))
{
user = await UserManager.FindByNameAsync(context.UserName);
if (user == null)
@ -100,7 +103,7 @@ public class AbpResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
await externalLoginProvider.UpdateUserAsync(user, externalLoginProviderInfo.Name);
}
await SetSuccessResultAsync(context, user);
await HandleExternalLoginAsync(context, user);
return;
}
}
@ -141,19 +144,24 @@ public class AbpResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
Logger.LogInformation("Authentication failed for username: {username}, reason: not allowed", context.UserName);
if (user.ShouldChangePasswordOnNextLogin)
if (await PreSignInCheckAsync(user))
{
await HandleShouldChangePasswordOnNextLoginAsync(context, user, context.Password);
return;
if (user.ShouldChangePasswordOnNextLogin)
{
await HandleShouldChangePasswordOnNextLoginAsync(context, user, context.Password);
return;
}
if (await UserManager.ShouldPeriodicallyChangePasswordAsync(user))
{
await HandlePeriodicallyChangePasswordAsync(context, user, context.Password);
return;
}
}
if (await UserManager.ShouldPeriodicallyChangePasswordAsync(user))
{
await HandlePeriodicallyChangePasswordAsync(context, user, context.Password);
return;
}
errorDescription = Localizer["LoginIsNotAllowed"];
errorDescription = user.IsActive && await SignInManager.CanSignInAsync(user) && await UserManager.IsLockedOutAsync(user)
? Localizer["UserLockedOut"]
: Localizer["LoginIsNotAllowed"];
}
}
else
@ -188,6 +196,80 @@ public class AbpResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
}
}
protected virtual async Task HandleExternalLoginAsync(ResourceOwnerPasswordValidationContext context, IdentityUser user)
{
await IdentityOptions.SetAsync();
if (!await PreSignInCheckAsync(user))
{
var isLockedOut = user.IsActive && await SignInManager.CanSignInAsync(user) && await UserManager.IsLockedOutAsync(user);
await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
{
Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
Action = isLockedOut ? IdentityServerSecurityLogActionConsts.LoginLockedout : IdentityServerSecurityLogActionConsts.LoginNotAllowed,
UserName = context.UserName,
ClientId = await FindClientIdAsync(context)
});
if (isLockedOut)
{
Logger.LogInformation("Authentication failed for username: {username}, reason: locked out", context.UserName);
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, Localizer["UserLockedOut"]);
return;
}
Logger.LogInformation("Authentication failed for username: {username}, reason: not allowed", context.UserName);
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, Localizer["LoginIsNotAllowed"]);
return;
}
// The change password challenge is not returned, because the password of the external login provider can't be used to change the local password.
if (user.ShouldChangePasswordOnNextLogin || await UserManager.ShouldPeriodicallyChangePasswordAsync(user))
{
Logger.LogInformation("Authentication failed for username: {username}, reason: {reason}", context.UserName, ExternalLoginPasswordChangeRequired);
await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
{
Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
Action = IdentityServerSecurityLogActionConsts.LoginNotAllowed,
UserName = context.UserName,
ClientId = await FindClientIdAsync(context)
});
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, ExternalLoginPasswordChangeRequired);
return;
}
if (await IsTfaEnabledAsync(user))
{
await HandleTwoFactorLoginAsync(context, user);
return;
}
await SetSuccessResultAsync(context, user);
}
protected virtual async Task<bool> PreSignInCheckAsync(IdentityUser user)
{
if (!user.IsActive)
{
return false;
}
if (!await SignInManager.CanSignInAsync(user))
{
return false;
}
if (await UserManager.IsLockedOutAsync(user))
{
return false;
}
return true;
}
protected virtual async Task HandleTwoFactorLoginAsync(ResourceOwnerPasswordValidationContext context, IdentityUser user)
{
var recoveryCode = context.Request?.Raw?["RecoveryCode"];

213
modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidatorExternalLogin_Tests.cs

@ -0,0 +1,213 @@
using System;
using System.Collections.Specialized;
using System.Threading.Tasks;
using IdentityServer4.Validation;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp.Identity;
using Volo.Abp.Identity.Settings;
using Xunit;
using IdentityUser = Volo.Abp.Identity.IdentityUser;
namespace Volo.Abp.IdentityServer.AspNetIdentity;
public class AbpResourceOwnerPasswordValidatorExternalLogin_Tests : AbpResourceOwnerPasswordValidatorTestBase
{
protected override void AfterAddApplication(IServiceCollection services)
{
services.Configure<AbpIdentityOptions>(options =>
{
options.ExternalLoginProviders.Add<TestExternalLoginProvider>(TestExternalLoginProvider.Name);
options.ExternalLoginProviders.Add<DisabledTestExternalLoginProvider>(DisabledTestExternalLoginProvider.Name);
});
}
[Fact]
public async Task External_Login_Should_Authenticate()
{
await CreateUserAsync(twoFactorEnabled: false);
var context = CreateContext(password: TestExternalLoginProvider.Password);
await ValidateAsync(context);
context.Result.IsError.ShouldBeFalse();
context.Result.Subject.ShouldNotBeNull();
}
[Fact]
public async Task External_Login_With_TwoFactor_Should_Require_Code_Before_Authenticating()
{
await CreateUserAsync(twoFactorEnabled: true);
var challengeContext = CreateContext(password: TestExternalLoginProvider.Password);
await ValidateAsync(challengeContext);
AssertInvalidGrant(challengeContext, "RequiresTwoFactor");
var code = await GenerateTwoFactorCodeAsync();
var context = CreateContext(new NameValueCollection
{
["TwoFactorProvider"] = TokenOptions.DefaultEmailProvider,
["TwoFactorCode"] = code
}, TestExternalLoginProvider.Password);
await ValidateAsync(context);
context.Result.IsError.ShouldBeFalse();
context.Result.Subject.ShouldNotBeNull();
}
[Fact]
public async Task External_Login_Should_Not_Authenticate_Inactive_User()
{
await CreateUserAsync(twoFactorEnabled: false);
await UpdateUserAsync(async (userManager, user) =>
{
user.SetIsActive(false);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var context = CreateContext(password: TestExternalLoginProvider.Password);
await ValidateAsync(context);
AssertInvalidGrant(
context,
"You are not allowed to login! Your account is inactive or needs to confirm your email/phone number.");
}
[Fact]
public async Task External_Login_Should_Not_Authenticate_Locked_Out_User()
{
await CreateUserAsync(twoFactorEnabled: false);
await UpdateUserAsync(async (userManager, user) =>
{
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors();
});
var context = CreateContext(password: TestExternalLoginProvider.Password);
await ValidateAsync(context);
AssertInvalidGrant(
context,
"The user account has been locked out due to invalid login attempts. Please wait a while and try again.");
}
[Fact]
public async Task External_Login_Should_Not_Authenticate_User_That_Requires_Confirmation()
{
GetRequiredService<IdentityServerTestSettingValueProvider>().Set(
IdentitySettingNames.SignIn.RequireConfirmedEmail,
true.ToString());
await CreateUserAsync(twoFactorEnabled: false);
await UpdateUserAsync(async (userManager, user) =>
{
user.SetEmailConfirmed(false);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var context = CreateContext(password: TestExternalLoginProvider.Password);
await ValidateAsync(context);
AssertInvalidGrant(
context,
"You are not allowed to login! Your account is inactive or needs to confirm your email/phone number.");
}
[Fact]
public async Task External_Login_Should_Not_Authenticate_User_That_Should_Change_Password()
{
await CreateUserAsync(twoFactorEnabled: false, shouldChangePasswordOnNextLogin: true);
var context = CreateContext(password: TestExternalLoginProvider.Password);
await ValidateAsync(context);
AssertInvalidGrant(context, "ExternalLoginPasswordChangeRequired");
}
[Fact]
public async Task External_Login_Should_Not_Change_Password_Of_User_That_Should_Change_Password()
{
await CreateUserAsync(twoFactorEnabled: false, shouldChangePasswordOnNextLogin: true);
string changePasswordToken = null;
await UpdateUserAsync(async (userManager, user) =>
{
(await userManager.RemovePasswordAsync(user)).CheckErrors();
(await userManager.AddPasswordAsync(user, TestExternalLoginProvider.Password)).CheckErrors();
changePasswordToken = await userManager.GenerateUserTokenAsync(
user,
TokenOptions.DefaultProvider,
"ShouldChangePasswordOnNextLogin");
});
var context = CreateContext(new NameValueCollection
{
["NewPassword"] = NewPassword,
["ChangePasswordToken"] = changePasswordToken
}, TestExternalLoginProvider.Password);
await ValidateAsync(context);
AssertInvalidGrant(context, "ExternalLoginPasswordChangeRequired");
await UpdateUserAsync(async (userManager, user) =>
{
(await userManager.CheckPasswordAsync(user, TestExternalLoginProvider.Password)).ShouldBeTrue();
(await userManager.CheckPasswordAsync(user, NewPassword)).ShouldBeFalse();
user.ShouldChangePasswordOnNextLogin.ShouldBeTrue();
});
}
[Fact]
public async Task External_Login_Should_Not_Authenticate_User_That_Should_Periodically_Change_Password()
{
var settingValueProvider = GetRequiredService<IdentityServerTestSettingValueProvider>();
settingValueProvider.Set(
IdentitySettingNames.Password.ForceUsersToPeriodicallyChangePassword,
true.ToString());
settingValueProvider.Set(
IdentitySettingNames.Password.PasswordChangePeriodDays,
1.ToString());
await CreateUserAsync(
twoFactorEnabled: false,
lastPasswordChangeTime: DateTimeOffset.UtcNow.AddDays(-2));
var context = CreateContext(password: TestExternalLoginProvider.Password);
await ValidateAsync(context);
AssertInvalidGrant(context, "ExternalLoginPasswordChangeRequired");
}
[Fact]
public async Task Disabled_External_Login_Provider_Should_Not_Be_Used()
{
await CreateUserAsync(twoFactorEnabled: false);
var context = CreateContext(password: "neither-local-nor-external-1q2w3E*");
await ValidateAsync(context);
AssertInvalidGrant(context, "Invalid username or password!");
}
private Task UpdateUserAsync(Func<IdentityUserManager, IdentityUser, Task> action)
{
return WithUnitOfWorkAsync(async serviceProvider =>
{
var userManager = serviceProvider.GetRequiredService<IdentityUserManager>();
var user = await userManager.FindByNameAsync(UserName);
await action(userManager, user);
});
}
private static void AssertInvalidGrant(
ResourceOwnerPasswordValidationContext context,
string expectedErrorDescription)
{
context.Result.IsError.ShouldBeTrue();
context.Result.Error.ShouldBe("invalid_grant");
context.Result.ErrorDescription.ShouldBe(expectedErrorDescription);
context.Result.Subject.ShouldBeNull();
(context.Result.CustomResponse?.ContainsKey("changePasswordToken") ?? false).ShouldBeFalse();
}
}

118
modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidatorPasswordChange_Tests.cs

@ -3,7 +3,9 @@ using System.Collections.Specialized;
using System.Threading.Tasks;
using IdentityServer4.Validation;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp.Identity;
using Volo.Abp.Identity.Settings;
using Xunit;
@ -176,6 +178,122 @@ public class AbpResourceOwnerPasswordValidatorPasswordChange_Tests : AbpResource
AssertPasswordChangeChallenge(retryContext, "ShouldChangePasswordOnNextLogin");
}
[Fact]
public async Task Required_Password_Change_Should_Not_Be_Offered_To_Inactive_User()
{
await CreateUserAsync(twoFactorEnabled: false, shouldChangePasswordOnNextLogin: true);
await UpdateUserAsync(async (userManager, user) =>
{
user.SetIsActive(false);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var context = CreateContext();
await ValidateAsync(context);
AssertNotAllowed(
context,
"You are not allowed to login! Your account is inactive or needs to confirm your email/phone number.");
}
[Fact]
public async Task Required_Password_Change_Should_Not_Be_Completed_By_Inactive_User()
{
await CreateUserAsync(twoFactorEnabled: false, shouldChangePasswordOnNextLogin: true);
string changePasswordToken = null;
await UpdateUserAsync(async (userManager, user) =>
{
changePasswordToken = await userManager.GenerateUserTokenAsync(
user,
TokenOptions.DefaultProvider,
"ShouldChangePasswordOnNextLogin");
user.SetIsActive(false);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var context = CreateContext(new NameValueCollection
{
["NewPassword"] = NewPassword,
["ChangePasswordToken"] = changePasswordToken
});
await ValidateAsync(context);
AssertNotAllowed(
context,
"You are not allowed to login! Your account is inactive or needs to confirm your email/phone number.");
var passwordState = await GetPasswordStateAsync();
passwordState.OldPasswordIsValid.ShouldBeTrue();
passwordState.NewPasswordIsValid.ShouldBeFalse();
passwordState.ShouldChangePasswordOnNextLogin.ShouldBeTrue();
}
[Fact]
public async Task Required_Password_Change_Should_Not_Be_Offered_To_Locked_Out_User()
{
await CreateUserAsync(twoFactorEnabled: false, shouldChangePasswordOnNextLogin: true);
await UpdateUserAsync(async (userManager, user) =>
{
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors();
});
var context = CreateContext();
await ValidateAsync(context);
AssertNotAllowed(
context,
"The user account has been locked out due to invalid login attempts. Please wait a while and try again.");
}
[Fact]
public async Task Required_Password_Change_Should_Not_Be_Offered_To_User_That_Requires_Confirmation()
{
var settingValueProvider = GetRequiredService<IdentityServerTestSettingValueProvider>();
settingValueProvider.Set(IdentitySettingNames.SignIn.RequireConfirmedEmail, true.ToString());
try
{
await CreateUserAsync(twoFactorEnabled: false, shouldChangePasswordOnNextLogin: true);
await UpdateUserAsync(async (userManager, user) =>
{
user.SetEmailConfirmed(false);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var context = CreateContext();
await ValidateAsync(context);
AssertNotAllowed(
context,
"You are not allowed to login! Your account is inactive or needs to confirm your email/phone number.");
}
finally
{
settingValueProvider.Clear();
}
}
private Task UpdateUserAsync(Func<IdentityUserManager, Volo.Abp.Identity.IdentityUser, Task> action)
{
return WithUnitOfWorkAsync(async serviceProvider =>
{
var userManager = serviceProvider.GetRequiredService<IdentityUserManager>();
var user = await userManager.FindByNameAsync(UserName);
await action(userManager, user);
});
}
private static void AssertNotAllowed(
ResourceOwnerPasswordValidationContext context,
string expectedErrorDescription)
{
context.Result.IsError.ShouldBeTrue();
context.Result.Error.ShouldBe("invalid_grant");
context.Result.ErrorDescription.ShouldBe(expectedErrorDescription);
context.Result.Subject.ShouldBeNull();
(context.Result.CustomResponse?.ContainsKey("changePasswordToken") ?? false).ShouldBeFalse();
}
private static string AssertPasswordChangeChallenge(
ResourceOwnerPasswordValidationContext context,
string expectedErrorDescription)

31
modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/DisabledTestExternalLoginProvider.cs

@ -0,0 +1,31 @@
using System;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
namespace Volo.Abp.IdentityServer.AspNetIdentity;
public class DisabledTestExternalLoginProvider : IExternalLoginProvider, ITransientDependency
{
public const string Name = "DisabledTest";
public Task<bool> TryAuthenticateAsync(string userName, string plainPassword)
{
throw new InvalidOperationException("A disabled external login provider should not be used.");
}
public Task<IdentityUser> CreateUserAsync(string userName, string providerName)
{
throw new InvalidOperationException("A disabled external login provider should not be used.");
}
public Task UpdateUserAsync(IdentityUser user, string providerName)
{
throw new InvalidOperationException("A disabled external login provider should not be used.");
}
public Task<bool> IsEnabledAsync()
{
return Task.FromResult(false);
}
}

32
modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/TestExternalLoginProvider.cs

@ -0,0 +1,32 @@
using System;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
namespace Volo.Abp.IdentityServer.AspNetIdentity;
public class TestExternalLoginProvider : IExternalLoginProvider, ITransientDependency
{
public const string Name = "Test";
public const string Password = "external-1q2w3E*";
public Task<bool> TryAuthenticateAsync(string userName, string plainPassword)
{
return Task.FromResult(plainPassword == Password);
}
public Task<IdentityUser> CreateUserAsync(string userName, string providerName)
{
throw new NotSupportedException();
}
public Task UpdateUserAsync(IdentityUser user, string providerName)
{
return Task.CompletedTask;
}
public Task<bool> IsEnabledAsync()
{
return Task.FromResult(true);
}
}

2
modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpErrorDescriptionConsts.cs

@ -5,4 +5,6 @@ public static class AbpErrorDescriptionConsts
public const string RequiresTwoFactor = "RequiresTwoFactor";
public const string RequiresConfirmUser = "RequiresConfirmUser";
public const string ExternalLoginPasswordChangeRequired = "ExternalLoginPasswordChangeRequired";
}

103
modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/Controllers/TokenController.Password.cs

@ -55,7 +55,8 @@ public partial class TokenController
var externalLoginProvider = (IExternalLoginProvider)scope.ServiceProvider
.GetRequiredService(externalLoginProviderInfo.Type);
if (await externalLoginProvider.TryAuthenticateAsync(request.Username, request.Password))
if (await externalLoginProvider.IsEnabledAsync() &&
await externalLoginProvider.TryAuthenticateAsync(request.Username, request.Password))
{
user = await UserManager.FindSharedUserByNameAsync(request.Username);
if (user == null)
@ -72,7 +73,7 @@ public partial class TokenController
using (CurrentTenant.Change(user.TenantId))
{
return await SetSuccessResultAsync(request, user);
return await HandleExternalLoginAsync(request, user);
}
}
}
@ -137,23 +138,33 @@ public partial class TokenController
{
Logger.LogInformation("Authentication failed for username: {username}, reason: not allowed", request.Username);
if (user.ShouldChangePasswordOnNextLogin)
if (await PreSignInCheckAsync(user))
{
return await HandleShouldChangePasswordOnNextLoginAsync(request, user, request.Password);
if (user.ShouldChangePasswordOnNextLogin)
{
return await HandleShouldChangePasswordOnNextLoginAsync(request, user, request.Password);
}
if (await UserManager.ShouldPeriodicallyChangePasswordAsync(user))
{
return await HandlePeriodicallyChangePasswordAsync(request, user, request.Password);
}
}
if (await UserManager.ShouldPeriodicallyChangePasswordAsync(user))
if (user.IsActive && await SignInManager.CanSignInAsync(user) && await UserManager.IsLockedOutAsync(user))
{
return await HandlePeriodicallyChangePasswordAsync(request, user, request.Password);
errorCode = AbpOpenIddictErrors.AccountLocked;
errorDescription = "The user account has been locked out due to invalid login attempts. Please wait a while and try again.";
}
if (user.IsActive)
else if (user.IsActive)
{
return await HandleConfirmUserAsync(request, user);
}
errorCode = AbpOpenIddictErrors.AccountInactive;
errorDescription = "You are not allowed to login! Your account is inactive or needs to confirm your email/phone number.";
else
{
errorCode = AbpOpenIddictErrors.AccountInactive;
errorDescription = "You are not allowed to login! Your account is inactive or needs to confirm your email/phone number.";
}
}
}
else
@ -182,6 +193,76 @@ public partial class TokenController
}
}
protected virtual async Task<IActionResult> HandleExternalLoginAsync(OpenIddictRequest request, IdentityUser user)
{
await IdentityOptions.SetAsync();
if (!await PreSignInCheckAsync(user))
{
var canSignIn = await SignInManager.CanSignInAsync(user);
var isLockedOut = user.IsActive && canSignIn && await UserManager.IsLockedOutAsync(user);
await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
{
Identity = OpenIddictSecurityLogIdentityConsts.OpenIddict,
Action = isLockedOut ? OpenIddictSecurityLogActionConsts.LoginLockedout : OpenIddictSecurityLogActionConsts.LoginNotAllowed,
UserName = request.Username,
ClientId = request.ClientId
});
if (isLockedOut)
{
Logger.LogInformation("Authentication failed for username: {username}, reason: locked out", request.Username);
return Forbid(new AuthenticationProperties(new Dictionary<string, string>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = AbpOpenIddictErrors.AccountLocked,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user account has been locked out due to invalid login attempts. Please wait a while and try again."
}), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
Logger.LogInformation("Authentication failed for username: {username}, reason: not allowed", request.Username);
if (user.IsActive && !canSignIn)
{
return await HandleConfirmUserAsync(request, user);
}
return Forbid(new AuthenticationProperties(new Dictionary<string, string>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = AbpOpenIddictErrors.AccountInactive,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "You are not allowed to login! Your account is inactive or needs to confirm your email/phone number."
}), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
// The change password challenge is not returned, because the password of the external login provider can't be used to change the local password.
if (user.ShouldChangePasswordOnNextLogin || await UserManager.ShouldPeriodicallyChangePasswordAsync(user))
{
Logger.LogInformation("Authentication failed for username: {username}, reason: {reason}", request.Username, AbpErrorDescriptionConsts.ExternalLoginPasswordChangeRequired);
await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
{
Identity = OpenIddictSecurityLogIdentityConsts.OpenIddict,
Action = OpenIddictSecurityLogActionConsts.LoginNotAllowed,
UserName = request.Username,
ClientId = request.ClientId
});
return Forbid(new AuthenticationProperties(new Dictionary<string, string>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = OpenIddictConstants.Errors.InvalidGrant,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = AbpErrorDescriptionConsts.ExternalLoginPasswordChangeRequired
}), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
if (await IsTfaEnabledAsync(user))
{
return await HandleTwoFactorLoginAsync(request, user);
}
return await SetSuccessResultAsync(request, user);
}
protected virtual async Task ReplaceEmailToUsernameOfInputIfNeeds(OpenIddictRequest request)
{
if (!ValidationHelper.IsValidEmailAddress(request.Username))

31
modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/DisabledTestExternalLoginProvider.cs

@ -0,0 +1,31 @@
using System;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
namespace Volo.Abp.OpenIddict.Integration;
public class DisabledTestExternalLoginProvider : IExternalLoginProvider, ITransientDependency
{
public const string Name = "DisabledTest";
public Task<bool> TryAuthenticateAsync(string userName, string plainPassword)
{
throw new InvalidOperationException("A disabled external login provider should not be used.");
}
public Task<IdentityUser> CreateUserAsync(string userName, string providerName)
{
throw new InvalidOperationException("A disabled external login provider should not be used.");
}
public Task UpdateUserAsync(IdentityUser user, string providerName)
{
throw new InvalidOperationException("A disabled external login provider should not be used.");
}
public Task<bool> IsEnabledAsync()
{
return Task.FromResult(false);
}
}

287
modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/OpenIddictPasswordGrantExternalLogin_Integration_Tests.cs

@ -0,0 +1,287 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp.Identity;
using Volo.Abp.Identity.Settings;
using Xunit;
using IdentityUser = Volo.Abp.Identity.IdentityUser;
namespace Volo.Abp.OpenIddict.Integration;
public class OpenIddictPasswordGrantExternalLogin_Integration_Tests : OpenIddictPasswordGrantIntegrationTestBase
{
protected override void ConfigureServices(IServiceCollection services)
{
services.Configure<AbpIdentityOptions>(options =>
{
options.ExternalLoginProviders.Add<TestExternalLoginProvider>(TestExternalLoginProvider.Name);
options.ExternalLoginProviders.Add<DisabledTestExternalLoginProvider>(DisabledTestExternalLoginProvider.Name);
});
}
[Fact]
public async Task External_Login_Should_Issue_Token()
{
await UpdateUserAsync(async (userManager, user) =>
{
(await userManager.SetTwoFactorEnabledAsync(user, false)).CheckErrors();
});
var response = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password);
await AssertAccessTokenAsync(response);
}
[Fact]
public async Task External_Login_With_TwoFactor_Should_Require_Code_Before_Issuing_Token()
{
var challenge = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password);
await AssertErrorAsync(challenge, "invalid_grant", AbpErrorDescriptionConsts.RequiresTwoFactor);
var code = await GenerateTwoFactorCodeAsync();
var response = await RequestPasswordTokenAsync(new Dictionary<string, string>
{
["TwoFactorProvider"] = TokenOptions.DefaultEmailProvider,
["TwoFactorCode"] = code
}, TestExternalLoginProvider.Password);
await AssertAccessTokenAsync(response);
}
[Fact]
public async Task External_Login_With_Invalid_TwoFactor_Code_Should_Not_Issue_Token()
{
var response = await RequestPasswordTokenAsync(new Dictionary<string, string>
{
["TwoFactorProvider"] = TokenOptions.DefaultEmailProvider,
["TwoFactorCode"] = "invalid-code"
}, TestExternalLoginProvider.Password);
await AssertErrorAsync(response, "invalid_grant", "Invalid authenticator code!");
}
[Fact]
public async Task External_Login_With_Valid_Recovery_Code_Should_Issue_Token()
{
var recoveryCode = await WithUnitOfWorkAsync(async serviceProvider =>
{
var userManager = serviceProvider.GetRequiredService<IdentityUserManager>();
var user = await userManager.FindByNameAsync(OpenIddictPasswordGrantTestData.UserName);
return (await userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 1)).Single();
});
var response = await RequestPasswordTokenAsync(new Dictionary<string, string>
{
["RecoveryCode"] = recoveryCode
}, TestExternalLoginProvider.Password);
await AssertAccessTokenAsync(response);
}
[Fact]
public async Task External_Login_With_Invalid_Recovery_Code_Should_Not_Issue_Token()
{
var response = await RequestPasswordTokenAsync(new Dictionary<string, string>
{
["RecoveryCode"] = "invalid-recovery-code"
}, TestExternalLoginProvider.Password);
await AssertErrorAsync(response, "invalid_grant", "Invalid recovery code!");
}
[Fact]
public async Task External_Login_Should_Not_Issue_Token_For_Inactive_User()
{
await UpdateUserAsync(async (userManager, user) =>
{
user.SetIsActive(false);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var response = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password);
await AssertErrorAsync(response, AbpOpenIddictErrors.AccountInactive);
}
[Fact]
public async Task External_Login_Should_Not_Issue_Token_For_Inactive_User_With_Valid_TwoFactor_Code()
{
var code = await GenerateTwoFactorCodeAsync();
await UpdateUserAsync(async (userManager, user) =>
{
user.SetIsActive(false);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var response = await RequestPasswordTokenAsync(new Dictionary<string, string>
{
["TwoFactorProvider"] = TokenOptions.DefaultEmailProvider,
["TwoFactorCode"] = code
}, TestExternalLoginProvider.Password);
await AssertErrorAsync(response, AbpOpenIddictErrors.AccountInactive);
}
[Fact]
public async Task External_Login_Should_Not_Issue_Token_For_Locked_Out_User()
{
await UpdateUserAsync(async (userManager, user) =>
{
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors();
});
var response = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password);
await AssertErrorAsync(response, AbpOpenIddictErrors.AccountLocked);
}
[Fact]
public async Task External_Login_Should_Not_Issue_Token_For_Locked_Out_User_With_Valid_TwoFactor_Code()
{
var code = await GenerateTwoFactorCodeAsync();
await UpdateUserAsync(async (userManager, user) =>
{
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors();
});
var response = await RequestPasswordTokenAsync(new Dictionary<string, string>
{
["TwoFactorProvider"] = TokenOptions.DefaultEmailProvider,
["TwoFactorCode"] = code
}, TestExternalLoginProvider.Password);
await AssertErrorAsync(response, AbpOpenIddictErrors.AccountLocked);
}
[Fact]
public async Task External_Login_Should_Not_Issue_Token_For_User_That_Should_Change_Password()
{
await UpdateUserAsync(async (userManager, user) =>
{
user.SetShouldChangePasswordOnNextLogin(true);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var response = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password);
await AssertErrorAsync(response, "invalid_grant", "ExternalLoginPasswordChangeRequired");
}
[Fact]
public async Task External_Login_Should_Not_Change_Password_Of_User_That_Should_Change_Password()
{
var changePasswordToken = await WithUnitOfWorkAsync(async serviceProvider =>
{
var userManager = serviceProvider.GetRequiredService<IdentityUserManager>();
var user = await userManager.FindByNameAsync(OpenIddictPasswordGrantTestData.UserName);
user.SetShouldChangePasswordOnNextLogin(true);
(await userManager.RemovePasswordAsync(user)).CheckErrors();
(await userManager.AddPasswordAsync(user, TestExternalLoginProvider.Password)).CheckErrors();
return await userManager.GenerateUserTokenAsync(
user,
TokenOptions.DefaultProvider,
"ShouldChangePasswordOnNextLogin");
});
var response = await RequestPasswordTokenAsync(new Dictionary<string, string>
{
["NewPassword"] = NewPassword,
["ChangePasswordToken"] = changePasswordToken
}, TestExternalLoginProvider.Password);
await AssertErrorAsync(response, "invalid_grant", "ExternalLoginPasswordChangeRequired");
await WithUnitOfWorkAsync(async serviceProvider =>
{
var userManager = serviceProvider.GetRequiredService<IdentityUserManager>();
var user = await userManager.FindByNameAsync(OpenIddictPasswordGrantTestData.UserName);
(await userManager.CheckPasswordAsync(user, TestExternalLoginProvider.Password)).ShouldBeTrue();
(await userManager.CheckPasswordAsync(user, NewPassword)).ShouldBeFalse();
user.ShouldChangePasswordOnNextLogin.ShouldBeTrue();
});
}
[Fact]
public async Task External_Login_Should_Not_Issue_Token_For_User_That_Should_Periodically_Change_Password()
{
var settingValueProvider = GetRequiredService<OpenIddictTestSettingValueProvider>();
settingValueProvider.Set(
IdentitySettingNames.Password.ForceUsersToPeriodicallyChangePassword,
true.ToString());
settingValueProvider.Set(
IdentitySettingNames.Password.PasswordChangePeriodDays,
1.ToString());
await UpdateUserAsync(async (userManager, user) =>
{
user.SetLastPasswordChangeTime(DateTimeOffset.UtcNow.AddDays(-2));
(await userManager.UpdateAsync(user)).CheckErrors();
});
var response = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password);
await AssertErrorAsync(response, "invalid_grant", "ExternalLoginPasswordChangeRequired");
}
[Fact]
public async Task External_Login_Should_Not_Issue_Token_For_User_That_Requires_Confirmation()
{
GetRequiredService<OpenIddictTestSettingValueProvider>().Set(
IdentitySettingNames.SignIn.RequireConfirmedEmail,
true.ToString());
await UpdateUserAsync(async (userManager, user) =>
{
user.SetEmailConfirmed(false);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var response = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password);
await AssertErrorAsync(response, "invalid_grant", AbpErrorDescriptionConsts.RequiresConfirmUser);
}
[Fact]
public async Task Disabled_External_Login_Provider_Should_Not_Be_Used()
{
var response = await RequestPasswordTokenAsync(password: "neither-local-nor-external-1q2w3E*");
await AssertErrorAsync(response, "invalid_grant", "Invalid username or password!");
}
private Task UpdateUserAsync(Func<IdentityUserManager, IdentityUser, Task> action)
{
return WithUnitOfWorkAsync(async serviceProvider =>
{
var userManager = serviceProvider.GetRequiredService<IdentityUserManager>();
var user = await userManager.FindByNameAsync(OpenIddictPasswordGrantTestData.UserName);
await action(userManager, user);
});
}
private static async Task AssertErrorAsync(
HttpResponseMessage response,
string expectedError,
string expectedErrorDescription = null)
{
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var root = document.RootElement;
root.GetProperty("error").GetString().ShouldBe(expectedError);
if (expectedErrorDescription != null)
{
root.GetProperty("error_description").GetString().ShouldBe(expectedErrorDescription);
}
root.TryGetProperty("access_token", out _).ShouldBeFalse();
root.TryGetProperty("changePasswordToken", out _).ShouldBeFalse();
}
}

119
modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/OpenIddictPasswordGrantPasswordChange_Integration_Tests.cs

@ -208,6 +208,125 @@ public class OpenIddictPasswordGrantPasswordChange_Integration_Tests : OpenIddic
"ShouldChangePasswordOnNextLogin");
}
[Fact]
public async Task Required_Password_Change_Should_Not_Be_Offered_To_Inactive_User()
{
await ConfigurePasswordChangeUserAsync(
twoFactorEnabled: false,
shouldChangePasswordOnNextLogin: true);
await UpdateUserAsync(async (userManager, user) =>
{
user.SetIsActive(false);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var response = await RequestPasswordTokenAsync();
await AssertNotAllowedAsync(response, AbpOpenIddictErrors.AccountInactive);
}
[Fact]
public async Task Required_Password_Change_Should_Not_Be_Completed_By_Inactive_User()
{
await ConfigurePasswordChangeUserAsync(
twoFactorEnabled: false,
shouldChangePasswordOnNextLogin: true);
string changePasswordToken = null;
await UpdateUserAsync(async (userManager, user) =>
{
changePasswordToken = await userManager.GenerateUserTokenAsync(
user,
TokenOptions.DefaultProvider,
"ShouldChangePasswordOnNextLogin");
user.SetIsActive(false);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var response = await RequestPasswordTokenAsync(new Dictionary<string, string>
{
["NewPassword"] = NewPassword,
["ChangePasswordToken"] = changePasswordToken
});
await AssertNotAllowedAsync(response, AbpOpenIddictErrors.AccountInactive);
var passwordState = await GetPasswordStateAsync();
passwordState.OldPasswordIsValid.ShouldBeTrue();
passwordState.NewPasswordIsValid.ShouldBeFalse();
passwordState.ShouldChangePasswordOnNextLogin.ShouldBeTrue();
}
[Fact]
public async Task Required_Password_Change_Should_Not_Be_Offered_To_Locked_Out_User()
{
await ConfigurePasswordChangeUserAsync(
twoFactorEnabled: false,
shouldChangePasswordOnNextLogin: true);
await UpdateUserAsync(async (userManager, user) =>
{
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors();
});
var response = await RequestPasswordTokenAsync();
await AssertNotAllowedAsync(response, AbpOpenIddictErrors.AccountLocked);
}
[Fact]
public async Task Required_Password_Change_Should_Not_Be_Offered_To_User_That_Requires_Confirmation()
{
var settingValueProvider = GetRequiredService<OpenIddictTestSettingValueProvider>();
settingValueProvider.Set(IdentitySettingNames.SignIn.RequireConfirmedEmail, true.ToString());
try
{
await ConfigurePasswordChangeUserAsync(
twoFactorEnabled: false,
shouldChangePasswordOnNextLogin: true);
await UpdateUserAsync(async (userManager, user) =>
{
user.SetEmailConfirmed(false);
(await userManager.UpdateAsync(user)).CheckErrors();
});
var response = await RequestPasswordTokenAsync();
await AssertNotAllowedAsync(response, "invalid_grant", AbpErrorDescriptionConsts.RequiresConfirmUser);
}
finally
{
settingValueProvider.Clear();
}
}
private Task UpdateUserAsync(Func<IdentityUserManager, Volo.Abp.Identity.IdentityUser, Task> action)
{
return WithUnitOfWorkAsync(async serviceProvider =>
{
var userManager = serviceProvider.GetRequiredService<IdentityUserManager>();
var user = await userManager.FindByNameAsync(OpenIddictPasswordGrantTestData.UserName);
await action(userManager, user);
});
}
private static async Task AssertNotAllowedAsync(
HttpResponseMessage response,
string expectedError,
string expectedErrorDescription = null)
{
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var root = document.RootElement;
root.GetProperty("error").GetString().ShouldBe(expectedError);
if (expectedErrorDescription != null)
{
root.GetProperty("error_description").GetString().ShouldBe(expectedErrorDescription);
}
root.TryGetProperty("access_token", out _).ShouldBeFalse();
root.TryGetProperty("changePasswordToken", out _).ShouldBeFalse();
}
private static async Task<string> AssertPasswordChangeChallengeAsync(
HttpResponseMessage response,
string expectedErrorDescription)

34
modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/TestExternalLoginProvider.cs

@ -0,0 +1,34 @@
using System;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
namespace Volo.Abp.OpenIddict.Integration;
public class TestExternalLoginProvider : IExternalLoginProvider, ITransientDependency
{
public const string Name = "Test";
public const string Password = "external-1q2w3E*";
public Task<bool> TryAuthenticateAsync(string userName, string plainPassword)
{
return Task.FromResult(
userName == OpenIddictPasswordGrantTestData.UserName && plainPassword == Password
);
}
public Task<IdentityUser> CreateUserAsync(string userName, string providerName)
{
throw new NotSupportedException();
}
public Task UpdateUserAsync(IdentityUser user, string providerName)
{
return Task.CompletedTask;
}
public Task<bool> IsEnabledAsync()
{
return Task.FromResult(true);
}
}
Loading…
Cancel
Save