Esempio n. 1
0
        private async Task <bool> IsTwoFactorAuthRequiredAsync(AbpLoginResult <Tenant, User> loginResult,
                                                               AuthenticateModel authenticateModel)
        {
            if (!await SettingManager.GetSettingValueAsync <bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin
                                                                  .IsEnabled))
            {
                return(false);
            }

            if (!loginResult.User.IsTwoFactorEnabled)
            {
                return(false);
            }

            if ((await _userManager.GetValidTwoFactorProvidersAsync(loginResult.User)).Count <= 0)
            {
                return(false);
            }

            if (await TwoFactorClientRememberedAsync(loginResult.User.ToUserIdentifier(), authenticateModel))
            {
                return(false);
            }

            return(true);
        }
Esempio n. 2
0
        private async Task SaveLoginAttempt(AbpLoginResult <SysTenant, SysUser> loginResult, string tenancyName, string userNameOrEmailAddress)
        {
            using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.Suppress))
            {
                var tenantId = loginResult.Tenant?.Id;
                using (UnitOfWorkManager.Current.SetTenantId(tenantId))
                {
                    var loginAttempt = new UserLoginAttempt
                    {
                        TenantId    = tenantId,
                        TenancyName = tenancyName,

                        UserId = loginResult.User?.Id,
                        UserNameOrEmailAddress = userNameOrEmailAddress,

                        Result = loginResult.Result,

                        BrowserInfo     = ClientInfoProvider.BrowserInfo,
                        ClientIpAddress = ClientInfoProvider.ClientIpAddress,
                        ClientName      = ClientInfoProvider.ComputerName,
                    };

                    await UserLoginAttemptRepository.InsertAsync(loginAttempt);

                    await UnitOfWorkManager.Current.SaveChangesAsync();

                    await uow.CompleteAsync();
                }
            }
        }
        private async Task <List <Claim> > CreateJwtClaims(AbpLoginResult <Tenant, User> loginResult)
        {
            var    claims      = loginResult.Identity.Claims.ToList();
            var    nameIdClaim = claims.First(c => c.Type == JwtRegisteredClaimNames.Sub);
            string userModel   = JsonConvert.SerializeObject(Mapper.Map <UserLoginInfoDto>(loginResult.User));
            var    org         = await UserManager.GetOrganizationUnitsAsync(loginResult.User);

            string orgModel = JsonConvert.SerializeObject(Mapper.Map <List <OrgLoginInfo> >(org));
            var    company  = await CompanyManager.FindByIdAsync(loginResult.User.CompanyId);

            string companyModel = JsonConvert.SerializeObject(Mapper.Map <CompanyLoginInfo>(company));
            var    roles        = await UserManager.GetRolesAsync(loginResult.User);

            var max_role_type = await UserRoleManager.MaxRoleType(roles);

            // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims.
            claims.AddRange(new[]
            {
                new Claim("UserModel", userModel),
                new Claim("OrgModel", orgModel),
                new Claim("CompanyModel", companyModel),
                new Claim("MaxRoleType", max_role_type.ToString()),
                new Claim(ClaimTypes.NameIdentifier, nameIdClaim.Value),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                //new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
            });

            return(claims);
        }
