Ejemplo n.º 1
0
        public override async Task <IActionResult> OnGetAsync()
        {
            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                Action   = IdentitySecurityLogActionConsts.Logout
            });

            await SignInManager.SignOutAsync();

            var logoutId = Request.Query["logoutId"].ToString();

            if (!string.IsNullOrEmpty(logoutId))
            {
                var logoutContext = await Interaction.GetLogoutContextAsync(logoutId);

                ReturnUrl = logoutContext?.PostLogoutRedirectUri;
            }

            if (ReturnUrl != null)
            {
                return(RedirectSafely(ReturnUrl, ReturnUrlHash));
            }

            Logger.LogInformation(
                $"{nameof(IdentityServerSupportedLogoutModel)} couldn't find postLogoutUri... Redirecting to the index page");
            return(RedirectSafely(ReturnUrl, ReturnUrlHash));
        }
Ejemplo n.º 2
0
        protected virtual async Task SetSuccessResultAsync(ResourceOwnerPasswordValidationContext context, IdentityUser user)
        {
            var sub = await UserManager.GetUserIdAsync(user);

            Logger.LogInformation("Credentials validated for username: {username}", context.UserName);

            var additionalClaims = new List <Claim>();

            await AddCustomClaimsAsync(additionalClaims, user, context);

            context.Result = new GrantValidationResult(
                sub,
                OidcConstants.AuthenticationMethods.Password,
                additionalClaims.ToArray()
                );

            await IdentitySecurityLogManager.SaveAsync(
                new IdentitySecurityLogContext
            {
                Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
                Action   = IdentityServerSecurityLogActionConsts.LoginSucceeded,
                UserName = context.UserName,
                ClientId = await FindClientIdAsync(context)
            }
                );
        }
Ejemplo n.º 3
0
    public virtual async Task <IActionResult> OnPostAsync(string action)
    {
        await CheckLocalLoginAsync();

        ValidateModel();

        ExternalProviders = await GetExternalProviders();

        EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

        await ReplaceEmailToUsernameOfInputIfNeeds();

        await IdentityOptions.SetAsync();

        var result = await SignInManager.PasswordSignInAsync(
            LoginInput.UserNameOrEmailAddress,
            LoginInput.Password,
            LoginInput.RememberMe,
            true
            );

        await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
        {
            Identity = IdentitySecurityLogIdentityConsts.Identity,
            Action   = result.ToIdentitySecurityLogAction(),
            UserName = LoginInput.UserNameOrEmailAddress
        });

        if (result.RequiresTwoFactor)
        {
            return(await TwoFactorLoginResultAsync());
        }

        if (result.IsLockedOut)
        {
            Alerts.Warning(L["UserLockedOutMessage"]);
            return(Page());
        }

        if (result.IsNotAllowed)
        {
            Alerts.Warning(L["LoginIsNotAllowed"]);
            return(Page());
        }

        if (!result.Succeeded)
        {
            Alerts.Danger(L["InvalidUserNameOrPassword"]);
            return(Page());
        }

        //TODO: Find a way of getting user's id from the logged in user and do not query it again like that!
        var user = await UserManager.FindByNameAsync(LoginInput.UserNameOrEmailAddress) ??
                   await UserManager.FindByEmailAsync(LoginInput.UserNameOrEmailAddress);

        Debug.Assert(user != null, nameof(user) + " != null");

        return(RedirectSafely(ReturnUrl, ReturnUrlHash));
    }
Ejemplo n.º 4
0
        public virtual async Task Logout()
        {
            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                Action   = IdentitySecurityLogActionConsts.Logout
            });

            await SignInManager.SignOutAsync();
        }
Ejemplo n.º 5
0
        public virtual async Task <IActionResult> OnGetAsync()
        {
            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                Action   = IdentitySecurityLogActionConsts.Logout
            });

            await SignInManager.SignOutAsync();

            return(RedirectSafely(ReturnUrl, ReturnUrlHash));
        }
