From b2fd3cf049c69e585fb621049fde55349865d132 Mon Sep 17 00:00:00 2001 From: maliming Date: Mon, 19 Oct 2026 15:22:18 +0800 Subject: [PATCH] Apply sign-in checks to external login providers --- docs/en/modules/elsa-pro.md | 2 + modules/account/Volo.Abp.Account.abpmdl | 4 + modules/account/Volo.Abp.Account.slnx | 1 + .../Account/Localization/Resources/ar.json | 2 + .../Account/Localization/Resources/cs.json | 2 + .../Account/Localization/Resources/da.json | 2 + .../Account/Localization/Resources/de.json | 2 + .../Account/Localization/Resources/el.json | 2 + .../Account/Localization/Resources/en-GB.json | 2 + .../Account/Localization/Resources/en.json | 2 + .../Account/Localization/Resources/es-mx.json | 2 + .../Account/Localization/Resources/es.json | 2 + .../Account/Localization/Resources/fa.json | 2 + .../Account/Localization/Resources/fi.json | 2 + .../Account/Localization/Resources/fr.json | 2 + .../Account/Localization/Resources/hi.json | 2 + .../Account/Localization/Resources/hr.json | 2 + .../Account/Localization/Resources/hu.json | 2 + .../Account/Localization/Resources/is.json | 2 + .../Account/Localization/Resources/it.json | 2 + .../Account/Localization/Resources/nl.json | 2 + .../Account/Localization/Resources/pl-PL.json | 2 + .../Account/Localization/Resources/pt-BR.json | 2 + .../Account/Localization/Resources/ro-RO.json | 2 + .../Account/Localization/Resources/ru.json | 2 + .../Account/Localization/Resources/sk.json | 2 + .../Account/Localization/Resources/sl.json | 2 + .../Account/Localization/Resources/sv.json | 2 + .../Account/Localization/Resources/tr.json | 2 + .../Account/Localization/Resources/vi.json | 2 + .../Localization/Resources/zh-Hans.json | 2 + .../Localization/Resources/zh-Hant.json | 2 + .../IdentityServerSupportedLoginModel.cs | 22 +- .../Pages/Account/AccountPageModel.cs | 32 ++ .../Pages/Account/Login.cshtml.cs | 35 ++- .../Pages/Account/Register.cshtml.cs | 28 +- .../Volo.Abp.Account.Web.Tests.abppkg | 4 + .../Volo.Abp.Account.Web.Tests.csproj | 23 ++ .../AbpAccountWebIdentityServerTestModule.cs | 40 +++ .../Abp/Account/Web/AbpAccountWebTestBase.cs | 181 +++++++++++ .../Account/Web/AbpAccountWebTestModule.cs | 46 +++ .../AccountPageModel_SignInCheck_Tests.cs | 81 +++++ ...rverSupportedLogin_NotAllowedUser_Tests.cs | 34 +++ .../Login_ExternalLoginCallback_Tests.cs | 78 +++++ .../Account/Login_NotAllowedUser_Tests.cs | 113 +++++++ .../Web/Pages/Account/Register_Tests.cs | 64 ++++ .../Account/Web/TestExternalLoginProvider.cs | 33 ++ .../Identity/AspNetCore/AbpSignInManager.cs | 47 ++- .../Identity/AspNetCore/AbpSignInResult.cs | 25 ++ .../Volo/Abp/Identity/IdentityUserManager.cs | 15 +- .../AbpIdentityAspNetCoreTestModule.cs | 1 + ...ger_PreSignInCheckWithoutPassword_Tests.cs | 130 ++++++++ .../DisabledFakeExternalLoginProvider.cs | 30 ++ .../AspNetCore/ExternalLoginProvider_Tests.cs | 116 ++++++- .../AspNetCore/FakeExternalLoginProvider.cs | 14 +- .../AbpResourceOwnerPasswordValidator.cs | 106 ++++++- ...nerPasswordValidatorExternalLogin_Tests.cs | 213 +++++++++++++ ...erPasswordValidatorPasswordChange_Tests.cs | 118 +++++++ .../DisabledTestExternalLoginProvider.cs | 31 ++ .../TestExternalLoginProvider.cs | 32 ++ .../OpenIddict/AbpErrorDescriptionConsts.cs | 2 + .../Controllers/TokenController.Password.cs | 103 ++++++- .../DisabledTestExternalLoginProvider.cs | 31 ++ ...ordGrantExternalLogin_Integration_Tests.cs | 287 ++++++++++++++++++ ...rdGrantPasswordChange_Integration_Tests.cs | 119 ++++++++ .../Integration/TestExternalLoginProvider.cs | 34 +++ 66 files changed, 2290 insertions(+), 43 deletions(-) create mode 100644 modules/account/test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.abppkg create mode 100644 modules/account/test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.csproj create mode 100644 modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebIdentityServerTestModule.cs create mode 100644 modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebTestBase.cs create mode 100644 modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebTestModule.cs create mode 100644 modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/AccountPageModel_SignInCheck_Tests.cs create mode 100644 modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/IdentityServerSupportedLogin_NotAllowedUser_Tests.cs create mode 100644 modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Login_ExternalLoginCallback_Tests.cs create mode 100644 modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Login_NotAllowedUser_Tests.cs create mode 100644 modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Register_Tests.cs create mode 100644 modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/TestExternalLoginProvider.cs create mode 100644 modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInResult.cs create mode 100644 modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpSignInManager_PreSignInCheckWithoutPassword_Tests.cs create mode 100644 modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/DisabledFakeExternalLoginProvider.cs create mode 100644 modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidatorExternalLogin_Tests.cs create mode 100644 modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/DisabledTestExternalLoginProvider.cs create mode 100644 modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/TestExternalLoginProvider.cs create mode 100644 modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/DisabledTestExternalLoginProvider.cs create mode 100644 modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/OpenIddictPasswordGrantExternalLogin_Integration_Tests.cs create mode 100644 modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/TestExternalLoginProvider.cs diff --git a/docs/en/modules/elsa-pro.md b/docs/en/modules/elsa-pro.md index ae7453b9da..509d879816 100644 --- a/docs/en/modules/elsa-pro.md +++ b/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) diff --git a/modules/account/Volo.Abp.Account.abpmdl b/modules/account/Volo.Abp.Account.abpmdl index 1c68c5785d..ca458aa738 100644 --- a/modules/account/Volo.Abp.Account.abpmdl +++ b/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" diff --git a/modules/account/Volo.Abp.Account.slnx b/modules/account/Volo.Abp.Account.slnx index 1beae2db60..ba16189d54 100644 --- a/modules/account/Volo.Abp.Account.slnx +++ b/modules/account/Volo.Abp.Account.slnx @@ -13,5 +13,6 @@ + diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ar.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ar.json index d3db345a9b..f45a9dd11c 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ar.json +++ b/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": "دخول", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/cs.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/cs.json index 6967ed0d61..05f59bd463 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/cs.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/da.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/da.json index 98cc684389..32580a54c6 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/da.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/de.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/de.json index 982a213753..2037e7219f 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/de.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/el.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/el.json index 594adbd31f..58f509af06 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/el.json +++ b/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": "Σύνδεση", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/en-GB.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/en-GB.json index 09a93dca6f..bf1c289c17 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/en-GB.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/en.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/en.json index a230495c87..942a9ba03b 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/en.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/es-mx.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/es-mx.json index f25046575a..56597cd568 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/es-mx.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/es.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/es.json index 814c41d218..8038cb9b5a 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/es.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fa.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fa.json index e431b84548..bfb2716d47 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fa.json +++ b/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": "ورود کاربران", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fi.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fi.json index 72acd91647..1b80ef496e 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fi.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fr.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fr.json index 73a53b4bee..961f8e784c 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/fr.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hi.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hi.json index 4264f6ebcf..3d1f7dc50f 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hi.json +++ b/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": "लॉग इन करें", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hr.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hr.json index 2262779dba..808904b23d 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hr.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hu.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hu.json index c2a8d3d354..5d7936c0ef 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/hu.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/is.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/is.json index cb38ff2b6a..1d78b2edec 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/is.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/it.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/it.json index a2a2a6db50..71e81d2410 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/it.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/nl.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/nl.json index a1c389d8a2..273171bed1 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/nl.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/pl-PL.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/pl-PL.json index 028fc3100b..8c9112c0de 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/pl-PL.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/pt-BR.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/pt-BR.json index e92a6f1d5b..811bba3c1b 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/pt-BR.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ro-RO.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ro-RO.json index 63fea101b1..20fc5333cf 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ro-RO.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ru.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ru.json index 834fd7707b..341a789315 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/ru.json +++ b/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": "Войти", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sk.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sk.json index 0965e8aaa3..b00ad3f02b 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sk.json +++ b/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ť", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sl.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sl.json index 63820bc60f..5c17e641e8 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sl.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sv.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sv.json index a03bf20e97..6f917392db 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/sv.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/tr.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/tr.json index 07309d4922..3853253467 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/tr.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/vi.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/vi.json index e29ba0d7b9..b3ede109b7 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/vi.json +++ b/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", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/zh-Hans.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/zh-Hans.json index 094798b95c..2a1ee5419e 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/zh-Hans.json +++ b/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": "登录", diff --git a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/zh-Hant.json b/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/zh-Hant.json index 1657ce4a49..7e1f1b302a 100644 --- a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/zh-Hant.json +++ b/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": "登入", diff --git a/modules/account/src/Volo.Abp.Account.Web.IdentityServer/Pages/Account/IdentityServerSupportedLoginModel.cs b/modules/account/src/Volo.Abp.Account.Web.IdentityServer/Pages/Account/IdentityServerSupportedLoginModel.cs index 676f37aa47..519d76ce9f 100644 --- a/modules/account/src/Volo.Abp.Account.Web.IdentityServer/Pages/Account/IdentityServerSupportedLoginModel.cs +++ b/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)) { diff --git a/modules/account/src/Volo.Abp.Account.Web/Pages/Account/AccountPageModel.cs b/modules/account/src/Volo.Abp.Account.Web/Pages/Account/AccountPageModel.cs index ebd556f8e2..38b7c8a67d 100644 --- a/modules/account/src/Volo.Abp.Account.Web/Pages/Account/AccountPageModel.cs +++ b/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 } } + /// + /// Checks the user before signing in without asking for the credentials of the user. + /// + /// Null if the user is allowed to sign in, otherwise the result why the user is denied. + protected virtual async Task CheckUserSignInAsync(IdentityUser user) + { + // The IdentityOptions property is hidden by the login page. + await LazyServiceProvider.LazyGetRequiredService>().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) diff --git a/modules/account/src/Volo.Abp.Account.Web/Pages/Account/Login.cshtml.cs b/modules/account/src/Volo.Abp.Account.Web/Pages/Account/Login.cshtml.cs index 57fcbe9e46..d53482daf0 100644 --- a/modules/account/src/Volo.Abp.Account.Web/Pages/Account/Login.cshtml.cs +++ b/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)); diff --git a/modules/account/src/Volo.Abp.Account.Web/Pages/Account/Register.cshtml.cs b/modules/account/src/Volo.Abp.Account.Web/Pages/Account/Register.cshtml.cs index 6b990253fc..ccdbc688c6 100644 --- a/modules/account/src/Volo.Abp.Account.Web/Pages/Account/Register.cshtml.cs +++ b/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); diff --git a/modules/account/test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.abppkg b/modules/account/test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.abppkg new file mode 100644 index 0000000000..4a37acf831 --- /dev/null +++ b/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" +} \ No newline at end of file diff --git a/modules/account/test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.csproj b/modules/account/test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.csproj new file mode 100644 index 0000000000..02dffc031f --- /dev/null +++ b/modules/account/test/Volo.Abp.Account.Web.Tests/Volo.Abp.Account.Web.Tests.csproj @@ -0,0 +1,23 @@ + + + + net10.0 + + + + + + + + + + + + + + + + + + + diff --git a/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebIdentityServerTestModule.cs b/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebIdentityServerTestModule.cs new file mode 100644 index 0000000000..da28ce7c2d --- /dev/null +++ b/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(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(); + interaction.GetAuthorizationContextAsync(Arg.Any()).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(); + context.Services.AddSingleton(Substitute.For()); + } +} diff --git a/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebTestBase.cs b/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebTestBase.cs new file mode 100644 index 0000000000..310cdb338a --- /dev/null +++ b/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 +{ +} + +public abstract class AbpAccountWebTestBase : AbpIntegratedTest + 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(); + } + + protected void SetSetting(string name, string value) + { + ((TestSettingStore)GetRequiredService()).GlobalValues[name] = value; + } + + protected async Task 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().Change(tenantId)) + using (var uow = GetRequiredService().Begin()) + { + var userManager = GetRequiredService(); + 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; + } + } + + /// + /// Creates the page like it is created for a request. + /// + /// The services of the request + /// The principal of the external login, if the request is a callback of it + protected TPage CreatePage(IServiceProvider serviceProvider, ClaimsPrincipal externalLoginPrincipal = null) + where TPage : AccountPageModel + { + var httpContext = new DefaultHttpContext { RequestServices = serviceProvider }; + serviceProvider.GetRequiredService().HttpContext = httpContext; + + var authenticationService = serviceProvider.GetRequiredService(); + authenticationService.AuthenticateAsync(Arg.Any(), Arg.Any()).Returns(AuthenticateResult.NoResult()); + if (externalLoginPrincipal != null) + { + var properties = new AuthenticationProperties(); + properties.Items["LoginProvider"] = ExternalLoginProvider; + authenticationService.AuthenticateAsync(Arg.Any(), IdentityConstants.ExternalScheme).Returns( + AuthenticateResult.Success(new AuthenticationTicket(externalLoginPrincipal, properties, IdentityConstants.ExternalScheme))); + } + + var page = serviceProvider.GetRequiredService(); + 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()); + page.Url = new UrlHelper(actionContext); + return page; + } + + protected bool IsSignedIn() + { + return GetRequiredService().ReceivedCalls().Any(call => + call.GetMethodInfo().Name == nameof(IAuthenticationService.SignInAsync) && + (string)call.GetArguments()[1] == IdentityConstants.ApplicationScheme); + } + + protected static string[] GetAlerts(IServiceProvider serviceProvider) + { + return serviceProvider.GetRequiredService().Alerts.Select(x => x.Text).ToArray(); + } + + protected string L(string name) + { + return GetRequiredService>()[name]; + } +} + +public class TestSignInManager : SignInManager +{ + public TestSignInManager( + UserManager userManager, + IHttpContextAccessor contextAccessor, + IUserClaimsPrincipalFactory claimsFactory, + IOptions optionsAccessor, + ILogger> logger, + IAuthenticationSchemeProvider schemes, + IUserConfirmation confirmation) + : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes, confirmation) + { + } +} diff --git a/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebTestModule.cs b/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/AbpAccountWebTestModule.cs new file mode 100644 index 0000000000..7970656b31 --- /dev/null +++ b/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()); + context.Services.Replace(ServiceDescriptor.Singleton(Substitute.For())); + context.Services.Replace(ServiceDescriptor.Singleton()); + } +} + +public class TestSettingStore : ISettingStore +{ + public Dictionary GlobalValues { get; } = new(); + + public Task GetOrNullAsync(string name, string providerName, string providerKey) + { + return Task.FromResult(GetOrNull(name, providerName)); + } + + public Task> 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; + } +} diff --git a/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/AccountPageModel_SignInCheck_Tests.cs b/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/AccountPageModel_SignInCheck_Tests.cs new file mode 100644 index 0000000000..a5d0e43dd9 --- /dev/null +++ b/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 CheckUserSignInAsync(params RestrictedUserState[] states) + { + var user = await CreateUserAsync(states: states); + + using var scope = ServiceProvider.CreateScope(); + var page = CreatePage(scope.ServiceProvider); + using (var uow = GetRequiredService().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>().ShouldBeAssignableTo(); + } +} + +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>().ShouldBeOfType(); + } +} + +public class TestAccountPageModel : AccountPageModel +{ + public Task CheckAsync(IdentityUser user) + { + return CheckUserSignInAsync(user); + } +} diff --git a/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/IdentityServerSupportedLogin_NotAllowedUser_Tests.cs b/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/IdentityServerSupportedLogin_NotAllowedUser_Tests.cs new file mode 100644 index 0000000000..4c97fe11ee --- /dev/null +++ b/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 +{ + [Fact] + public void Should_Use_Login_Page_Of_IdentityServer() + { + using var scope = ServiceProvider.CreateScope(); + CreatePage(scope.ServiceProvider).ShouldBeOfType(); + } +} + +// 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(options => + { + options.IsEnabled = true; + options.UserSharingStrategy = TenantUserSharingStrategy.Shared; + }); + } +} diff --git a/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Login_ExternalLoginCallback_Tests.cs b/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Login_ExternalLoginCallback_Tests.cs new file mode 100644 index 0000000000..52e303fb9c --- /dev/null +++ b/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(() => 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(scope.ServiceProvider, principal); + using (var uow = GetRequiredService().Begin()) + { + await page.OnGetExternalLoginCallbackAsync("/"); + await uow.CompleteAsync(); + } + } + + private async Task FindByLoginAsync(string providerKey) + { + using (var uow = GetRequiredService().Begin()) + { + return await GetRequiredService().FindByLoginAsync(ExternalLoginProvider, providerKey); + } + } +} + +public class Login_ExternalLoginCallback_ReplacedSignInManager_Tests : Login_ExternalLoginCallback_Tests +{ + protected override void AfterAddApplication(IServiceCollection services) + { + ReplaceSignInManager(services); + } +} diff --git a/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Login_NotAllowedUser_Tests.cs b/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Login_NotAllowedUser_Tests.cs new file mode 100644 index 0000000000..260577bdee --- /dev/null +++ b/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 : AbpAccountWebTestBase + where TStartupModule : IAbpModule +{ + protected virtual Guid? UserTenantId => null; + + protected override void AfterAddApplication(IServiceCollection services) + { + services.Configure(options => + { + options.ExternalLoginProviders.Add(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 LoginAsync(string userName, string password) + { + using var scope = ServiceProvider.CreateScope(); + var page = CreatePage(scope.ServiceProvider); + page.LoginInput = new LoginModel.LoginInputModel { UserNameOrEmailAddress = userName, Password = password }; + + using (var uow = GetRequiredService().Begin()) + { + await page.OnPostAsync("Login"); + await uow.CompleteAsync(); + } + + IsSignedIn().ShouldBeFalse(); + return GetAlerts(scope.ServiceProvider); + } +} + +public class Login_NotAllowedUser_Tests : Login_NotAllowedUser_TestBase +{ +} + +// 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(options => + { + options.IsEnabled = true; + options.UserSharingStrategy = TenantUserSharingStrategy.Shared; + }); + } +} diff --git a/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Register_Tests.cs b/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/Pages/Account/Register_Tests.cs new file mode 100644 index 0000000000..274a687502 --- /dev/null +++ b/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(); + 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(); + 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(scope.ServiceProvider); + page.Input = new RegisterModel.PostInput { UserName = userName, EmailAddress = userName + "@abp.io", Password = Password }; + page.ReturnUrl = "/"; + + using (var uow = GetRequiredService().Begin()) + { + var result = await page.OnPostAsync(); + await uow.CompleteAsync(); + + (await GetRequiredService().FindByNameAsync(userName)).ShouldNotBeNull(); + return (result, GetAlerts(scope.ServiceProvider)); + } + } +} + +public class Register_ReplacedSignInManager_Tests : Register_Tests +{ + protected override void AfterAddApplication(IServiceCollection services) + { + ReplaceSignInManager(services); + } +} diff --git a/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/TestExternalLoginProvider.cs b/modules/account/test/Volo.Abp.Account.Web.Tests/Volo/Abp/Account/Web/TestExternalLoginProvider.cs new file mode 100644 index 0000000000..ee9e093945 --- /dev/null +++ b/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 TryAuthenticateAsync(string userName, string plainPassword) + { + return Task.FromResult(plainPassword == Password); + } + + public Task CreateUserAsync(string userName, string providerName) + { + throw new NotSupportedException(); + } + + public Task UpdateUserAsync(IdentityUser user, string providerName) + { + return Task.CompletedTask; + } + + public Task IsEnabledAsync() + { + return Task.FromResult(true); + } +} diff --git a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInManager.cs b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInManager.cs index 34bf4e0c8d..760e8f4e9b 100644 --- a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInManager.cs +++ b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInManager.cs @@ -19,6 +19,11 @@ public class AbpSignInManager : SignInManager protected ICurrentTenant CurrentTenant { get; } protected IOptions IdentityOptionsAccessor { get; } + /// + /// Set while checks a user with a shared password. + /// + protected bool IsPasswordChangePeriodIgnored { get; set; } + public AbpSignInManager( IdentityUserManager userManager, IHttpContextAccessor contextAccessor, @@ -57,7 +62,8 @@ public class AbpSignInManager : SignInManager 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 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 return await PreSignInCheck(user); } + /// + /// 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. + /// + /// The user + /// Null if the user should be allowed to sign in, otherwise the SignInResult why they should be denied. + public virtual async Task CallPreSignInCheckWithoutPasswordAsync(IdentityUser user) + { + var isPasswordChangePeriodIgnored = IsPasswordChangePeriodIgnored; + IsPasswordChangePeriodIgnored = IdentityUserManager.IsUserSharingEnabled(); + try + { + return await PreSignInCheck(user); + } + finally + { + IsPasswordChangePeriodIgnored = isPasswordChangePeriodIgnored; + } + } + protected override async Task PreSignInCheck(IdentityUser user) { if (!user.IsActive) @@ -225,7 +268,7 @@ public class AbpSignInManager : SignInManager return SignInResult.NotAllowed; } - if (await IdentityUserManager.ShouldPeriodicallyChangePasswordAsync(user)) + if (!IsPasswordChangePeriodIgnored && await IdentityUserManager.ShouldPeriodicallyChangePasswordAsync(user)) { return SignInResult.NotAllowed; } diff --git a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInResult.cs b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInResult.cs new file mode 100644 index 0000000000..12118d9e79 --- /dev/null +++ b/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 +{ + /// + /// 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. + /// + 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(); + } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserManager.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserManager.cs index 2ea747e868..7b982dd046 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserManager.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserManager.cs @@ -689,9 +689,14 @@ public class IdentityUserManager : UserManager, IDomainService throw new AbpIdentityResultException(IdentityResult.Failed(ErrorDescriber.InvalidUserName(userName))); } + public virtual bool IsUserSharingEnabled() + { + return MultiTenancyOptions.Value.UserSharingStrategy == TenantUserSharingStrategy.Shared; + } + public virtual async Task FindSharedUserByEmailAsync(string email) { - if (MultiTenancyOptions.Value.UserSharingStrategy == TenantUserSharingStrategy.Isolated) + if (!IsUserSharingEnabled()) { return await base.FindByEmailAsync(email); } @@ -722,7 +727,7 @@ public class IdentityUserManager : UserManager, IDomainService public virtual async Task FindSharedUserByNameAsync(string userName) { - if (MultiTenancyOptions.Value.UserSharingStrategy == TenantUserSharingStrategy.Isolated) + if (!IsUserSharingEnabled()) { return await base.FindByNameAsync(userName); } @@ -753,7 +758,7 @@ public class IdentityUserManager : UserManager, IDomainService public virtual async Task 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, IDomainService public virtual async Task FindSharedUserByPasskeyIdAsync(byte[] credentialId) { - if (MultiTenancyOptions.Value.UserSharingStrategy == TenantUserSharingStrategy.Isolated) + if (!IsUserSharingEnabled()) { return await base.FindByPasskeyIdAsync(credentialId); } @@ -813,7 +818,7 @@ public class IdentityUserManager : UserManager, IDomainService public virtual async Task FindSharedUserByIdAsync(string userId) { - if (MultiTenancyOptions.Value.UserSharingStrategy == TenantUserSharingStrategy.Isolated) + if (!IsUserSharingEnabled()) { return await base.FindByIdAsync(userId); } diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestModule.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestModule.cs index a7dba2c7d0..c02c3b21fe 100644 --- a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestModule.cs +++ b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestModule.cs @@ -29,6 +29,7 @@ public class AbpIdentityAspNetCoreTestModule : AbpModule Configure(options => { options.ExternalLoginProviders.Add(FakeExternalLoginProvider.Name); + options.ExternalLoginProviders.Add(DisabledFakeExternalLoginProvider.Name); }); Configure(options => diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpSignInManager_PreSignInCheckWithoutPassword_Tests.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpSignInManager_PreSignInCheckWithoutPassword_Tests.cs new file mode 100644 index 0000000000..412cb8f1f3 --- /dev/null +++ b/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(ServiceProvider)); + + result.ShouldBe(SignInResult.NotAllowed); + } + + private async Task CheckUserWithExpiredPasswordAsync( + TenantUserSharingStrategy strategy, + Func configureUser = null, + AbpSignInManager signInManager = null) + { + GetRequiredService>().Value.UserSharingStrategy = strategy; + TestSettingValueProvider.AddSetting(IdentitySettingNames.Password.ForceUsersToPeriodicallyChangePassword, true.ToString()); + TestSettingValueProvider.AddSetting(IdentitySettingNames.Password.PasswordChangePeriodDays, 1.ToString()); + + try + { + using (var uow = GetRequiredService().Begin()) + { + var userManager = GetRequiredService(); + 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()).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 claimsFactory, + IOptions optionsAccessor, + ILogger> logger, + IAuthenticationSchemeProvider schemes, + IUserConfirmation confirmation, + IOptions options, + ISettingProvider settingProvider, + ICurrentTenant currentTenant) + : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes, confirmation, options, settingProvider, currentTenant) + { + } + + protected override async Task PreSignInCheck(IdentityUser user) + { + return await base.PreSignInCheck(user) ?? SignInResult.NotAllowed; + } +} diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/DisabledFakeExternalLoginProvider.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/DisabledFakeExternalLoginProvider.cs new file mode 100644 index 0000000000..ccbd30640c --- /dev/null +++ b/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 TryAuthenticateAsync(string userName, string plainPassword) + { + throw new InvalidOperationException("A disabled external login provider should not be used."); + } + + public Task 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 IsEnabledAsync() + { + return Task.FromResult(false); + } +} diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/ExternalLoginProvider_Tests.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/ExternalLoginProvider_Tests.cs index 96f526da3e..b828de9148 100644 --- a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/ExternalLoginProvider_Tests.cs +++ b/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().FindByNameAsync("disabled_ext_user")).ShouldBeNull(); + } + + private async Task CreateExternalUserAsync( + Func configureUser, + string userName = "ext_user") + { + var result = await GetResponseAsStringAsync( + $"api/signin-test/password?userName={userName}&password=abc" + ); + + result.ShouldBe("Succeeded"); + + using (var uow = GetRequiredService().Begin()) + { + var userManager = GetRequiredService(); + var user = await userManager.FindByNameAsync(userName); + await configureUser(userManager, user); + await uow.CompleteAsync(); + } + } + private async Task CheckUserAsync() { var userRepository = GetRequiredService(); diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/FakeExternalLoginProvider.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/FakeExternalLoginProvider.cs index fbfc0e2ef6..a473ed105f 100644 --- a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/FakeExternalLoginProvider.cs +++ b/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 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 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(); diff --git a/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidator.cs b/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidator.cs index dd52f90719..986f5901ef 100644 --- a/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidator.cs +++ b/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 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 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"]; diff --git a/modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidatorExternalLogin_Tests.cs b/modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidatorExternalLogin_Tests.cs new file mode 100644 index 0000000000..172deefa56 --- /dev/null +++ b/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(options => + { + options.ExternalLoginProviders.Add(TestExternalLoginProvider.Name); + options.ExternalLoginProviders.Add(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().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(); + 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 action) + { + return WithUnitOfWorkAsync(async serviceProvider => + { + var userManager = serviceProvider.GetRequiredService(); + 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(); + } +} diff --git a/modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidatorPasswordChange_Tests.cs b/modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidatorPasswordChange_Tests.cs index 8e8db23773..1dfbc8a750 100644 --- a/modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidatorPasswordChange_Tests.cs +++ b/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(); + 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 action) + { + return WithUnitOfWorkAsync(async serviceProvider => + { + var userManager = serviceProvider.GetRequiredService(); + 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) diff --git a/modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/DisabledTestExternalLoginProvider.cs b/modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/DisabledTestExternalLoginProvider.cs new file mode 100644 index 0000000000..c6470e43c4 --- /dev/null +++ b/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 TryAuthenticateAsync(string userName, string plainPassword) + { + throw new InvalidOperationException("A disabled external login provider should not be used."); + } + + public Task 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 IsEnabledAsync() + { + return Task.FromResult(false); + } +} diff --git a/modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/TestExternalLoginProvider.cs b/modules/identityserver/test/Volo.Abp.IdentityServer.Domain.Tests/Volo/Abp/IdentityServer/AspNetIdentity/TestExternalLoginProvider.cs new file mode 100644 index 0000000000..2bdc98ab97 --- /dev/null +++ b/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 TryAuthenticateAsync(string userName, string plainPassword) + { + return Task.FromResult(plainPassword == Password); + } + + public Task CreateUserAsync(string userName, string providerName) + { + throw new NotSupportedException(); + } + + public Task UpdateUserAsync(IdentityUser user, string providerName) + { + return Task.CompletedTask; + } + + public Task IsEnabledAsync() + { + return Task.FromResult(true); + } +} diff --git a/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpErrorDescriptionConsts.cs b/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpErrorDescriptionConsts.cs index 93839fa6e3..b4fb6bbbf9 100644 --- a/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/AbpErrorDescriptionConsts.cs +++ b/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"; } diff --git a/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/Controllers/TokenController.Password.cs b/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/Controllers/TokenController.Password.cs index 74b53a7774..8ea14ddfad 100644 --- a/modules/openiddict/src/Volo.Abp.OpenIddict.AspNetCore/Volo/Abp/OpenIddict/Controllers/TokenController.Password.cs +++ b/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 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 + { + [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 + { + [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 + { + [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)) diff --git a/modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/DisabledTestExternalLoginProvider.cs b/modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/DisabledTestExternalLoginProvider.cs new file mode 100644 index 0000000000..09b427522e --- /dev/null +++ b/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 TryAuthenticateAsync(string userName, string plainPassword) + { + throw new InvalidOperationException("A disabled external login provider should not be used."); + } + + public Task 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 IsEnabledAsync() + { + return Task.FromResult(false); + } +} diff --git a/modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/OpenIddictPasswordGrantExternalLogin_Integration_Tests.cs b/modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/OpenIddictPasswordGrantExternalLogin_Integration_Tests.cs new file mode 100644 index 0000000000..164110635c --- /dev/null +++ b/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(options => + { + options.ExternalLoginProviders.Add(TestExternalLoginProvider.Name); + options.ExternalLoginProviders.Add(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 + { + ["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 + { + ["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(); + var user = await userManager.FindByNameAsync(OpenIddictPasswordGrantTestData.UserName); + return (await userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 1)).Single(); + }); + + var response = await RequestPasswordTokenAsync(new Dictionary + { + ["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 + { + ["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 + { + ["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 + { + ["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(); + 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 + { + ["NewPassword"] = NewPassword, + ["ChangePasswordToken"] = changePasswordToken + }, TestExternalLoginProvider.Password); + + await AssertErrorAsync(response, "invalid_grant", "ExternalLoginPasswordChangeRequired"); + + await WithUnitOfWorkAsync(async serviceProvider => + { + var userManager = serviceProvider.GetRequiredService(); + 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(); + 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().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 action) + { + return WithUnitOfWorkAsync(async serviceProvider => + { + var userManager = serviceProvider.GetRequiredService(); + 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(); + } +} diff --git a/modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/OpenIddictPasswordGrantPasswordChange_Integration_Tests.cs b/modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/OpenIddictPasswordGrantPasswordChange_Integration_Tests.cs index a88a865568..8a0872e27b 100644 --- a/modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/OpenIddictPasswordGrantPasswordChange_Integration_Tests.cs +++ b/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 + { + ["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(); + 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 action) + { + return WithUnitOfWorkAsync(async serviceProvider => + { + var userManager = serviceProvider.GetRequiredService(); + 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 AssertPasswordChangeChallengeAsync( HttpResponseMessage response, string expectedErrorDescription) diff --git a/modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/TestExternalLoginProvider.cs b/modules/openiddict/test/Volo.Abp.OpenIddict.AspNetCore.Tests/Volo/Abp/OpenIddict/Integration/TestExternalLoginProvider.cs new file mode 100644 index 0000000000..549c476cc4 --- /dev/null +++ b/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 TryAuthenticateAsync(string userName, string plainPassword) + { + return Task.FromResult( + userName == OpenIddictPasswordGrantTestData.UserName && plainPassword == Password + ); + } + + public Task CreateUserAsync(string userName, string providerName) + { + throw new NotSupportedException(); + } + + public Task UpdateUserAsync(IdentityUser user, string providerName) + { + return Task.CompletedTask; + } + + public Task IsEnabledAsync() + { + return Task.FromResult(true); + } +}