Esempio n. 4
0
        public virtual async Task SignInAsync(AbpLoginResult <TTenant, TUser> loginResult, bool isPersistent, bool?rememberBrowser = null)
        {
            if (loginResult.Result != AbpLoginResultType.Success)
            {
                throw new ArgumentException("loginResult.Result should be success in order to sign in!");
            }

            using (_unitOfWorkManager.Current.SetTenantId(loginResult.Tenant?.Id))
            {
                await SignOutAllAsync();

                if (rememberBrowser == null)
                {
                    rememberBrowser = IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsRememberBrowserEnabled, loginResult.Tenant?.Id);
                }

                if (rememberBrowser == true)
                {
                    await SignOutAllAndSignInAsync(loginResult.Identity, isPersistent);

                    await AuthenticationManager.SignInAsync(
                        _configuration.TwoFactorRememberBrowserAuthenticationScheme,
                        CreateIdentityForTwoFactor(
                            loginResult.User,
                            _configuration.TwoFactorRememberBrowserAuthenticationScheme
                            )
                        );
                }
                else
                {
                    await SignOutAllAndSignInAsync(loginResult.Identity, isPersistent);
                }
            }
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task <LoginOutput> Login(LoginInput input)
        {
            AbpLoginResult abpLoginResult = await _LoginManager.LoginAsync(input.Username, input.Password, input.TenantId ?? 0);

            if (abpLoginResult.Result == AbpLoginResultType.InvalidUserNameOrEmailAddress)
            {
                return(new LoginOutput()
                {
                    ErrorMessage = "无效的用户名", AbpLoginResult = abpLoginResult
                });
            }

            if (abpLoginResult.Result == AbpLoginResultType.InvalidPassword)
            {
                return(new LoginOutput()
                {
                    ErrorMessage = "无效的密码", AbpLoginResult = abpLoginResult
                });
            }

            return(new LoginOutput()
            {
                AbpLoginResult = abpLoginResult
            });
        }
        protected virtual void SaveLoginAttempt(AbpLoginResult <TTenant, TUser> loginResult, string tenancyName, string userNameOrEmailAddress)
        {
            using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.Suppress))
            {
                var tenantId = loginResult.Tenant != null ? loginResult.Tenant.Id : (int?)null;
                using (UnitOfWorkManager.Current.SetTenantId(tenantId))
                {
                    var loginAttempt = new UserLoginAttempt
                    {
                        TenantId    = tenantId,
                        TenancyName = tenancyName,

                        UserId = loginResult.User != null ? loginResult.User.Id : (long?)null,
                        UserNameOrEmailAddress = userNameOrEmailAddress,

                        Result = loginResult.Result,

                        BrowserInfo     = ClientInfoProvider.BrowserInfo,
                        ClientIpAddress = ClientInfoProvider.ClientIpAddress,
                        ClientName      = ClientInfoProvider.ComputerName,
                    };

                    UserLoginAttemptRepository.Insert(loginAttempt);
                    UnitOfWorkManager.Current.SaveChanges();

                    uow.Complete();
                }
            }
        }
Esempio n. 7
0
        public async Task <ExternalAuthenticateResultModel> ExternalAuthenticate([FromBody] ExternalAuthenticateModel model)
        {
            ExternalAuthUserInfo externalUser = await GetExternalUserInfo(model);

            AbpLoginResult <Tenant, User> loginResult = await _logInManager.LoginAsync(new UserLoginInfo(model.AuthProvider, model.ProviderKey, model.AuthProvider), GetTenancyNameOrNull());

            switch (loginResult.Result)
            {
            case AbpLoginResultType.Success:
            {
                string accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
                return(new ExternalAuthenticateResultModel
                    {
                        AccessToken = accessToken,
                        EncryptedAccessToken = GetEncryptedAccessToken(accessToken),
                        ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds
                    });
            }

            case AbpLoginResultType.UnknownExternalLogin:
            {
                User newUser = await RegisterExternalUserAsync(externalUser);

                if (!newUser.IsActive)
                {
                    return(new ExternalAuthenticateResultModel
                        {
                            WaitingForActivation = true
                        });
                }

                // Try to login again with newly registered user!
                loginResult = await _logInManager.LoginAsync(new UserLoginInfo(model.AuthProvider, model.ProviderKey, model.AuthProvider), GetTenancyNameOrNull());

                if (loginResult.Result != AbpLoginResultType.Success)
                {
                    throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(
                              loginResult.Result,
                              model.ProviderKey,
                              GetTenancyNameOrNull()
                              );
                }

                return(new ExternalAuthenticateResultModel
                    {
                        AccessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity)),
                        ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds
                    });
            }

            default:
            {
                throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(
                          loginResult.Result,
                          model.ProviderKey,
                          GetTenancyNameOrNull()
                          );
            }
            }
        }