Ejemplo n.º 6
0
 protected virtual async Task SaveSecurityLogAsync(string clientId = null)
 {
     if (CurrentUser.IsAuthenticated)
     {
         await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
         {
             Identity = IdentitySecurityLogIdentityConsts.Identity,
             Action   = IdentitySecurityLogActionConsts.Logout,
             ClientId = clientId
         });
     }
 }
Ejemplo n.º 7
0
        public virtual async Task <IActionResult> OnGetExternalLoginCallbackAsync(string returnUrl     = "",
                                                                                  string returnUrlHash = "", string remoteError = null)
        {
            if (remoteError != null)
            {
                Logger.LogWarning($"External login callback error: {remoteError}");
                return(RedirectToPage("./Login"));
            }

            var loginInfo = await SignInManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                Logger.LogWarning("External login info is not available");
                return(RedirectToPage("./Login"));
            }

            var result = await SignInManager.ExternalLoginSignInAsync(
                loginInfo.LoginProvider,
                loginInfo.ProviderKey,
                false,
                true
                );

            if (!result.Succeeded)
            {
                await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
                {
                    Identity = IdentitySecurityLogIdentityConsts.IdentityExternal,
                    Action   = "Login" + result
                });
            }

            if (result.IsLockedOut)
            {
                MyAlerts.Danger(L["UserLockedOutMessage"], L["OperationFailed"]);
                return(await OnGetAsync());
            }

            if (result.Succeeded)
            {
                return(RedirectSafely(returnUrl, returnUrlHash));
            }

            return(RedirectToPage("./Register", new
            {
                IsExternalLogin = true,
                UserName = loginInfo.Principal.FindFirstValue(ClaimTypes.Name),
                Email = loginInfo.Principal.FindFirstValue(ClaimTypes.Email),
                ReturnUrl = returnUrl,
                ReturnUrlHash = returnUrlHash
            }));
        }
Ejemplo n.º 8
0
    public virtual async Task ResetPasswordAsync(ResetPasswordDto input)
    {
        await IdentityOptions.SetAsync();

        var user = await UserManager.GetByIdAsync(input.UserId);

        (await UserManager.ResetPasswordAsync(user, input.ResetToken, input.Password)).CheckErrors();

        await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
        {
            Identity = IdentitySecurityLogIdentityConsts.Identity,
            Action   = IdentitySecurityLogActionConsts.ChangePassword
        });
    }
Ejemplo n.º 9
0
        public virtual async Task <IActionResult> OnGetAsync()
        {
            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                Action   = IdentitySecurityLogActionConsts.Logout
            });

            await SignInManager.SignOutAsync();

            if (ReturnUrl != null)
            {
                return(RedirectSafely(ReturnUrl, ReturnUrlHash));
            }

            return(RedirectToPage("/Account/Login"));
        }
Ejemplo n.º 10
0
        public async override Task <IActionResult> OnGetAsync()
        {
            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                Action   = IdentitySecurityLogActionConsts.Logout
            });

            await SignInManager.SignOutAsync();

            var logoutId = Request.Query["logoutId"].ToString();

            if (!string.IsNullOrEmpty(logoutId))
            {
                var logoutContext = await Interaction.GetLogoutContextAsync(logoutId);

                await SignInManager.SignOutAsync();

                HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity());

                LoggedOutModel vm = new LoggedOutModel()
                {
                    PostLogoutRedirectUri = logoutContext?.PostLogoutRedirectUri,
                    ClientName            = logoutContext?.ClientName,
                    SignOutIframeUrl      = logoutContext?.SignOutIFrameUrl
                };

                Logger.LogInformation($"Redirecting to LoggedOut Page...");

                return(RedirectToPage("./LoggedOut", vm));
            }

            if (ReturnUrl != null)
            {
                return(LocalRedirect(ReturnUrl));
            }

            Logger.LogInformation(
                $"IdentityServerSupportedLogoutModel couldn't find postLogoutUri... Redirecting to:/Account/Login..");
            return(RedirectToPage("/Account/Login"));
        }
