mirror of https://github.com/abpframework/abp.git
66 changed files with 2290 additions and 43 deletions
@ -0,0 +1,4 @@ |
|||
{ |
|||
"role": "lib.test", |
|||
"projectId": "e7ac0de5-6c69-4e07-8d24-6082c3dd9c1b" |
|||
} |
|||
@ -0,0 +1,23 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk"> |
|||
|
|||
<PropertyGroup> |
|||
<TargetFramework>net10.0</TargetFramework> |
|||
<RootNamespace /> |
|||
</PropertyGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Microsoft.NET.Test.Sdk" /> |
|||
<PackageReference Include="NSubstitute" /> |
|||
<PackageReference Include="Shouldly" /> |
|||
<PackageReference Include="xunit" /> |
|||
<PackageReference Include="xunit.extensibility.execution" /> |
|||
<PackageReference Include="xunit.runner.visualstudio" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<ProjectReference Include="..\..\src\Volo.Abp.Account.Web\Volo.Abp.Account.Web.csproj" /> |
|||
<ProjectReference Include="..\..\src\Volo.Abp.Account.Web.IdentityServer\Volo.Abp.Account.Web.IdentityServer.csproj" /> |
|||
<ProjectReference Include="..\Volo.Abp.Account.Application.Tests\Volo.Abp.Account.Application.Tests.csproj" /> |
|||
</ItemGroup> |
|||
|
|||
</Project> |
|||
@ -0,0 +1,40 @@ |
|||
using IdentityServer4.Models; |
|||
using IdentityServer4.Services; |
|||
using Microsoft.AspNetCore.Authentication; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.DependencyInjection.Extensions; |
|||
using NSubstitute; |
|||
using Volo.Abp.IdentityServer; |
|||
using Volo.Abp.Modularity; |
|||
|
|||
namespace Volo.Abp.Account.Web; |
|||
|
|||
[DependsOn( |
|||
typeof(AbpAccountWebTestModule), |
|||
typeof(AbpAccountWebIdentityServerModule) |
|||
)] |
|||
public class AbpAccountWebIdentityServerTestModule : AbpModule |
|||
{ |
|||
public override void PreConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
// The other tests of the assembly run in the same process, so the static claim types are not changed.
|
|||
PreConfigure<AbpIdentityServerBuilderOptions>(options => |
|||
{ |
|||
options.UpdateAbpClaimTypes = false; |
|||
options.UpdateJwtSecurityTokenHandlerDefaultInboundClaimTypeMap = false; |
|||
options.AddDeveloperSigningCredential = false; |
|||
}); |
|||
} |
|||
|
|||
public override void ConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
// There is no authorize request in the tests.
|
|||
var interaction = Substitute.For<IIdentityServerInteractionService>(); |
|||
interaction.GetAuthorizationContextAsync(Arg.Any<string>()).Returns((AuthorizationRequest)null); |
|||
context.Services.Replace(ServiceDescriptor.Singleton(interaction)); |
|||
|
|||
// IdentityServer decorates the authentication service, the substitute of the tests is used instead.
|
|||
context.Services.RemoveAll<IAuthenticationService>(); |
|||
context.Services.AddSingleton(Substitute.For<IAuthenticationService>()); |
|||
} |
|||
} |
|||
@ -0,0 +1,181 @@ |
|||
using System; |
|||
using System.Linq; |
|||
using System.Security.Claims; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Authentication; |
|||
using Microsoft.AspNetCore.Http; |
|||
using Microsoft.AspNetCore.Identity; |
|||
using Microsoft.AspNetCore.Mvc; |
|||
using Microsoft.AspNetCore.Mvc.ModelBinding; |
|||
using Microsoft.AspNetCore.Mvc.RazorPages; |
|||
using Microsoft.AspNetCore.Mvc.Routing; |
|||
using Microsoft.AspNetCore.Mvc.ViewFeatures; |
|||
using Microsoft.AspNetCore.Routing; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Localization; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Extensions.Options; |
|||
using NSubstitute; |
|||
using Volo.Abp.Account.Localization; |
|||
using Volo.Abp.Account.Web.Pages.Account; |
|||
using Volo.Abp.AspNetCore.Mvc.UI.Alerts; |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.Identity.Settings; |
|||
using Volo.Abp.Modularity; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Volo.Abp.Settings; |
|||
using Volo.Abp.Testing; |
|||
using Volo.Abp.Uow; |
|||
using IdentityRole = Volo.Abp.Identity.IdentityRole; |
|||
using IdentityUser = Volo.Abp.Identity.IdentityUser; |
|||
|
|||
namespace Volo.Abp.Account.Web; |
|||
|
|||
public enum RestrictedUserState |
|||
{ |
|||
Inactive, |
|||
LockedOut, |
|||
RequiresConfirmation, |
|||
MustChangePassword, |
|||
PasswordExpired |
|||
} |
|||
|
|||
public abstract class AbpAccountWebTestBase : AbpAccountWebTestBase<AbpAccountWebTestModule> |
|||
{ |
|||
} |
|||
|
|||
public abstract class AbpAccountWebTestBase<TStartupModule> : AbpIntegratedTest<TStartupModule> |
|||
where TStartupModule : IAbpModule |
|||
{ |
|||
protected const string Password = "1q2w3E*"; |
|||
protected const string ExternalLoginProvider = "TestProvider"; |
|||
|
|||
protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options) |
|||
{ |
|||
options.UseAutofac(); |
|||
} |
|||
|
|||
// The sign-in manager of an application, replaced like it is documented for ASP.NET Core Identity.
|
|||
protected static void ReplaceSignInManager(IServiceCollection services) |
|||
{ |
|||
new IdentityBuilder(typeof(IdentityUser), typeof(IdentityRole), services).AddSignInManager<TestSignInManager>(); |
|||
} |
|||
|
|||
protected void SetSetting(string name, string value) |
|||
{ |
|||
((TestSettingStore)GetRequiredService<ISettingStore>()).GlobalValues[name] = value; |
|||
} |
|||
|
|||
protected async Task<IdentityUser> CreateUserAsync(Guid? tenantId = null, params RestrictedUserState[] states) |
|||
{ |
|||
if (states.Contains(RestrictedUserState.RequiresConfirmation)) |
|||
{ |
|||
SetSetting(IdentitySettingNames.SignIn.RequireConfirmedEmail, "true"); |
|||
} |
|||
|
|||
if (states.Contains(RestrictedUserState.PasswordExpired)) |
|||
{ |
|||
SetSetting(IdentitySettingNames.Password.ForceUsersToPeriodicallyChangePassword, "true"); |
|||
SetSetting(IdentitySettingNames.Password.PasswordChangePeriodDays, "1"); |
|||
} |
|||
|
|||
using (GetRequiredService<ICurrentTenant>().Change(tenantId)) |
|||
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin()) |
|||
{ |
|||
var userManager = GetRequiredService<IdentityUserManager>(); |
|||
var userName = "user-" + Guid.NewGuid().ToString("N"); |
|||
var user = new IdentityUser(Guid.NewGuid(), userName, userName + "@abp.io", tenantId); |
|||
user.SetEmailConfirmed(!states.Contains(RestrictedUserState.RequiresConfirmation)); |
|||
(await userManager.CreateAsync(user, Password)).CheckErrors(); |
|||
|
|||
foreach (var state in states) |
|||
{ |
|||
switch (state) |
|||
{ |
|||
case RestrictedUserState.Inactive: |
|||
user.SetIsActive(false); |
|||
break; |
|||
case RestrictedUserState.LockedOut: |
|||
(await userManager.SetLockoutEnabledAsync(user, true)).CheckErrors(); |
|||
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors(); |
|||
break; |
|||
case RestrictedUserState.MustChangePassword: |
|||
user.SetShouldChangePasswordOnNextLogin(true); |
|||
break; |
|||
case RestrictedUserState.PasswordExpired: |
|||
user.SetLastPasswordChangeTime(DateTimeOffset.UtcNow.AddDays(-30)); |
|||
break; |
|||
} |
|||
} |
|||
|
|||
(await userManager.UpdateAsync(user)).CheckErrors(); |
|||
await uow.CompleteAsync(); |
|||
return user; |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Creates the page like it is created for a request.
|
|||
/// </summary>
|
|||
/// <param name="serviceProvider">The services of the request</param>
|
|||
/// <param name="externalLoginPrincipal">The principal of the external login, if the request is a callback of it</param>
|
|||
protected TPage CreatePage<TPage>(IServiceProvider serviceProvider, ClaimsPrincipal externalLoginPrincipal = null) |
|||
where TPage : AccountPageModel |
|||
{ |
|||
var httpContext = new DefaultHttpContext { RequestServices = serviceProvider }; |
|||
serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext = httpContext; |
|||
|
|||
var authenticationService = serviceProvider.GetRequiredService<IAuthenticationService>(); |
|||
authenticationService.AuthenticateAsync(Arg.Any<HttpContext>(), Arg.Any<string>()).Returns(AuthenticateResult.NoResult()); |
|||
if (externalLoginPrincipal != null) |
|||
{ |
|||
var properties = new AuthenticationProperties(); |
|||
properties.Items["LoginProvider"] = ExternalLoginProvider; |
|||
authenticationService.AuthenticateAsync(Arg.Any<HttpContext>(), IdentityConstants.ExternalScheme).Returns( |
|||
AuthenticateResult.Success(new AuthenticationTicket(externalLoginPrincipal, properties, IdentityConstants.ExternalScheme))); |
|||
} |
|||
|
|||
var page = serviceProvider.GetRequiredService<TPage>(); |
|||
var modelState = new ModelStateDictionary(); |
|||
var actionContext = new ActionContext(httpContext, new RouteData(), new PageActionDescriptor(), modelState); |
|||
page.PageContext = new PageContext(actionContext) |
|||
{ |
|||
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), modelState) |
|||
}; |
|||
page.TempData = new TempDataDictionary(httpContext, Substitute.For<ITempDataProvider>()); |
|||
page.Url = new UrlHelper(actionContext); |
|||
return page; |
|||
} |
|||
|
|||
protected bool IsSignedIn() |
|||
{ |
|||
return GetRequiredService<IAuthenticationService>().ReceivedCalls().Any(call => |
|||
call.GetMethodInfo().Name == nameof(IAuthenticationService.SignInAsync) && |
|||
(string)call.GetArguments()[1] == IdentityConstants.ApplicationScheme); |
|||
} |
|||
|
|||
protected static string[] GetAlerts(IServiceProvider serviceProvider) |
|||
{ |
|||
return serviceProvider.GetRequiredService<IAlertManager>().Alerts.Select(x => x.Text).ToArray(); |
|||
} |
|||
|
|||
protected string L(string name) |
|||
{ |
|||
return GetRequiredService<IStringLocalizer<AccountResource>>()[name]; |
|||
} |
|||
} |
|||
|
|||
public class TestSignInManager : SignInManager<IdentityUser> |
|||
{ |
|||
public TestSignInManager( |
|||
UserManager<IdentityUser> userManager, |
|||
IHttpContextAccessor contextAccessor, |
|||
IUserClaimsPrincipalFactory<IdentityUser> claimsFactory, |
|||
IOptions<IdentityOptions> optionsAccessor, |
|||
ILogger<SignInManager<IdentityUser>> logger, |
|||
IAuthenticationSchemeProvider schemes, |
|||
IUserConfirmation<IdentityUser> confirmation) |
|||
: base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes, confirmation) |
|||
{ |
|||
} |
|||
} |
|||
@ -0,0 +1,46 @@ |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Authentication; |
|||
using Microsoft.AspNetCore.Hosting; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.DependencyInjection.Extensions; |
|||
using NSubstitute; |
|||
using Volo.Abp.Modularity; |
|||
using Volo.Abp.Settings; |
|||
|
|||
namespace Volo.Abp.Account.Web; |
|||
|
|||
[DependsOn( |
|||
typeof(AbpAccountApplicationTestModule), |
|||
typeof(AbpAccountWebModule) |
|||
)] |
|||
public class AbpAccountWebTestModule : AbpModule |
|||
{ |
|||
public override void ConfigureServices(ServiceConfigurationContext context) |
|||
{ |
|||
context.Services.AddSingleton(Substitute.For<IWebHostEnvironment>()); |
|||
context.Services.Replace(ServiceDescriptor.Singleton(Substitute.For<IAuthenticationService>())); |
|||
context.Services.Replace(ServiceDescriptor.Singleton<ISettingStore, TestSettingStore>()); |
|||
} |
|||
} |
|||
|
|||
public class TestSettingStore : ISettingStore |
|||
{ |
|||
public Dictionary<string, string> GlobalValues { get; } = new(); |
|||
|
|||
public Task<string> GetOrNullAsync(string name, string providerName, string providerKey) |
|||
{ |
|||
return Task.FromResult(GetOrNull(name, providerName)); |
|||
} |
|||
|
|||
public Task<List<SettingValue>> GetAllAsync(string[] names, string providerName, string providerKey) |
|||
{ |
|||
return Task.FromResult(names.Select(name => new SettingValue(name, GetOrNull(name, providerName))).ToList()); |
|||
} |
|||
|
|||
private string GetOrNull(string name, string providerName) |
|||
{ |
|||
return providerName == GlobalSettingValueProvider.ProviderName ? GlobalValues.GetOrDefault(name) : null; |
|||
} |
|||
} |
|||
@ -0,0 +1,81 @@ |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Identity; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.Identity.AspNetCore; |
|||
using Volo.Abp.Uow; |
|||
using Xunit; |
|||
using IdentityUser = Volo.Abp.Identity.IdentityUser; |
|||
|
|||
namespace Volo.Abp.Account.Web.Pages.Account; |
|||
|
|||
// Some pages sign in a user without asking for the credentials of the user, for example after the registration.
|
|||
public abstract class AccountPageModel_SignInCheck_TestBase : AbpAccountWebTestBase |
|||
{ |
|||
[Fact] |
|||
public async Task Should_Allow_User() |
|||
{ |
|||
(await CheckUserSignInAsync()).ShouldBeNull(); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData(RestrictedUserState.Inactive)] |
|||
[InlineData(RestrictedUserState.RequiresConfirmation)] |
|||
[InlineData(RestrictedUserState.MustChangePassword)] |
|||
[InlineData(RestrictedUserState.PasswordExpired)] |
|||
public async Task Should_Not_Allow_Restricted_User(RestrictedUserState state) |
|||
{ |
|||
(await CheckUserSignInAsync(state)).ShouldBe(SignInResult.NotAllowed); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Allow_Locked_Out_User() |
|||
{ |
|||
(await CheckUserSignInAsync(RestrictedUserState.LockedOut)).ShouldBe(SignInResult.LockedOut); |
|||
} |
|||
|
|||
protected async Task<SignInResult> CheckUserSignInAsync(params RestrictedUserState[] states) |
|||
{ |
|||
var user = await CreateUserAsync(states: states); |
|||
|
|||
using var scope = ServiceProvider.CreateScope(); |
|||
var page = CreatePage<TestAccountPageModel>(scope.ServiceProvider); |
|||
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin()) |
|||
{ |
|||
var result = await page.CheckAsync(user); |
|||
await uow.CompleteAsync(); |
|||
return result; |
|||
} |
|||
} |
|||
} |
|||
|
|||
public class AccountPageModel_SignInCheck_Tests : AccountPageModel_SignInCheck_TestBase |
|||
{ |
|||
[Fact] |
|||
public void Should_Use_AbpSignInManager() |
|||
{ |
|||
GetRequiredService<SignInManager<IdentityUser>>().ShouldBeAssignableTo<AbpSignInManager>(); |
|||
} |
|||
} |
|||
|
|||
public class AccountPageModel_SignInCheck_ReplacedSignInManager_Tests : AccountPageModel_SignInCheck_TestBase |
|||
{ |
|||
protected override void AfterAddApplication(IServiceCollection services) |
|||
{ |
|||
ReplaceSignInManager(services); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Should_Use_Replaced_SignInManager() |
|||
{ |
|||
GetRequiredService<SignInManager<IdentityUser>>().ShouldBeOfType<TestSignInManager>(); |
|||
} |
|||
} |
|||
|
|||
public class TestAccountPageModel : AccountPageModel |
|||
{ |
|||
public Task<SignInResult> CheckAsync(IdentityUser user) |
|||
{ |
|||
return CheckUserSignInAsync(user); |
|||
} |
|||
} |
|||
@ -0,0 +1,34 @@ |
|||
using System; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Account.Web.Pages.Account; |
|||
|
|||
// The login page is replaced by the login page of IdentityServer.
|
|||
public class IdentityServerSupportedLogin_NotAllowedUser_Tests : Login_NotAllowedUser_TestBase<AbpAccountWebIdentityServerTestModule> |
|||
{ |
|||
[Fact] |
|||
public void Should_Use_Login_Page_Of_IdentityServer() |
|||
{ |
|||
using var scope = ServiceProvider.CreateScope(); |
|||
CreatePage<LoginModel>(scope.ServiceProvider).ShouldBeOfType<IdentityServerSupportedLoginModel>(); |
|||
} |
|||
} |
|||
|
|||
// The user of a tenant logs in on the host side.
|
|||
public class IdentityServerSupportedLogin_NotAllowedUser_SharedUser_Tests : IdentityServerSupportedLogin_NotAllowedUser_Tests |
|||
{ |
|||
protected override Guid? UserTenantId { get; } = Guid.NewGuid(); |
|||
|
|||
protected override void AfterAddApplication(IServiceCollection services) |
|||
{ |
|||
base.AfterAddApplication(services); |
|||
services.Configure<AbpMultiTenancyOptions>(options => |
|||
{ |
|||
options.IsEnabled = true; |
|||
options.UserSharingStrategy = TenantUserSharingStrategy.Shared; |
|||
}); |
|||
} |
|||
} |
|||
@ -0,0 +1,78 @@ |
|||
using System; |
|||
using System.Security.Claims; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Identity; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.Uow; |
|||
using Xunit; |
|||
using IdentityUser = Volo.Abp.Identity.IdentityUser; |
|||
|
|||
namespace Volo.Abp.Account.Web.Pages.Account; |
|||
|
|||
// The external login is not linked to a user yet, the user is found by the email of the external login.
|
|||
public class Login_ExternalLoginCallback_Tests : AbpAccountWebTestBase |
|||
{ |
|||
[Fact] |
|||
public async Task Should_Sign_In_User_That_Is_Found_By_Email() |
|||
{ |
|||
var user = await CreateUserAsync(); |
|||
var providerKey = Guid.NewGuid().ToString("N"); |
|||
|
|||
await CallbackAsync(user, providerKey); |
|||
|
|||
IsSignedIn().ShouldBeTrue(); |
|||
(await FindByLoginAsync(providerKey))?.Id.ShouldBe(user.Id); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData(RestrictedUserState.Inactive)] |
|||
[InlineData(RestrictedUserState.LockedOut)] |
|||
[InlineData(RestrictedUserState.RequiresConfirmation)] |
|||
[InlineData(RestrictedUserState.MustChangePassword)] |
|||
[InlineData(RestrictedUserState.PasswordExpired)] |
|||
public async Task Should_Not_Sign_In_Restricted_User_That_Is_Found_By_Email(RestrictedUserState state) |
|||
{ |
|||
var user = await CreateUserAsync(states: state); |
|||
var providerKey = Guid.NewGuid().ToString("N"); |
|||
|
|||
await Should.ThrowAsync<UserFriendlyException>(() => CallbackAsync(user, providerKey)); |
|||
|
|||
IsSignedIn().ShouldBeFalse(); |
|||
(await FindByLoginAsync(providerKey)).ShouldBeNull(); |
|||
} |
|||
|
|||
private async Task CallbackAsync(IdentityUser user, string providerKey) |
|||
{ |
|||
var principal = new ClaimsPrincipal(new ClaimsIdentity(new[] |
|||
{ |
|||
new Claim(ClaimTypes.NameIdentifier, providerKey), |
|||
new Claim(ClaimTypes.Email, user.Email) |
|||
}, IdentityConstants.ExternalScheme)); |
|||
|
|||
using var scope = ServiceProvider.CreateScope(); |
|||
var page = CreatePage<LoginModel>(scope.ServiceProvider, principal); |
|||
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin()) |
|||
{ |
|||
await page.OnGetExternalLoginCallbackAsync("/"); |
|||
await uow.CompleteAsync(); |
|||
} |
|||
} |
|||
|
|||
private async Task<IdentityUser> FindByLoginAsync(string providerKey) |
|||
{ |
|||
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin()) |
|||
{ |
|||
return await GetRequiredService<IdentityUserManager>().FindByLoginAsync(ExternalLoginProvider, providerKey); |
|||
} |
|||
} |
|||
} |
|||
|
|||
public class Login_ExternalLoginCallback_ReplacedSignInManager_Tests : Login_ExternalLoginCallback_Tests |
|||
{ |
|||
protected override void AfterAddApplication(IServiceCollection services) |
|||
{ |
|||
ReplaceSignInManager(services); |
|||
} |
|||
} |
|||
@ -0,0 +1,113 @@ |
|||
using System; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.Modularity; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Volo.Abp.Uow; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Account.Web.Pages.Account; |
|||
|
|||
// The page has no step to change the password, so a user that has to change the password is not allowed to log in.
|
|||
public abstract class Login_NotAllowedUser_TestBase<TStartupModule> : AbpAccountWebTestBase<TStartupModule> |
|||
where TStartupModule : IAbpModule |
|||
{ |
|||
protected virtual Guid? UserTenantId => null; |
|||
|
|||
protected override void AfterAddApplication(IServiceCollection services) |
|||
{ |
|||
services.Configure<AbpIdentityOptions>(options => |
|||
{ |
|||
options.ExternalLoginProviders.Add<TestExternalLoginProvider>(TestExternalLoginProvider.Name); |
|||
}); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Check_Password_Of_User_That_Has_To_Change_Password() |
|||
{ |
|||
var user = await CreateUserAsync(UserTenantId, RestrictedUserState.MustChangePassword); |
|||
|
|||
(await LoginAsync(user.UserName, "wrong-password")).ShouldBe(new[] { L("InvalidUserNameOrPassword") }); |
|||
(await LoginAsync(user.UserName, Password)).ShouldBe(new[] { L("LoginIsNotAllowed") }); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Show_Locked_Out_Message_For_Locked_Out_User_That_Has_To_Change_Password() |
|||
{ |
|||
var user = await CreateUserAsync(UserTenantId, RestrictedUserState.MustChangePassword, RestrictedUserState.LockedOut); |
|||
|
|||
(await LoginAsync(user.UserName, "wrong-password")).ShouldBe(new[] { L("UserLockedOutMessage") }); |
|||
} |
|||
|
|||
// The user may be authenticated by an external login provider, the local password is not the reason of the rejection.
|
|||
[Fact] |
|||
public async Task Should_Not_Check_Password_Of_Unconfirmed_User_That_Has_To_Change_Password() |
|||
{ |
|||
var user = await CreateUserAsync(UserTenantId, RestrictedUserState.MustChangePassword, RestrictedUserState.RequiresConfirmation); |
|||
|
|||
(await LoginAsync(user.UserName, "wrong-password")).ShouldBe(new[] { L("LoginIsNotAllowed") }); |
|||
} |
|||
|
|||
// The password of the external login provider can not be changed by the application.
|
|||
[Fact] |
|||
public async Task Should_Not_Allow_External_Login_User_That_Has_To_Change_Password() |
|||
{ |
|||
var user = await CreateUserAsync(UserTenantId, RestrictedUserState.MustChangePassword); |
|||
|
|||
(await LoginAsync(user.UserName, TestExternalLoginProvider.Password)).ShouldBe(new[] { L("ExternalLoginPasswordChangeRequired") }); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Show_Locked_Out_Message_For_Locked_Out_External_Login_User_That_Has_To_Change_Password() |
|||
{ |
|||
var user = await CreateUserAsync(UserTenantId, RestrictedUserState.MustChangePassword, RestrictedUserState.LockedOut); |
|||
|
|||
(await LoginAsync(user.UserName, TestExternalLoginProvider.Password)).ShouldBe(new[] { L("UserLockedOutMessage") }); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Allow_Unconfirmed_External_Login_User_That_Has_To_Change_Password() |
|||
{ |
|||
var user = await CreateUserAsync(UserTenantId, RestrictedUserState.MustChangePassword, RestrictedUserState.RequiresConfirmation); |
|||
|
|||
(await LoginAsync(user.UserName, TestExternalLoginProvider.Password)).ShouldBe(new[] { L("LoginIsNotAllowed") }); |
|||
} |
|||
|
|||
private async Task<string[]> LoginAsync(string userName, string password) |
|||
{ |
|||
using var scope = ServiceProvider.CreateScope(); |
|||
var page = CreatePage<LoginModel>(scope.ServiceProvider); |
|||
page.LoginInput = new LoginModel.LoginInputModel { UserNameOrEmailAddress = userName, Password = password }; |
|||
|
|||
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin()) |
|||
{ |
|||
await page.OnPostAsync("Login"); |
|||
await uow.CompleteAsync(); |
|||
} |
|||
|
|||
IsSignedIn().ShouldBeFalse(); |
|||
return GetAlerts(scope.ServiceProvider); |
|||
} |
|||
} |
|||
|
|||
public class Login_NotAllowedUser_Tests : Login_NotAllowedUser_TestBase<AbpAccountWebTestModule> |
|||
{ |
|||
} |
|||
|
|||
// The user of a tenant logs in on the host side.
|
|||
public class Login_NotAllowedUser_SharedUser_Tests : Login_NotAllowedUser_Tests |
|||
{ |
|||
protected override Guid? UserTenantId { get; } = Guid.NewGuid(); |
|||
|
|||
protected override void AfterAddApplication(IServiceCollection services) |
|||
{ |
|||
base.AfterAddApplication(services); |
|||
services.Configure<AbpMultiTenancyOptions>(options => |
|||
{ |
|||
options.IsEnabled = true; |
|||
options.UserSharingStrategy = TenantUserSharingStrategy.Shared; |
|||
}); |
|||
} |
|||
} |
|||
@ -0,0 +1,64 @@ |
|||
using System; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Mvc; |
|||
using Microsoft.AspNetCore.Mvc.RazorPages; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.Identity.Settings; |
|||
using Volo.Abp.Uow; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Account.Web.Pages.Account; |
|||
|
|||
public class Register_Tests : AbpAccountWebTestBase |
|||
{ |
|||
[Fact] |
|||
public async Task Should_Sign_In_Registered_User() |
|||
{ |
|||
var (result, alerts) = await RegisterAsync(); |
|||
|
|||
result.ShouldNotBeOfType<PageResult>(); |
|||
alerts.ShouldBeEmpty(); |
|||
IsSignedIn().ShouldBeTrue(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Show_Message_If_Registered_User_Is_Not_Allowed_To_Sign_In() |
|||
{ |
|||
SetSetting(IdentitySettingNames.SignIn.RequireConfirmedEmail, "true"); |
|||
|
|||
var (result, alerts) = await RegisterAsync(); |
|||
|
|||
result.ShouldBeOfType<PageResult>(); |
|||
alerts.ShouldBe(new[] { L("RegisteredButLoginIsNotAllowed") }); |
|||
IsSignedIn().ShouldBeFalse(); |
|||
} |
|||
|
|||
private async Task<(IActionResult Result, string[] Alerts)> RegisterAsync() |
|||
{ |
|||
var userName = "user-" + Guid.NewGuid().ToString("N"); |
|||
|
|||
using var scope = ServiceProvider.CreateScope(); |
|||
var page = CreatePage<RegisterModel>(scope.ServiceProvider); |
|||
page.Input = new RegisterModel.PostInput { UserName = userName, EmailAddress = userName + "@abp.io", Password = Password }; |
|||
page.ReturnUrl = "/"; |
|||
|
|||
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin()) |
|||
{ |
|||
var result = await page.OnPostAsync(); |
|||
await uow.CompleteAsync(); |
|||
|
|||
(await GetRequiredService<IdentityUserManager>().FindByNameAsync(userName)).ShouldNotBeNull(); |
|||
return (result, GetAlerts(scope.ServiceProvider)); |
|||
} |
|||
} |
|||
} |
|||
|
|||
public class Register_ReplacedSignInManager_Tests : Register_Tests |
|||
{ |
|||
protected override void AfterAddApplication(IServiceCollection services) |
|||
{ |
|||
ReplaceSignInManager(services); |
|||
} |
|||
} |
|||
@ -0,0 +1,33 @@ |
|||
using System; |
|||
using System.Threading.Tasks; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.Identity; |
|||
|
|||
namespace Volo.Abp.Account.Web; |
|||
|
|||
// Authenticates the existing users with a password that is not their local password.
|
|||
public class TestExternalLoginProvider : IExternalLoginProvider, ITransientDependency |
|||
{ |
|||
public const string Name = "Test"; |
|||
public const string Password = "External!9Aa"; |
|||
|
|||
public Task<bool> TryAuthenticateAsync(string userName, string plainPassword) |
|||
{ |
|||
return Task.FromResult(plainPassword == Password); |
|||
} |
|||
|
|||
public Task<IdentityUser> CreateUserAsync(string userName, string providerName) |
|||
{ |
|||
throw new NotSupportedException(); |
|||
} |
|||
|
|||
public Task UpdateUserAsync(IdentityUser user, string providerName) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
public Task<bool> IsEnabledAsync() |
|||
{ |
|||
return Task.FromResult(true); |
|||
} |
|||
} |
|||
@ -0,0 +1,25 @@ |
|||
using Microsoft.AspNetCore.Identity; |
|||
|
|||
namespace Volo.Abp.Identity.AspNetCore; |
|||
|
|||
public class AbpSignInResult : SignInResult |
|||
{ |
|||
/// <summary>
|
|||
/// The user is authenticated by an external login provider but has to change the password,
|
|||
/// which can't be done with the password of the external login provider.
|
|||
/// </summary>
|
|||
public static AbpSignInResult ExternalLoginPasswordChangeRequired { get; } = new AbpSignInResult |
|||
{ |
|||
IsNotAllowed = true, |
|||
IsExternalLoginPasswordChangeRequired = true |
|||
}; |
|||
|
|||
public bool IsExternalLoginPasswordChangeRequired { get; protected set; } |
|||
|
|||
public override string ToString() |
|||
{ |
|||
return IsExternalLoginPasswordChangeRequired |
|||
? nameof(ExternalLoginPasswordChangeRequired) |
|||
: base.ToString(); |
|||
} |
|||
} |
|||
@ -0,0 +1,130 @@ |
|||
using System; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Authentication; |
|||
using Microsoft.AspNetCore.Http; |
|||
using Microsoft.AspNetCore.Identity; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Extensions.Options; |
|||
using Shouldly; |
|||
using Volo.Abp.Identity.Settings; |
|||
using Volo.Abp.MultiTenancy; |
|||
using Volo.Abp.Settings; |
|||
using Volo.Abp.Uow; |
|||
using Xunit; |
|||
|
|||
namespace Volo.Abp.Identity.AspNetCore; |
|||
|
|||
public class AbpSignInManager_PreSignInCheckWithoutPassword_Tests : AbpIdentityAspNetCoreTestBase |
|||
{ |
|||
[Theory] |
|||
[InlineData(TenantUserSharingStrategy.Isolated, false)] |
|||
[InlineData(TenantUserSharingStrategy.Shared, true)] |
|||
public async Task Should_Only_Check_Password_Change_Period_If_Password_Is_Not_Shared(TenantUserSharingStrategy strategy, bool isAllowed) |
|||
{ |
|||
var result = await CheckUserWithExpiredPasswordAsync(strategy); |
|||
|
|||
if (isAllowed) |
|||
{ |
|||
result.ShouldBeNull(); |
|||
} |
|||
else |
|||
{ |
|||
result.ShouldBe(SignInResult.NotAllowed); |
|||
} |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Allow_User_That_Should_Change_Password_On_Next_Login() |
|||
{ |
|||
var result = await CheckUserWithExpiredPasswordAsync(TenantUserSharingStrategy.Shared, (_, user) => |
|||
{ |
|||
user.SetShouldChangePasswordOnNextLogin(true); |
|||
return Task.CompletedTask; |
|||
}); |
|||
|
|||
result.ShouldBe(SignInResult.NotAllowed); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Should_Not_Allow_Locked_Out_User() |
|||
{ |
|||
var result = await CheckUserWithExpiredPasswordAsync(TenantUserSharingStrategy.Shared, async (userManager, user) => |
|||
{ |
|||
(await userManager.SetLockoutEnabledAsync(user, true)).CheckErrors(); |
|||
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors(); |
|||
}); |
|||
|
|||
result.ShouldBe(SignInResult.LockedOut); |
|||
} |
|||
|
|||
// Only the password change period is skipped, the other checks of a customized sign-in manager still run.
|
|||
[Fact] |
|||
public async Task Should_Run_Custom_Pre_Sign_In_Check() |
|||
{ |
|||
var result = await CheckUserWithExpiredPasswordAsync( |
|||
TenantUserSharingStrategy.Shared, |
|||
signInManager: ActivatorUtilities.CreateInstance<RejectingSignInManager>(ServiceProvider)); |
|||
|
|||
result.ShouldBe(SignInResult.NotAllowed); |
|||
} |
|||
|
|||
private async Task<SignInResult> CheckUserWithExpiredPasswordAsync( |
|||
TenantUserSharingStrategy strategy, |
|||
Func<IdentityUserManager, IdentityUser, Task> configureUser = null, |
|||
AbpSignInManager signInManager = null) |
|||
{ |
|||
GetRequiredService<IOptions<AbpMultiTenancyOptions>>().Value.UserSharingStrategy = strategy; |
|||
TestSettingValueProvider.AddSetting(IdentitySettingNames.Password.ForceUsersToPeriodicallyChangePassword, true.ToString()); |
|||
TestSettingValueProvider.AddSetting(IdentitySettingNames.Password.PasswordChangePeriodDays, 1.ToString()); |
|||
|
|||
try |
|||
{ |
|||
using (var uow = GetRequiredService<IUnitOfWorkManager>().Begin()) |
|||
{ |
|||
var userManager = GetRequiredService<IdentityUserManager>(); |
|||
var userName = "expired-" + Guid.NewGuid().ToString("N"); |
|||
var user = new IdentityUser(Guid.NewGuid(), userName, userName + "@abp.io"); |
|||
(await userManager.CreateAsync(user, "1q2w3E*")).CheckErrors(); |
|||
user.SetLastPasswordChangeTime(DateTimeOffset.UtcNow.AddDays(-2)); |
|||
if (configureUser != null) |
|||
{ |
|||
await configureUser(userManager, user); |
|||
} |
|||
(await userManager.UpdateAsync(user)).CheckErrors(); |
|||
|
|||
var result = await (signInManager ?? GetRequiredService<AbpSignInManager>()).CallPreSignInCheckWithoutPasswordAsync(user); |
|||
await uow.CompleteAsync(); |
|||
return result; |
|||
} |
|||
} |
|||
finally |
|||
{ |
|||
TestSettingValueProvider.AddSetting(IdentitySettingNames.Password.ForceUsersToPeriodicallyChangePassword, false.ToString()); |
|||
} |
|||
} |
|||
} |
|||
|
|||
// A sign-in manager with a custom rule that rejects the user after the checks of the base class.
|
|||
public class RejectingSignInManager : AbpSignInManager |
|||
{ |
|||
public RejectingSignInManager( |
|||
IdentityUserManager userManager, |
|||
IHttpContextAccessor contextAccessor, |
|||
IUserClaimsPrincipalFactory<IdentityUser> claimsFactory, |
|||
IOptions<IdentityOptions> optionsAccessor, |
|||
ILogger<SignInManager<IdentityUser>> logger, |
|||
IAuthenticationSchemeProvider schemes, |
|||
IUserConfirmation<IdentityUser> confirmation, |
|||
IOptions<AbpIdentityOptions> options, |
|||
ISettingProvider settingProvider, |
|||
ICurrentTenant currentTenant) |
|||
: base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes, confirmation, options, settingProvider, currentTenant) |
|||
{ |
|||
} |
|||
|
|||
protected override async Task<SignInResult> PreSignInCheck(IdentityUser user) |
|||
{ |
|||
return await base.PreSignInCheck(user) ?? SignInResult.NotAllowed; |
|||
} |
|||
} |
|||
@ -0,0 +1,30 @@ |
|||
using System; |
|||
using System.Threading.Tasks; |
|||
using Volo.Abp.DependencyInjection; |
|||
|
|||
namespace Volo.Abp.Identity.AspNetCore; |
|||
|
|||
public class DisabledFakeExternalLoginProvider : IExternalLoginProvider, ITransientDependency |
|||
{ |
|||
public const string Name = "DisabledFake"; |
|||
|
|||
public Task<bool> TryAuthenticateAsync(string userName, string plainPassword) |
|||
{ |
|||
throw new InvalidOperationException("A disabled external login provider should not be used."); |
|||
} |
|||
|
|||
public Task<IdentityUser> CreateUserAsync(string userName, string providerName) |
|||
{ |
|||
throw new InvalidOperationException("A disabled external login provider should not be used."); |
|||
} |
|||
|
|||
public Task UpdateUserAsync(IdentityUser user, string providerName) |
|||
{ |
|||
throw new InvalidOperationException("A disabled external login provider should not be used."); |
|||
} |
|||
|
|||
public Task<bool> IsEnabledAsync() |
|||
{ |
|||
return Task.FromResult(false); |
|||
} |
|||
} |
|||
@ -0,0 +1,213 @@ |
|||
using System; |
|||
using System.Collections.Specialized; |
|||
using System.Threading.Tasks; |
|||
using IdentityServer4.Validation; |
|||
using Microsoft.AspNetCore.Identity; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.Identity.Settings; |
|||
using Xunit; |
|||
using IdentityUser = Volo.Abp.Identity.IdentityUser; |
|||
|
|||
namespace Volo.Abp.IdentityServer.AspNetIdentity; |
|||
|
|||
public class AbpResourceOwnerPasswordValidatorExternalLogin_Tests : AbpResourceOwnerPasswordValidatorTestBase |
|||
{ |
|||
protected override void AfterAddApplication(IServiceCollection services) |
|||
{ |
|||
services.Configure<AbpIdentityOptions>(options => |
|||
{ |
|||
options.ExternalLoginProviders.Add<TestExternalLoginProvider>(TestExternalLoginProvider.Name); |
|||
options.ExternalLoginProviders.Add<DisabledTestExternalLoginProvider>(DisabledTestExternalLoginProvider.Name); |
|||
}); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Authenticate() |
|||
{ |
|||
await CreateUserAsync(twoFactorEnabled: false); |
|||
var context = CreateContext(password: TestExternalLoginProvider.Password); |
|||
|
|||
await ValidateAsync(context); |
|||
|
|||
context.Result.IsError.ShouldBeFalse(); |
|||
context.Result.Subject.ShouldNotBeNull(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_With_TwoFactor_Should_Require_Code_Before_Authenticating() |
|||
{ |
|||
await CreateUserAsync(twoFactorEnabled: true); |
|||
var challengeContext = CreateContext(password: TestExternalLoginProvider.Password); |
|||
|
|||
await ValidateAsync(challengeContext); |
|||
|
|||
AssertInvalidGrant(challengeContext, "RequiresTwoFactor"); |
|||
|
|||
var code = await GenerateTwoFactorCodeAsync(); |
|||
var context = CreateContext(new NameValueCollection |
|||
{ |
|||
["TwoFactorProvider"] = TokenOptions.DefaultEmailProvider, |
|||
["TwoFactorCode"] = code |
|||
}, TestExternalLoginProvider.Password); |
|||
|
|||
await ValidateAsync(context); |
|||
|
|||
context.Result.IsError.ShouldBeFalse(); |
|||
context.Result.Subject.ShouldNotBeNull(); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Authenticate_Inactive_User() |
|||
{ |
|||
await CreateUserAsync(twoFactorEnabled: false); |
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
user.SetIsActive(false); |
|||
(await userManager.UpdateAsync(user)).CheckErrors(); |
|||
}); |
|||
var context = CreateContext(password: TestExternalLoginProvider.Password); |
|||
|
|||
await ValidateAsync(context); |
|||
|
|||
AssertInvalidGrant( |
|||
context, |
|||
"You are not allowed to login! Your account is inactive or needs to confirm your email/phone number."); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Authenticate_Locked_Out_User() |
|||
{ |
|||
await CreateUserAsync(twoFactorEnabled: false); |
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors(); |
|||
}); |
|||
var context = CreateContext(password: TestExternalLoginProvider.Password); |
|||
|
|||
await ValidateAsync(context); |
|||
|
|||
AssertInvalidGrant( |
|||
context, |
|||
"The user account has been locked out due to invalid login attempts. Please wait a while and try again."); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Authenticate_User_That_Requires_Confirmation() |
|||
{ |
|||
GetRequiredService<IdentityServerTestSettingValueProvider>().Set( |
|||
IdentitySettingNames.SignIn.RequireConfirmedEmail, |
|||
true.ToString()); |
|||
|
|||
await CreateUserAsync(twoFactorEnabled: false); |
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
user.SetEmailConfirmed(false); |
|||
(await userManager.UpdateAsync(user)).CheckErrors(); |
|||
}); |
|||
var context = CreateContext(password: TestExternalLoginProvider.Password); |
|||
|
|||
await ValidateAsync(context); |
|||
|
|||
AssertInvalidGrant( |
|||
context, |
|||
"You are not allowed to login! Your account is inactive or needs to confirm your email/phone number."); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Authenticate_User_That_Should_Change_Password() |
|||
{ |
|||
await CreateUserAsync(twoFactorEnabled: false, shouldChangePasswordOnNextLogin: true); |
|||
var context = CreateContext(password: TestExternalLoginProvider.Password); |
|||
|
|||
await ValidateAsync(context); |
|||
|
|||
AssertInvalidGrant(context, "ExternalLoginPasswordChangeRequired"); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Change_Password_Of_User_That_Should_Change_Password() |
|||
{ |
|||
await CreateUserAsync(twoFactorEnabled: false, shouldChangePasswordOnNextLogin: true); |
|||
string changePasswordToken = null; |
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
(await userManager.RemovePasswordAsync(user)).CheckErrors(); |
|||
(await userManager.AddPasswordAsync(user, TestExternalLoginProvider.Password)).CheckErrors(); |
|||
changePasswordToken = await userManager.GenerateUserTokenAsync( |
|||
user, |
|||
TokenOptions.DefaultProvider, |
|||
"ShouldChangePasswordOnNextLogin"); |
|||
}); |
|||
var context = CreateContext(new NameValueCollection |
|||
{ |
|||
["NewPassword"] = NewPassword, |
|||
["ChangePasswordToken"] = changePasswordToken |
|||
}, TestExternalLoginProvider.Password); |
|||
|
|||
await ValidateAsync(context); |
|||
|
|||
AssertInvalidGrant(context, "ExternalLoginPasswordChangeRequired"); |
|||
|
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
(await userManager.CheckPasswordAsync(user, TestExternalLoginProvider.Password)).ShouldBeTrue(); |
|||
(await userManager.CheckPasswordAsync(user, NewPassword)).ShouldBeFalse(); |
|||
user.ShouldChangePasswordOnNextLogin.ShouldBeTrue(); |
|||
}); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Authenticate_User_That_Should_Periodically_Change_Password() |
|||
{ |
|||
var settingValueProvider = GetRequiredService<IdentityServerTestSettingValueProvider>(); |
|||
settingValueProvider.Set( |
|||
IdentitySettingNames.Password.ForceUsersToPeriodicallyChangePassword, |
|||
true.ToString()); |
|||
settingValueProvider.Set( |
|||
IdentitySettingNames.Password.PasswordChangePeriodDays, |
|||
1.ToString()); |
|||
|
|||
await CreateUserAsync( |
|||
twoFactorEnabled: false, |
|||
lastPasswordChangeTime: DateTimeOffset.UtcNow.AddDays(-2)); |
|||
var context = CreateContext(password: TestExternalLoginProvider.Password); |
|||
|
|||
await ValidateAsync(context); |
|||
|
|||
AssertInvalidGrant(context, "ExternalLoginPasswordChangeRequired"); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Disabled_External_Login_Provider_Should_Not_Be_Used() |
|||
{ |
|||
await CreateUserAsync(twoFactorEnabled: false); |
|||
var context = CreateContext(password: "neither-local-nor-external-1q2w3E*"); |
|||
|
|||
await ValidateAsync(context); |
|||
|
|||
AssertInvalidGrant(context, "Invalid username or password!"); |
|||
} |
|||
|
|||
private Task UpdateUserAsync(Func<IdentityUserManager, IdentityUser, Task> action) |
|||
{ |
|||
return WithUnitOfWorkAsync(async serviceProvider => |
|||
{ |
|||
var userManager = serviceProvider.GetRequiredService<IdentityUserManager>(); |
|||
var user = await userManager.FindByNameAsync(UserName); |
|||
await action(userManager, user); |
|||
}); |
|||
} |
|||
|
|||
private static void AssertInvalidGrant( |
|||
ResourceOwnerPasswordValidationContext context, |
|||
string expectedErrorDescription) |
|||
{ |
|||
context.Result.IsError.ShouldBeTrue(); |
|||
context.Result.Error.ShouldBe("invalid_grant"); |
|||
context.Result.ErrorDescription.ShouldBe(expectedErrorDescription); |
|||
context.Result.Subject.ShouldBeNull(); |
|||
(context.Result.CustomResponse?.ContainsKey("changePasswordToken") ?? false).ShouldBeFalse(); |
|||
} |
|||
} |
|||
@ -0,0 +1,31 @@ |
|||
using System; |
|||
using System.Threading.Tasks; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.Identity; |
|||
|
|||
namespace Volo.Abp.IdentityServer.AspNetIdentity; |
|||
|
|||
public class DisabledTestExternalLoginProvider : IExternalLoginProvider, ITransientDependency |
|||
{ |
|||
public const string Name = "DisabledTest"; |
|||
|
|||
public Task<bool> TryAuthenticateAsync(string userName, string plainPassword) |
|||
{ |
|||
throw new InvalidOperationException("A disabled external login provider should not be used."); |
|||
} |
|||
|
|||
public Task<IdentityUser> CreateUserAsync(string userName, string providerName) |
|||
{ |
|||
throw new InvalidOperationException("A disabled external login provider should not be used."); |
|||
} |
|||
|
|||
public Task UpdateUserAsync(IdentityUser user, string providerName) |
|||
{ |
|||
throw new InvalidOperationException("A disabled external login provider should not be used."); |
|||
} |
|||
|
|||
public Task<bool> IsEnabledAsync() |
|||
{ |
|||
return Task.FromResult(false); |
|||
} |
|||
} |
|||
@ -0,0 +1,32 @@ |
|||
using System; |
|||
using System.Threading.Tasks; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.Identity; |
|||
|
|||
namespace Volo.Abp.IdentityServer.AspNetIdentity; |
|||
|
|||
public class TestExternalLoginProvider : IExternalLoginProvider, ITransientDependency |
|||
{ |
|||
public const string Name = "Test"; |
|||
public const string Password = "external-1q2w3E*"; |
|||
|
|||
public Task<bool> TryAuthenticateAsync(string userName, string plainPassword) |
|||
{ |
|||
return Task.FromResult(plainPassword == Password); |
|||
} |
|||
|
|||
public Task<IdentityUser> CreateUserAsync(string userName, string providerName) |
|||
{ |
|||
throw new NotSupportedException(); |
|||
} |
|||
|
|||
public Task UpdateUserAsync(IdentityUser user, string providerName) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
public Task<bool> IsEnabledAsync() |
|||
{ |
|||
return Task.FromResult(true); |
|||
} |
|||
} |
|||
@ -0,0 +1,31 @@ |
|||
using System; |
|||
using System.Threading.Tasks; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.Identity; |
|||
|
|||
namespace Volo.Abp.OpenIddict.Integration; |
|||
|
|||
public class DisabledTestExternalLoginProvider : IExternalLoginProvider, ITransientDependency |
|||
{ |
|||
public const string Name = "DisabledTest"; |
|||
|
|||
public Task<bool> TryAuthenticateAsync(string userName, string plainPassword) |
|||
{ |
|||
throw new InvalidOperationException("A disabled external login provider should not be used."); |
|||
} |
|||
|
|||
public Task<IdentityUser> CreateUserAsync(string userName, string providerName) |
|||
{ |
|||
throw new InvalidOperationException("A disabled external login provider should not be used."); |
|||
} |
|||
|
|||
public Task UpdateUserAsync(IdentityUser user, string providerName) |
|||
{ |
|||
throw new InvalidOperationException("A disabled external login provider should not be used."); |
|||
} |
|||
|
|||
public Task<bool> IsEnabledAsync() |
|||
{ |
|||
return Task.FromResult(false); |
|||
} |
|||
} |
|||
@ -0,0 +1,287 @@ |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using System.Net; |
|||
using System.Net.Http; |
|||
using System.Text.Json; |
|||
using System.Threading.Tasks; |
|||
using Microsoft.AspNetCore.Identity; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Shouldly; |
|||
using Volo.Abp.Identity; |
|||
using Volo.Abp.Identity.Settings; |
|||
using Xunit; |
|||
using IdentityUser = Volo.Abp.Identity.IdentityUser; |
|||
|
|||
namespace Volo.Abp.OpenIddict.Integration; |
|||
|
|||
public class OpenIddictPasswordGrantExternalLogin_Integration_Tests : OpenIddictPasswordGrantIntegrationTestBase |
|||
{ |
|||
protected override void ConfigureServices(IServiceCollection services) |
|||
{ |
|||
services.Configure<AbpIdentityOptions>(options => |
|||
{ |
|||
options.ExternalLoginProviders.Add<TestExternalLoginProvider>(TestExternalLoginProvider.Name); |
|||
options.ExternalLoginProviders.Add<DisabledTestExternalLoginProvider>(DisabledTestExternalLoginProvider.Name); |
|||
}); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Issue_Token() |
|||
{ |
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
(await userManager.SetTwoFactorEnabledAsync(user, false)).CheckErrors(); |
|||
}); |
|||
|
|||
var response = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password); |
|||
|
|||
await AssertAccessTokenAsync(response); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_With_TwoFactor_Should_Require_Code_Before_Issuing_Token() |
|||
{ |
|||
var challenge = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password); |
|||
|
|||
await AssertErrorAsync(challenge, "invalid_grant", AbpErrorDescriptionConsts.RequiresTwoFactor); |
|||
|
|||
var code = await GenerateTwoFactorCodeAsync(); |
|||
var response = await RequestPasswordTokenAsync(new Dictionary<string, string> |
|||
{ |
|||
["TwoFactorProvider"] = TokenOptions.DefaultEmailProvider, |
|||
["TwoFactorCode"] = code |
|||
}, TestExternalLoginProvider.Password); |
|||
|
|||
await AssertAccessTokenAsync(response); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_With_Invalid_TwoFactor_Code_Should_Not_Issue_Token() |
|||
{ |
|||
var response = await RequestPasswordTokenAsync(new Dictionary<string, string> |
|||
{ |
|||
["TwoFactorProvider"] = TokenOptions.DefaultEmailProvider, |
|||
["TwoFactorCode"] = "invalid-code" |
|||
}, TestExternalLoginProvider.Password); |
|||
|
|||
await AssertErrorAsync(response, "invalid_grant", "Invalid authenticator code!"); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_With_Valid_Recovery_Code_Should_Issue_Token() |
|||
{ |
|||
var recoveryCode = await WithUnitOfWorkAsync(async serviceProvider => |
|||
{ |
|||
var userManager = serviceProvider.GetRequiredService<IdentityUserManager>(); |
|||
var user = await userManager.FindByNameAsync(OpenIddictPasswordGrantTestData.UserName); |
|||
return (await userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 1)).Single(); |
|||
}); |
|||
|
|||
var response = await RequestPasswordTokenAsync(new Dictionary<string, string> |
|||
{ |
|||
["RecoveryCode"] = recoveryCode |
|||
}, TestExternalLoginProvider.Password); |
|||
|
|||
await AssertAccessTokenAsync(response); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_With_Invalid_Recovery_Code_Should_Not_Issue_Token() |
|||
{ |
|||
var response = await RequestPasswordTokenAsync(new Dictionary<string, string> |
|||
{ |
|||
["RecoveryCode"] = "invalid-recovery-code" |
|||
}, TestExternalLoginProvider.Password); |
|||
|
|||
await AssertErrorAsync(response, "invalid_grant", "Invalid recovery code!"); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Issue_Token_For_Inactive_User() |
|||
{ |
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
user.SetIsActive(false); |
|||
(await userManager.UpdateAsync(user)).CheckErrors(); |
|||
}); |
|||
|
|||
var response = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password); |
|||
|
|||
await AssertErrorAsync(response, AbpOpenIddictErrors.AccountInactive); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Issue_Token_For_Inactive_User_With_Valid_TwoFactor_Code() |
|||
{ |
|||
var code = await GenerateTwoFactorCodeAsync(); |
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
user.SetIsActive(false); |
|||
(await userManager.UpdateAsync(user)).CheckErrors(); |
|||
}); |
|||
|
|||
var response = await RequestPasswordTokenAsync(new Dictionary<string, string> |
|||
{ |
|||
["TwoFactorProvider"] = TokenOptions.DefaultEmailProvider, |
|||
["TwoFactorCode"] = code |
|||
}, TestExternalLoginProvider.Password); |
|||
|
|||
await AssertErrorAsync(response, AbpOpenIddictErrors.AccountInactive); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Issue_Token_For_Locked_Out_User() |
|||
{ |
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors(); |
|||
}); |
|||
|
|||
var response = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password); |
|||
|
|||
await AssertErrorAsync(response, AbpOpenIddictErrors.AccountLocked); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Issue_Token_For_Locked_Out_User_With_Valid_TwoFactor_Code() |
|||
{ |
|||
var code = await GenerateTwoFactorCodeAsync(); |
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
(await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.AddHours(1))).CheckErrors(); |
|||
}); |
|||
|
|||
var response = await RequestPasswordTokenAsync(new Dictionary<string, string> |
|||
{ |
|||
["TwoFactorProvider"] = TokenOptions.DefaultEmailProvider, |
|||
["TwoFactorCode"] = code |
|||
}, TestExternalLoginProvider.Password); |
|||
|
|||
await AssertErrorAsync(response, AbpOpenIddictErrors.AccountLocked); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Issue_Token_For_User_That_Should_Change_Password() |
|||
{ |
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
user.SetShouldChangePasswordOnNextLogin(true); |
|||
(await userManager.UpdateAsync(user)).CheckErrors(); |
|||
}); |
|||
|
|||
var response = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password); |
|||
|
|||
await AssertErrorAsync(response, "invalid_grant", "ExternalLoginPasswordChangeRequired"); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Change_Password_Of_User_That_Should_Change_Password() |
|||
{ |
|||
var changePasswordToken = await WithUnitOfWorkAsync(async serviceProvider => |
|||
{ |
|||
var userManager = serviceProvider.GetRequiredService<IdentityUserManager>(); |
|||
var user = await userManager.FindByNameAsync(OpenIddictPasswordGrantTestData.UserName); |
|||
user.SetShouldChangePasswordOnNextLogin(true); |
|||
(await userManager.RemovePasswordAsync(user)).CheckErrors(); |
|||
(await userManager.AddPasswordAsync(user, TestExternalLoginProvider.Password)).CheckErrors(); |
|||
return await userManager.GenerateUserTokenAsync( |
|||
user, |
|||
TokenOptions.DefaultProvider, |
|||
"ShouldChangePasswordOnNextLogin"); |
|||
}); |
|||
|
|||
var response = await RequestPasswordTokenAsync(new Dictionary<string, string> |
|||
{ |
|||
["NewPassword"] = NewPassword, |
|||
["ChangePasswordToken"] = changePasswordToken |
|||
}, TestExternalLoginProvider.Password); |
|||
|
|||
await AssertErrorAsync(response, "invalid_grant", "ExternalLoginPasswordChangeRequired"); |
|||
|
|||
await WithUnitOfWorkAsync(async serviceProvider => |
|||
{ |
|||
var userManager = serviceProvider.GetRequiredService<IdentityUserManager>(); |
|||
var user = await userManager.FindByNameAsync(OpenIddictPasswordGrantTestData.UserName); |
|||
(await userManager.CheckPasswordAsync(user, TestExternalLoginProvider.Password)).ShouldBeTrue(); |
|||
(await userManager.CheckPasswordAsync(user, NewPassword)).ShouldBeFalse(); |
|||
user.ShouldChangePasswordOnNextLogin.ShouldBeTrue(); |
|||
}); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Issue_Token_For_User_That_Should_Periodically_Change_Password() |
|||
{ |
|||
var settingValueProvider = GetRequiredService<OpenIddictTestSettingValueProvider>(); |
|||
settingValueProvider.Set( |
|||
IdentitySettingNames.Password.ForceUsersToPeriodicallyChangePassword, |
|||
true.ToString()); |
|||
settingValueProvider.Set( |
|||
IdentitySettingNames.Password.PasswordChangePeriodDays, |
|||
1.ToString()); |
|||
|
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
user.SetLastPasswordChangeTime(DateTimeOffset.UtcNow.AddDays(-2)); |
|||
(await userManager.UpdateAsync(user)).CheckErrors(); |
|||
}); |
|||
|
|||
var response = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password); |
|||
|
|||
await AssertErrorAsync(response, "invalid_grant", "ExternalLoginPasswordChangeRequired"); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task External_Login_Should_Not_Issue_Token_For_User_That_Requires_Confirmation() |
|||
{ |
|||
GetRequiredService<OpenIddictTestSettingValueProvider>().Set( |
|||
IdentitySettingNames.SignIn.RequireConfirmedEmail, |
|||
true.ToString()); |
|||
|
|||
await UpdateUserAsync(async (userManager, user) => |
|||
{ |
|||
user.SetEmailConfirmed(false); |
|||
(await userManager.UpdateAsync(user)).CheckErrors(); |
|||
}); |
|||
|
|||
var response = await RequestPasswordTokenAsync(password: TestExternalLoginProvider.Password); |
|||
|
|||
await AssertErrorAsync(response, "invalid_grant", AbpErrorDescriptionConsts.RequiresConfirmUser); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task Disabled_External_Login_Provider_Should_Not_Be_Used() |
|||
{ |
|||
var response = await RequestPasswordTokenAsync(password: "neither-local-nor-external-1q2w3E*"); |
|||
|
|||
await AssertErrorAsync(response, "invalid_grant", "Invalid username or password!"); |
|||
} |
|||
|
|||
private Task UpdateUserAsync(Func<IdentityUserManager, IdentityUser, Task> action) |
|||
{ |
|||
return WithUnitOfWorkAsync(async serviceProvider => |
|||
{ |
|||
var userManager = serviceProvider.GetRequiredService<IdentityUserManager>(); |
|||
var user = await userManager.FindByNameAsync(OpenIddictPasswordGrantTestData.UserName); |
|||
await action(userManager, user); |
|||
}); |
|||
} |
|||
|
|||
private static async Task AssertErrorAsync( |
|||
HttpResponseMessage response, |
|||
string expectedError, |
|||
string expectedErrorDescription = null) |
|||
{ |
|||
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); |
|||
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); |
|||
var root = document.RootElement; |
|||
root.GetProperty("error").GetString().ShouldBe(expectedError); |
|||
if (expectedErrorDescription != null) |
|||
{ |
|||
root.GetProperty("error_description").GetString().ShouldBe(expectedErrorDescription); |
|||
} |
|||
|
|||
root.TryGetProperty("access_token", out _).ShouldBeFalse(); |
|||
root.TryGetProperty("changePasswordToken", out _).ShouldBeFalse(); |
|||
} |
|||
} |
|||
@ -0,0 +1,34 @@ |
|||
using System; |
|||
using System.Threading.Tasks; |
|||
using Volo.Abp.DependencyInjection; |
|||
using Volo.Abp.Identity; |
|||
|
|||
namespace Volo.Abp.OpenIddict.Integration; |
|||
|
|||
public class TestExternalLoginProvider : IExternalLoginProvider, ITransientDependency |
|||
{ |
|||
public const string Name = "Test"; |
|||
public const string Password = "external-1q2w3E*"; |
|||
|
|||
public Task<bool> TryAuthenticateAsync(string userName, string plainPassword) |
|||
{ |
|||
return Task.FromResult( |
|||
userName == OpenIddictPasswordGrantTestData.UserName && plainPassword == Password |
|||
); |
|||
} |
|||
|
|||
public Task<IdentityUser> CreateUserAsync(string userName, string providerName) |
|||
{ |
|||
throw new NotSupportedException(); |
|||
} |
|||
|
|||
public Task UpdateUserAsync(IdentityUser user, string providerName) |
|||
{ |
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
public Task<bool> IsEnabledAsync() |
|||
{ |
|||
return Task.FromResult(true); |
|||
} |
|||
} |
|||
Loading…
Reference in new issue