Esempio n. 8
0
        private async Task SaveLoginAttempt(AbpLoginResult loginResult, string userNameOrEmailAddress)
        {
            using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
            {
                var loginAttempt = new UserLoginAttempt
                {
                    UserId   = loginResult.User != null ? loginResult.User.Id : (long?)null,
                    UserName = userNameOrEmailAddress,

                    Result = loginResult.Result,
                };

                //TODO: We should replace this workaround with IClientInfoProvider when it's implemented in ABP (https://github.com/aspnetboilerplate/aspnetboilerplate/issues/926)
                if (AuditInfoProvider != null)
                {
                    var auditInfo = new AuditInfo();
                    AuditInfoProvider.Fill(auditInfo);
                    loginAttempt.BrowserInfo     = auditInfo.BrowserInfo;
                    loginAttempt.ClientIpAddress = auditInfo.ClientIpAddress;
                    loginAttempt.ClientName      = auditInfo.ClientName;
                }

                await _userLoginAttemptRepository.InsertAsync(loginAttempt);

                await _unitOfWorkManager.Current.SaveChangesAsync();

                await uow.CompleteAsync();
            }
        }
        public async Task <AuthenticateResultModel> Switching(long id)
        {
            var tenant = await this._tenantRepository.GetAll().IgnoreQueryFilters().FirstOrDefaultAsync(o => o.Id == id && !o.IsDeleted && o.IsActive);

            AbpLoginResult <Tenant, User> loginResult;

            if (tenant == null)
            {
                loginResult = new AbpLoginResult <Tenant, User>(AbpLoginResultType.UserIsNotActive);
            }
            else
            {
                var user = await this._userRepository.GetAll().IgnoreQueryFilters().FirstAsync(o => o.UserName == "admin" && o.TenantId == tenant.Id);

                var principal = await _claimsPrincipalFactory.CreateAsync(user);

                loginResult = new AbpLoginResult <Tenant, User>(
                    tenant,
                    user,
                    principal.Identity as ClaimsIdentity
                    );
            }
            var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity, loginResult.Tenant));

            return(new AuthenticateResultModel
            {
                AccessToken = accessToken,
                EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
                ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds,
                UserId = loginResult.User.Id
            });
        }
Esempio n. 10
0
        public virtual async Task <AjaxResponse> Register(RegisterViewModel model)
        {
            try
            {
                //  CheckSelfRegistrationIsEnabled();
                CurrentUnitOfWork.SetTenantId(null);
                var tenant = await GetActiveTenantAsync(Tenant.DefaultTenantName);

                CurrentUnitOfWork.SetTenantId(tenant.Id);
                //Getting tenant-specific settings
                // var isNewRegisteredUserActiveByDefault = await SettingManager.GetSettingValueForApplicationAsync<bool>(YtSettings.General.UserDefaultActive);
                var user = new User
                {
                    TenantId = tenant.Id,
                    Name     = model.Name,
                    IsActive = true
                };
                if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty())
                {
                    throw new AbpException("用户名或密码不可为空");
                }
                user.UserName = model.UserName;
                user.Password = new PasswordHasher().HashPassword(model.Password);
                user.Roles    = new List <UserRole>();
                var roles = _roleManager.Roles.Where(r => r.IsDefault).ToList();
                foreach (var defaultRole in roles)
                {
                    user.Roles.Add(new UserRole(tenant.Id, user.Id, defaultRole.Id));
                }

                //  CheckErrors(await _userManager.CreateAsync(user));
                await _userManager.CreateAsync(user);

                await _unitOfWorkManager.Current.SaveChangesAsync();

                if (!user.IsActive)
                {
                    return(new AjaxResponse("用户注册成功,处于禁用状态"));
                }
                AbpLoginResult <Tenant, User>
                loginResult = await GetLoginResultAsync(user.UserName, model.Password, tenant.TenancyName);

                if (loginResult.Result == AbpLoginResultType.Success)
                {
                    var ticket     = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());
                    var currentUtc = new SystemClock().UtcNow;
                    ticket.Properties.IssuedUtc = currentUtc;
                    //有效期1天
                    ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(1));
                    return(new AjaxResponse(OAuthBearerOptions.AccessTokenFormat.Protect(ticket)));
                }
                Logger.Warn("登陆失败,原因: " + loginResult.Result);
                return(new AjaxResponse("用户注册成功,登陆失败,原因" + loginResult.Result));
            }
            catch (UserFriendlyException ex)
            {
                return(new AjaxResponse(ex.Message));
            }
        }
        private AuthenticationTicket GetTicketByLoginResult(AbpLoginResult <Tenant, User> loginResult)
        {
            var ticket = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());

            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
            return(ticket);
        }