Ejemplo n.º 11
0
        protected virtual async Task HandleTwoFactorLoginAsync(ResourceOwnerPasswordValidationContext context, IdentityUser user)
        {
            var twoFactorProvider = context.Request?.Raw?["TwoFactorProvider"];
            var twoFactorCode     = context.Request?.Raw?["TwoFactorCode"];

            if (!twoFactorProvider.IsNullOrWhiteSpace() && !twoFactorCode.IsNullOrWhiteSpace())
            {
                var providers = await UserManager.GetValidTwoFactorProvidersAsync(user);

                if (providers.Contains(twoFactorProvider) && await UserManager.VerifyTwoFactorTokenAsync(user, twoFactorProvider, twoFactorCode))
                {
                    await SetSuccessResultAsync(context, user);

                    return;
                }

                Logger.LogInformation("Authentication failed for username: {username}, reason: InvalidAuthenticatorCode", context.UserName);
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, Localizer["InvalidAuthenticatorCode"]);
            }
            else
            {
                Logger.LogInformation("Authentication failed for username: {username}, reason: RequiresTwoFactor", context.UserName);
                var twoFactorToken = await UserManager.GenerateUserTokenAsync(user, TokenOptions.DefaultProvider, nameof(SignInResult.RequiresTwoFactor));

                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, nameof(SignInResult.RequiresTwoFactor),
                                                           new Dictionary <string, object>()
                {
                    { "userId", user.Id },
                    { "twoFactorToken", twoFactorToken }
                });

                await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
                {
                    Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
                    Action   = IdentityServerSecurityLogActionConsts.LoginRequiresTwoFactor,
                    UserName = context.UserName,
                    ClientId = await FindClientIdAsync(context)
                });
            }
        }
Ejemplo n.º 12
0
        public virtual async Task <AbpLoginResult> Login(UserLoginInfo login)
        {
            await CheckLocalLoginAsync();

            ValidateLoginInfo(login);

            await ReplaceEmailToUsernameOfInputIfNeeds(login);

            var signInResult = await SignInManager.PasswordSignInAsync(
                login.UserNameOrEmailAddress,
                login.Password,
                login.RememberMe,
                true
                );

            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                Action   = signInResult.ToIdentitySecurityLogAction(),
                UserName = login.UserNameOrEmailAddress
            });

            return(GetAbpLoginResult(signInResult));
        }
Ejemplo n.º 13
0
        public virtual async Task <IActionResult> OnGetExternalLoginCallbackAsync(string returnUrl = "", string returnUrlHash = "", string remoteError = null)
        {
            //TODO: Did not implemented Identity Server 4 sample for this method (see ExternalLoginCallback in Quickstart of IDS4 sample)

            /* Also did not implement these:
             * - Logout(string logoutId)
             */

            if (remoteError != null)
            {
                Logger.LogWarning($"External login callback error: {remoteError}");
                return(RedirectToPage("./Login"));
            }

            var loginInfo = await SignInManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                Logger.LogWarning("External login info is not available");
                return(RedirectToPage("./Login"));
            }

            var result = await SignInManager.ExternalLoginSignInAsync(
                loginInfo.LoginProvider,
                loginInfo.ProviderKey,
                isPersistent : false,
                bypassTwoFactor : true
                );

            if (!result.Succeeded)
            {
                await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
                {
                    Identity = IdentitySecurityLogIdentityConsts.IdentityExternal,
                    Action   = "Login" + result
                });
            }

            if (result.IsLockedOut)
            {
                throw new UserFriendlyException("Cannot proceed because user is locked out!");
            }

            if (result.Succeeded)
            {
                return(RedirectSafely(returnUrl, returnUrlHash));
            }

            //TODO: Handle other cases for result!

            // Get the information about the user from the external login provider
            var externalLoginInfo = await SignInManager.GetExternalLoginInfoAsync();

            if (externalLoginInfo == null)
            {
                throw new ApplicationException("Error loading external login information during confirmation.");
            }

            if (!IsEmailRetrievedFromExternalLogin(externalLoginInfo))
            {
                return(RedirectToPage("./Register", new
                {
                    IsExternalLogin = true,
                    ExternalLoginAuthSchema = externalLoginInfo.LoginProvider,
                    ReturnUrl = returnUrl
                }));
            }

            var user = await CreateExternalUserAsync(externalLoginInfo);

            await SignInManager.SignInAsync(user, false);

            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
            {
                Identity = IdentitySecurityLogIdentityConsts.IdentityExternal,
                Action   = result.ToIdentitySecurityLogAction(),
                UserName = user.Name
            });

            return(RedirectSafely(returnUrl, returnUrlHash));
        }
        public virtual async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            await ReplaceEmailToUsernameOfInputIfNeeds(context);

            var user = await UserManager.FindByNameAsync(context.UserName);

            string errorDescription;

            if (user != null)
            {
                var result = await SignInManager.CheckPasswordSignInAsync(user, context.Password, true);

                if (result.Succeeded)
                {
                    var sub = await UserManager.GetUserIdAsync(user);

                    Logger.LogInformation("Credentials validated for username: {username}", context.UserName);
                    await Events.RaiseAsync(new UserLoginSuccessEvent(context.UserName, sub, context.UserName, interactive : false));

                    var additionalClaims = new List <Claim>();

                    await AddCustomClaimsAsync(additionalClaims, user, context);

                    context.Result = new GrantValidationResult(
                        sub,
                        OidcConstants.AuthenticationMethods.Password,
                        additionalClaims.ToArray()
                        );

                    await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
                    {
                        Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
                        Action   = result.ToIdentitySecurityLogAction(),
                    });

                    return;
                }
                else if (result.IsLockedOut)
                {
                    Logger.LogInformation("Authentication failed for username: {username}, reason: locked out", context.UserName);
                    await Events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "locked out", interactive : false));

                    errorDescription = Localizer["UserLockedOut"];
                }
                else if (result.IsNotAllowed)
                {
                    Logger.LogInformation("Authentication failed for username: {username}, reason: not allowed", context.UserName);
                    await Events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "not allowed", interactive : false));

                    errorDescription = Localizer["LoginIsNotAllowed"];
                }
                else
                {
                    Logger.LogInformation("Authentication failed for username: {username}, reason: invalid credentials", context.UserName);
                    await Events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "invalid credentials", interactive : false));

                    errorDescription = Localizer["InvalidUserNameOrPassword"];
                }

                await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
                {
                    Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
                    Action   = result.ToIdentitySecurityLogAction(),
                    UserName = context.UserName
                });
            }
            else
            {
                Logger.LogInformation("No user found matching username: {username}", context.UserName);
                await Events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "invalid username", interactive : false));

                errorDescription = Localizer["InvalidUsername"];

                await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
                {
                    Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
                    Action   = IdentityServerSecurityLogActionConsts.LoginInvalidUserName
                });
            }

            context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, errorDescription);
        }