Esempio n. 12
0
        private static int?GetTenantId(AbpLoginResult <Tenant, User> loginResult)
        {
            int?tenantId = null;

            if (loginResult.Tenant != null)
            {
                tenantId = loginResult.Tenant.Id;
            }

            return(tenantId);
        }
Esempio n. 13
0
        private async Task <DeviceLoginResult> DeviceLogin(LoginModel loginModel, AbpLoginResult <Tenant, User> loginResult)
        {
            var deviceLoginResult = await _deviceManager.DeviceLoginAsync(loginModel.DeviceLoginModel.Imei, loginModel.DeviceLoginModel.AppVersion, loginModel.DeviceLoginModel.SystemVersion, loginModel.DeviceLoginModel.Status, loginResult.User);

            if (deviceLoginResult.DeviceLogin == DeviceLoginEnum.NotMe)
            {
                throw new UserFriendlyException("登录失败", "设备已绑定其他账号");
            }

            return(deviceLoginResult);
        }
Esempio n. 14
0
        public async Task <IActionResult> Login([FromBody] LoginViewModel loginModel)
        {
            AbpLoginResult <Tenant, User> loginResult = await
                                                        GetLoginResultAsync(loginModel.UsernameOrEmailAddress, loginModel.Password, GetTenancyNameOrNull());

            await _signInManager.SignInAsync(loginResult.Identity, loginModel.RememberMe);

            await UnitOfWorkManager.Current.SaveChangesAsync();

            return(Ok());
        }
        private async Task <AbpLoginResult <Tenant, User> > GetLoginResultAsync(string usernameOrEmailAddress, string password, string tenancyName)
        {
            AbpLoginResult <Tenant, User> loginResult = await _logInManager.LoginAsync(usernameOrEmailAddress, password, tenancyName);

            switch (loginResult.Result)
            {
            case AbpLoginResultType.Success:
                return(loginResult);

            default:
                throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(loginResult.Result, usernameOrEmailAddress, tenancyName);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// This method can return two results:
        /// <see cref="SignInStatus.Success"/> indicates that user has successfully signed in.
        /// <see cref="SignInStatus.RequiresVerification"/> indicates that user has successfully signed in.
        /// </summary>
        /// <param name="loginResult">The login result received from <see cref="AbpLogInManager{TTenant,TRole,TUser}"/> Should be Success.</param>
        /// <param name="isPersistent">True to use persistent cookie.</param>
        /// <param name="rememberBrowser">Remember user's browser (and not use two factor auth again) or not.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">loginResult.Result should be success in order to sign in!</exception>
        public virtual async Task <SignInStatus> SignInOrTwoFactor(AbpLoginResult <TTenant, TUser> loginResult,
                                                                   bool isPersistent, bool?rememberBrowser = null)
        {
            return(await _unitOfWorkManager.WithUnitOfWorkAsync(async() =>
            {
                if (loginResult.Result != AbpLoginResultType.Success)
                {
                    throw new ArgumentException("loginResult.Result should be success in order to sign in!");
                }

                using (_unitOfWorkManager.Current.SetTenantId(loginResult.Tenant?.Id))
                {
                    if (IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled, loginResult.Tenant?.Id))
                    {
                        UserManager.As <AbpUserManager <TRole, TUser> >()
                        .RegisterTwoFactorProviders(loginResult.Tenant?.Id);

                        if (await UserManager.GetTwoFactorEnabledAsync(loginResult.User.Id))
                        {
                            if ((await UserManager.GetValidTwoFactorProvidersAsync(loginResult.User.Id)).Count > 0)
                            {
                                if (!await AuthenticationManager.TwoFactorBrowserRememberedAsync(loginResult.User.Id
                                                                                                 .ToString()) ||
                                    rememberBrowser == false)
                                {
                                    var claimsIdentity = new ClaimsIdentity(DefaultAuthenticationTypes.TwoFactorCookie);

                                    claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier,
                                                                      loginResult.User.Id.ToString()));

                                    if (loginResult.Tenant != null)
                                    {
                                        claimsIdentity.AddClaim(new Claim(AbpClaimTypes.TenantId,
                                                                          loginResult.Tenant.Id.ToString()));
                                    }

                                    AuthenticationManager.SignIn(new AuthenticationProperties {
                                        IsPersistent = true
                                    },
                                                                 claimsIdentity);
                                    return SignInStatus.RequiresVerification;
                                }
                            }
                        }
                    }

                    SignIn(loginResult, isPersistent, rememberBrowser);
                    return SignInStatus.Success;
                }
            }));
        }
Esempio n. 17
0
        /// <param name="loginResult">The login result received from <see cref="AbpLogInManager{TTenant,TRole,TUser}"/> Should be Success.</param>
        /// <param name="isPersistent">True to use persistent cookie.</param>
        /// <param name="rememberBrowser">Remember user's browser (and not use two factor auth again) or not.</param>
        public virtual void SignIn(AbpLoginResult <TTenant, TUser> loginResult, bool isPersistent,
                                   bool?rememberBrowser = null)
        {
            _unitOfWorkManager.WithUnitOfWork(() =>
            {
                if (loginResult.Result != AbpLoginResultType.Success)
                {
                    throw new ArgumentException("loginResult.Result should be success in order to sign in!");
                }

                using (_unitOfWorkManager.Current.SetTenantId(loginResult.Tenant?.Id))
                {
                    AuthenticationManager.SignOut(
                        DefaultAuthenticationTypes.ExternalCookie,
                        DefaultAuthenticationTypes.TwoFactorCookie
                        );

                    if (rememberBrowser == null)
                    {
                        rememberBrowser = IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsRememberBrowserEnabled,
                                                 loginResult.Tenant?.Id);
                    }

                    if (rememberBrowser == true)
                    {
                        var rememberBrowserIdentity =
                            AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(loginResult.User.Id.ToString());
                        AuthenticationManager.SignIn(
                            new AuthenticationProperties
                        {
                            IsPersistent = isPersistent
                        },
                            loginResult.Identity,
                            rememberBrowserIdentity
                            );
                    }
                    else
                    {
                        AuthenticationManager.SignIn(
                            new AuthenticationProperties
                        {
                            IsPersistent = isPersistent
                        },
                            loginResult.Identity
                            );
                    }
                }
            });
        }
Esempio n. 18
0
        public virtual async Task <SignInStatus> SignInOrTwoFactorAsync(AbpLoginResult <TTenant, TUser> loginResult, bool isPersistent, bool?rememberBrowser = null)
        {
            if (loginResult.Result != AbpLoginResultType.Success)
            {
                throw new ArgumentException("loginResult.Result should be success in order to sign in!");
            }

            using (_unitOfWorkManager.Current.SetTenantId(loginResult.Tenant?.Id))
            {
                if (IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled, loginResult.Tenant?.Id))
                {
                    UserManager.As <AbpUserManager <TRole, TUser> >().RegisterTwoFactorProviders(loginResult.Tenant?.Id);

                    if (await UserManager.GetTwoFactorEnabledAsync(loginResult.User.Id))
                    {
                        if ((await UserManager.GetValidTwoFactorProvidersAsync(loginResult.User.Id)).Count > 0)
                        {
                            if (!await TwoFactorBrowserRememberedAsync(loginResult.User.Id.ToString(), loginResult.User.TenantId) ||
                                rememberBrowser == false)
                            {
                                var claimsIdentity = new ClaimsIdentity(_configuration.TwoFactorAuthenticationScheme);

                                claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, loginResult.User.Id.ToString()));

                                if (loginResult.Tenant != null)
                                {
                                    claimsIdentity.AddClaim(new Claim(AbpClaimTypes.TenantId, loginResult.Tenant.Id.ToString()));
                                }

                                await AuthenticationManager.SignInAsync(
                                    _configuration.TwoFactorAuthenticationScheme,
                                    CreateIdentityForTwoFactor(
                                        loginResult.User,
                                        _configuration.TwoFactorAuthenticationScheme
                                        )
                                    );

                                return(SignInStatus.RequiresVerification);
                            }
                        }
                    }
                }

                await SignInAsync(loginResult, isPersistent, rememberBrowser);

                return(SignInStatus.Success);
            }
        }