Ejemplo n.º 15
0
    public virtual async Task <IActionResult> OnGetExternalLoginCallbackAsync(string returnUrl = "", string returnUrlHash = "", string remoteError = null)
    {
        //TODO: Did not implemented Identity Server 4 sample for this method (see ExternalLoginCallback in Quickstart of IDS4 sample)

        /* Also did not implement these:
         * - Logout(string logoutId)
         */

        if (remoteError != null)
        {
            Logger.LogWarning($"External login callback error: {remoteError}");
            return(RedirectToPage("./Login"));
        }

        await IdentityOptions.SetAsync();

        var loginInfo = await SignInManager.GetExternalLoginInfoAsync();

        if (loginInfo == null)
        {
            Logger.LogWarning("External login info is not available");
            return(RedirectToPage("./Login"));
        }

        var result = await SignInManager.ExternalLoginSignInAsync(
            loginInfo.LoginProvider,
            loginInfo.ProviderKey,
            isPersistent : false,
            bypassTwoFactor : true
            );

        if (!result.Succeeded)
        {
            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
            {
                Identity = IdentitySecurityLogIdentityConsts.IdentityExternal,
                Action   = "Login" + result
            });
        }

        if (result.IsLockedOut)
        {
            Logger.LogWarning($"External login callback error: user is locked out!");
            throw new UserFriendlyException("Cannot proceed because user is locked out!");
        }

        if (result.IsNotAllowed)
        {
            Logger.LogWarning($"External login callback error: user is not allowed!");
            throw new UserFriendlyException("Cannot proceed because user is not allowed!");
        }

        if (result.Succeeded)
        {
            return(RedirectSafely(returnUrl, returnUrlHash));
        }

        //TODO: Handle other cases for result!

        var email = loginInfo.Principal.FindFirstValue(AbpClaimTypes.Email);

        if (email.IsNullOrWhiteSpace())
        {
            return(RedirectToPage("./Register", new {
                IsExternalLogin = true,
                ExternalLoginAuthSchema = loginInfo.LoginProvider,
                ReturnUrl = returnUrl
            }));
        }

        var user = await UserManager.FindByEmailAsync(email);

        if (user == null)
        {
            user = await CreateExternalUserAsync(loginInfo);
        }
        else
        {
            if (await UserManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey) == null)
            {
                CheckIdentityErrors(await UserManager.AddLoginAsync(user, loginInfo));
            }
        }

        await SignInManager.SignInAsync(user, false);

        await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
        {
            Identity = IdentitySecurityLogIdentityConsts.IdentityExternal,
            Action   = result.ToIdentitySecurityLogAction(),
            UserName = user.Name
        });

        return(RedirectSafely(returnUrl, returnUrlHash));
    }