Esempio n. 19
0
        private string GetToken(AbpLoginResult <Tenant, User> loginResult)
        {
            if (loginResult.Result != AbpLoginResultType.Success)
            {
                throw new UserFriendlyException("登录或注册失败。结果:" + loginResult.Result);
            }

            var ticket = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());

            var currentUtc = new SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

            return(OAuthBearerOptions.AccessTokenFormat.Protect(ticket));
        }
Esempio n. 20
0
        public async Task <AuthenticateResultModel> Authenticate([FromBody] AuthenticateModel model)
        {
            AbpLoginResult <Tenant, User> loginResult = await GetLoginResultAsync(
                model.UserNameOrEmailAddress,
                model.Password,
                GetTenancyNameOrNull()
                );

            string accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));

            return(new AuthenticateResultModel
            {
                AccessToken = accessToken,
                EncryptedAccessToken = GetEncryptedAccessToken(accessToken),
                ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds,
                UserId = loginResult.User.Id
            });
        }
        public virtual async Task <JsonResult> Login(LoginViewModel loginModel, string returnUrl = "", string returnUrlHash = "")
        {
            returnUrl = NormalizeReturnUrl(returnUrl);
            if (!string.IsNullOrWhiteSpace(returnUrlHash))
            {
                returnUrl = returnUrl + returnUrlHash;
            }

            AbpLoginResult <Tenant, User> loginResult = await
                                                        GetLoginResultAsync(loginModel.UsernameOrEmailAddress, loginModel.Password, GetTenancyNameOrNull());

            await _signInManager.SignInAsync(loginResult.Identity, loginModel.RememberMe);

            await UnitOfWorkManager.Current.SaveChangesAsync();

            return(Json(new AjaxResponse {
                TargetUrl = returnUrl
            }));
        }
Esempio n. 22
0
        /// <summary>
        /// 怬
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task <LoginOutput> Login(LoginInput input)
        {
            AbpLoginResult abpLoginResult = await _LoginManager.LoginAsync(input.Username, input.Password, input.TenantId ?? 0);

            if (abpLoginResult.Result == AbpLoginResultType.InvalidUserNameOrEmailAddress)
            {
                throw new UserFriendlyException("Óû§Ãû»òÃÜÂë´íÎó");
            }

            if (abpLoginResult.Result == AbpLoginResultType.InvalidPassword)
            {
                throw new UserFriendlyException("Óû§Ãû»òÃÜÂë´íÎó");
            }

            return(new LoginOutput()
            {
                AbpLoginResult = abpLoginResult
            });
        }
Esempio n. 23
0
        public virtual async Task <SignInResult> SignInOrTwoFactorAsync(AbpLoginResult <TTenant, TUser> loginResult,
                                                                        bool isPersistent, bool?rememberBrowser = null, string loginProvider = null, bool bypassTwoFactor = false)
        {
            if (loginResult.Result != AbpLoginResultType.Success)
            {
                throw new ArgumentException("loginResult.Result should be success in order to sign in!");
            }

            using (_unitOfWorkManager.Current.SetTenantId(loginResult.Tenant?.Id))
            {
                await UserManager.As <AbpUserManager <TRole, TUser> >().InitializeOptionsAsync(loginResult.Tenant?.Id);

                if (!bypassTwoFactor && IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled,
                                               loginResult.Tenant?.Id))
                {
                    if (await UserManager.GetTwoFactorEnabledAsync(loginResult.User))
                    {
                        if ((await UserManager.GetValidTwoFactorProvidersAsync(loginResult.User)).Count > 0)
                        {
                            if (!await IsTwoFactorClientRememberedAsync(loginResult.User) || rememberBrowser == false)
                            {
                                await Context.SignInAsync(
                                    IdentityConstants.TwoFactorUserIdScheme,
                                    StoreTwoFactorInfo(loginResult.User, loginProvider)
                                    );

                                return(SignInResult.TwoFactorRequired);
                            }
                        }
                    }
                }

                if (loginProvider != null)
                {
                    await Context.SignOutAsync(IdentityConstants.ExternalScheme);
                }

                await SignInAsync(loginResult.User, isPersistent, loginProvider);

                return(SignInResult.Success);
            }
        }
        public virtual async Task <ActionResult> ExternalLoginCallback(string returnUrl, string remoteError = null)
        {
            returnUrl = NormalizeReturnUrl(returnUrl);

            if (remoteError != null)
            {
                Logger.Error("Remote Error in ExternalLoginCallback: " + remoteError);
                throw new UserFriendlyException(L("CouldNotCompleteLoginOperation"));
            }

            ExternalLoginInfo externalLoginInfo = await _signInManager.GetExternalLoginInfoAsync();

            if (externalLoginInfo == null)
            {
                Logger.Warn("Could not get information from external login.");
                return(RedirectToAction(nameof(Login)));
            }

            await _signInManager.SignOutAsync();

            string tenancyName = GetTenancyNameOrNull();

            AbpLoginResult <Tenant, User> loginResult = await _logInManager.LoginAsync(externalLoginInfo, tenancyName);

            switch (loginResult.Result)
            {
            case AbpLoginResultType.Success:
                await _signInManager.SignInAsync(loginResult.Identity, false);

                return(Redirect(returnUrl));

            case AbpLoginResultType.UnknownExternalLogin:
                return(await RegisterForExternalLogin(externalLoginInfo));

            default:
                throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(
                          loginResult.Result,
                          externalLoginInfo.Principal.FindFirstValue(ClaimTypes.Email) ?? externalLoginInfo.ProviderKey,
                          tenancyName
                          );
            }
        }
Esempio n. 25
0
        public async Task <IActionResult> Login()
        {
            Volo.Abp.Account.Web.Areas.Account.Controllers.Models.UserLoginInfo userLoginInfo = new Volo.Abp.Account.Web.Areas.Account.Controllers.Models.UserLoginInfo
            {
                UserNameOrEmailAddress = "testuser",
                Password   = "******",
                RememberMe = false,
            };

            string userNameOrEmailAddress = "testuser";
            string password = "******";
            //bool rememberMe = false;
            string AuthenticationUrl = "https://localhost:44346/api/account/login";

            //FormUrlEncodedContent content = new FormUrlEncodedContent(new[] {
            //        //new KeyValuePair<string, string>("grant_type", "password"),
            //        new KeyValuePair<string, string>("userNameOrEmailAddress", userNameOrEmailAddress),
            //        new KeyValuePair<string, string>("password", password),
            //    });

            //Controllers.UserLoginInfo content
            //_oidcClient = new OidcClient();

            var usercontent2 = new StringContent(JsonConvert.SerializeObject(userLoginInfo), Encoding.UTF8, "application/json");

            var serverClient = _httpClientFactory.CreateClient();
            //var response = await serverClient.GetAsync("https://localhost:44346/connect/authorize");
            var serverResponse = await serverClient.PostAsync(AuthenticationUrl, usercontent2);

            if (serverResponse.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var data = await serverResponse.Content.ReadAsStringAsync();

                AbpLoginResult xx = JsonConvert.DeserializeObject(data) as AbpLoginResult;
            }

            return(Ok(new
            {
                message = usercontent2,
                respones = serverResponse.Content
            }));
        }