Ejemplo n.º 16
0
        public virtual async Task <IActionResult> OnPostAsync()
        {
            if (!await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin))
            {
                MyAlerts.Danger(L["LocalLoginDisabledMessage"], L["OperationFailed"]);
                return(await OnGetAsync());
            }

            try
            {
                ValidateModel();
            }
            catch (AbpValidationException e)
            {
                var message = GetMessageFromException(e);
                MyAlerts.Warning(message, L["OperationFailed"]);
                return(await OnGetAsync());
            }

            await ReplaceEmailToUsernameOfInputIfNeeds();

            var result = await SignInManager.PasswordSignInAsync(
                Input.UserNameOrEmailAddress,
                Input.Password,
                Input.RememberMe,
                true
                );

            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                Action   = result.ToIdentitySecurityLogAction(),
                UserName = Input.UserNameOrEmailAddress
            });

            if (result.RequiresTwoFactor)
            {
                return(await TwoFactorLoginResultAsync());
            }

            if (result.IsLockedOut)
            {
                MyAlerts.Danger(L["UserLockedOutMessage"], L["OperationFailed"]);
                return(await OnGetAsync());
            }

            if (result.IsNotAllowed)
            {
                MyAlerts.Danger(L["LoginIsNotAllowed"], L["OperationFailed"]);
                return(await OnGetAsync());
            }

            if (!result.Succeeded)
            {
                MyAlerts.Warning(L["InvalidUserNameOrPassword"], L["OperationFailed"]);
                return(await OnGetAsync());
            }

            //TODO: Find a way of getting user's id from the logged in user and do not query it again like that!
            var user = await UserManager.FindByNameAsync(Input.UserNameOrEmailAddress) ??
                       await UserManager.FindByEmailAsync(Input.UserNameOrEmailAddress);

            Debug.Assert(user != null, nameof(user) + " != null");

            return(RedirectSafely(ReturnUrl, ReturnUrlHash));
        }
        public async override Task <IActionResult> OnPostAsync(string action)
        {
            if (action == "Cancel")
            {
                var context = await Interaction.GetAuthorizationContextAsync(ReturnUrl);

                if (context == null)
                {
                    return(Redirect("~/"));
                }

                await Interaction.GrantConsentAsync(context, new ConsentResponse()
                {
                    Error = AuthorizationError.AccessDenied
                });

                return(Redirect(ReturnUrl));
            }

            await CheckLocalLoginAsync();

            ValidateModel();

            ExternalProviders = await GetExternalProviders();

            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

            await ReplaceEmailToUsernameOfInputIfNeeds();

            var result = await SignInManager.PasswordSignInAsync(
                LoginInput.UserNameOrEmailAddress,
                LoginInput.Password,
                LoginInput.RememberMe,
                true
                );

            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                Action   = result.ToIdentitySecurityLogAction(),
                UserName = LoginInput.UserNameOrEmailAddress
            });

            if (result.RequiresTwoFactor)
            {
                return(await TwoFactorLoginResultAsync());
            }

            if (result.IsLockedOut)
            {
                Alerts.Warning(L["UserLockedOutMessage"]);
                return(Page());
            }

            if (result.IsNotAllowed)
            {
                Alerts.Warning(L["LoginIsNotAllowed"]);
                return(Page());
            }

            if (!result.Succeeded)
            {
                Alerts.Danger(L["InvalidUserNameOrPassword"]);
                return(Page());
            }

            //TODO: Find a way of getting user's id from the logged in user and do not query it again like that!
            var user = await UserManager.FindByNameAsync(LoginInput.UserNameOrEmailAddress) ??
                       await UserManager.FindByEmailAsync(LoginInput.UserNameOrEmailAddress);

            Debug.Assert(user != null, nameof(user) + " != null");
            await IdentityServerEvents.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.UserName)); //TODO: Use user's name once implemented

            return(RedirectSafely(ReturnUrl, ReturnUrlHash));
        }
Ejemplo n.º 18
0
        public virtual async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var clientId = context.Request?.Client?.ClientId;

            using var scope = ServiceScopeFactory.CreateScope();

            await ReplaceEmailToUsernameOfInputIfNeeds(context);

            IdentityUser user = null;

            async Task SetSuccessResultAsync()
            {
                var sub = await UserManager.GetUserIdAsync(user);

                Logger.LogInformation("Credentials validated for username: {username}", context.UserName);

                var additionalClaims = new List <Claim>();

                await AddCustomClaimsAsync(additionalClaims, user, context);

                context.Result = new GrantValidationResult(
                    sub,
                    OidcConstants.AuthenticationMethods.Password,
                    additionalClaims.ToArray()
                    );

                await IdentitySecurityLogManager.SaveAsync(
                    new IdentitySecurityLogContext
                {
                    Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
                    Action   = IdentityServerSecurityLogActionConsts.LoginSucceeded,
                    UserName = context.UserName,
                    ClientId = clientId
                }
                    );
            }

            if (AbpIdentityOptions.ExternalLoginProviders.Any())
            {
                foreach (var externalLoginProviderInfo in AbpIdentityOptions.ExternalLoginProviders.Values)
                {
                    var externalLoginProvider = (IExternalLoginProvider)scope.ServiceProvider
                                                .GetRequiredService(externalLoginProviderInfo.Type);

                    if (await externalLoginProvider.TryAuthenticateAsync(context.UserName, context.Password))
                    {
                        user = await UserManager.FindByNameAsync(context.UserName);

                        if (user == null)
                        {
                            user = await externalLoginProvider.CreateUserAsync(context.UserName, externalLoginProviderInfo.Name);
                        }
                        else
                        {
                            await externalLoginProvider.UpdateUserAsync(user, externalLoginProviderInfo.Name);
                        }

                        await SetSuccessResultAsync();

                        return;
                    }
                }
            }

            user = await UserManager.FindByNameAsync(context.UserName);

            string errorDescription;

            if (user != null)
            {
                var result = await SignInManager.CheckPasswordSignInAsync(user, context.Password, true);

                if (result.Succeeded)
                {
                    await SetSuccessResultAsync();

                    return;
                }
                else if (result.IsLockedOut)
                {
                    Logger.LogInformation("Authentication failed for username: {username}, reason: locked out", context.UserName);
                    errorDescription = Localizer["UserLockedOut"];
                }
                else if (result.IsNotAllowed)
                {
                    Logger.LogInformation("Authentication failed for username: {username}, reason: not allowed", context.UserName);
                    errorDescription = Localizer["LoginIsNotAllowed"];
                }
                else
                {
                    Logger.LogInformation("Authentication failed for username: {username}, reason: invalid credentials", context.UserName);
                    errorDescription = Localizer["InvalidUserNameOrPassword"];
                }

                await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
                {
                    Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
                    Action   = result.ToIdentitySecurityLogAction(),
                    UserName = context.UserName,
                    ClientId = clientId
                });
            }
            else
            {
                Logger.LogInformation("No user found matching username: {username}", context.UserName);
                errorDescription = Localizer["InvalidUsername"];

                await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
                {
                    Identity = IdentityServerSecurityLogIdentityConsts.IdentityServer,
                    Action   = IdentityServerSecurityLogActionConsts.LoginInvalidUserName,
                    UserName = context.UserName,
                    ClientId = clientId
                });
            }

            context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, errorDescription);
        }
Ejemplo n.º 19
0
        public virtual async Task <IActionResult> OnPostAsync(string action)
        {
            ActionHelper.AddTitle(this, "Login");

            // Clean old noitify data
            ViewData["LoginError"] = null;

            await CheckLocalLoginAsync();

            ValidateModel();

            ExternalProviders = await GetExternalProviders();

            EnableLocalLogin = await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin);

            await ReplaceEmailToUsernameOfInputIfNeeds();

            await IdentityOptions.SetAsync();

            var result = await SignInManager.PasswordSignInAsync(
                LoginInput.UserNameOrEmailAddress,
                LoginInput.Password,
                LoginInput.RememberMe,
                true
                );

            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                Action   = result.ToIdentitySecurityLogAction(),
                UserName = LoginInput.UserNameOrEmailAddress
            });

            if (result.RequiresTwoFactor)
            {
                return(await TwoFactorLoginResultAsync());
            }

            if (result.IsLockedOut)
            {
                ViewData["LoginError"] = L["Please try again after a few minutes"];
                ToastHelper.ToastError(this, L["Please try again after a few minutes"]);
                return(Page());
            }

            if (result.IsNotAllowed)
            {
                ViewData["LoginError"] = L["You are not permitted login right now"];
                ToastHelper.ToastError(this, L["You are not permitted login right now"]);
                return(Page());
            }

            if (!result.Succeeded)
            {
                ViewData["LoginError"] = L["Invalid Username/Email or Password"];
                ToastHelper.ToastError(this, L["Invalid Username/Email or Password"]);
                return(Page());
            }

            //TODO: Find a way of getting user's id from the logged in user and do not query it again like that!
            var user = await UserManager.FindByNameAsync(LoginInput.UserNameOrEmailAddress) ??
                       await UserManager.FindByEmailAsync(LoginInput.UserNameOrEmailAddress);

            Debug.Assert(user != null, nameof(user) + " != null");

            ToastHelper.ToastSuccess(this, L["Login successful"]);

            return(RedirectSafely(ReturnUrl, ReturnUrlHash));
        }