Esempio n. 26
0
        /// <summary>
        /// 验证密码复杂度(不能为默认密码)和密码修改周期
        /// </summary>
        /// <param name="loginModel"></param>
        /// <param name="loginResult"></param>
        private void ValidateCycleAndComplex(LoginViewModel loginModel, AbpLoginResult <Tenant, User> loginResult)
        {
            //进行密码复杂度的校验
            var pwdRule = OperateSection.GetPwdRuleSection();

            if (pwdRule.IsValidatecComplex)//是否启用复杂度校验
            {
                var complexList = OperateSection.GetPwdComplexSetList();
                if (complexList != null && complexList.Count > 0)
                {
                    foreach (var complex in complexList)
                    {
                        if (Regex.IsMatch(loginModel.Password, complex.Regular))
                        {
                            throw new Exception("密码复杂度不够:" + complex.ErrorMsg + "。即将跳入密码修改页面...");
                        }
                    }
                }
                if (pwdRule.DefualtPwd == loginModel.Password)
                {
                    throw new Exception("不能为系统默认密码。即将跳入密码修改页面...");
                }
            }

            //密码周期性验证
            if (pwdRule.IsCycle)//启用了周期性验证
            {
                var dd         = _userPwdAppService.GetAllPwdLog(loginResult.User.Id);
                var lastPwdLog = _userPwdAppService.GetLastPwdLog(loginResult.User.Id);
                if (lastPwdLog != null)
                {
                    if (!string.IsNullOrEmpty(pwdRule.CycleTime) && Convert.ToInt32(pwdRule.CycleTime) < DateTime.Now.Subtract(lastPwdLog.CreationTime).Duration().Days)
                    {
                        throw new Exception("当前密码累计使用已超过【" + pwdRule.CycleTime + "】天,请修改密码。即将跳入密码修改页面...");
                    }
                }
            }
        }
        protected virtual async Task <AbpLoginResult <TTenant, TUser> > LoginAsyncInternal(string userNameOrEmailAddress, string plainPassword, string tenancyName, bool shouldLockout)
        {
            if (userNameOrEmailAddress.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(userNameOrEmailAddress));
            }

            if (plainPassword.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(plainPassword));
            }

            //Get and check tenant
            TTenant tenant = null;

            using (UnitOfWorkManager.Current.SetTenantId(null))
            {
                if (!MultiTenancyConfig.IsEnabled)
                {
                    tenant = await GetDefaultTenantAsync();
                }
                else if (!string.IsNullOrWhiteSpace(tenancyName))
                {
                    tenant = await TenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName);

                    if (tenant == null)
                    {
                        return(new AbpLoginResult <TTenant, TUser>(AbpLoginResultType.InvalidTenancyName));
                    }

                    if (!tenant.IsActive)
                    {
                        return(new AbpLoginResult <TTenant, TUser>(AbpLoginResultType.TenantIsNotActive, tenant));
                    }
                }
            }

            var tenantId = tenant == null ? (int?)null : tenant.Id;

            using (UnitOfWorkManager.Current.SetTenantId(tenantId))
            {
                //TryLoginFromExternalAuthenticationSources method may create the user, that's why we are calling it before AbpStore.FindByNameOrEmailAsync
                var loggedInFromExternalSource = await TryLoginFromExternalAuthenticationSources(userNameOrEmailAddress, plainPassword, tenant);

                var user = await UserManager.AbpStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress);

                if (user == null)
                {
                    return(new AbpLoginResult <TTenant, TUser>(AbpLoginResultType.InvalidUserNameOrEmailAddress, tenant));
                }

                if (!loggedInFromExternalSource)
                {
                    UserManager.InitializeLockoutSettings(tenantId);

                    if (await UserManager.IsLockedOutAsync(user.Id))
                    {
                        return(new AbpLoginResult <TTenant, TUser>(AbpLoginResultType.LockedOut, tenant, user));
                    }

                    var verificationResult = UserManager.PasswordHasher.VerifyHashedPassword(user.Password, plainPassword);
                    if (verificationResult != PasswordVerificationResult.Success)
                    {
                        if (shouldLockout)
                        {
                            if (await TryLockOutAsync(tenantId, user.Id))
                            {
                                return(new AbpLoginResult <TTenant, TUser>(AbpLoginResultType.LockedOut, tenant, user));
                            }
                        }

                        var abpLoginResult = new AbpLoginResult <TTenant, TUser>(AbpLoginResultType.InvalidPassword, tenant, user);
                        abpLoginResult.HashPassword = UserManager.PasswordHasher.HashPassword(plainPassword);
                        return(abpLoginResult);
                    }

                    await UserManager.ResetAccessFailedCountAsync(user.Id);
                }

                return(await CreateLoginResultAsync(user, tenant));
            }
        }