Base solution for your next web application
Open Closed

External Login (Eg. Facebook) Failed to Activate #5432


User avatar
0
firnas created

When trying to login with external user i am getting "There is no such an entity. Entity type: OnePoint.Authorization.Users.User, id: 105" error. By default i activated the user to avoid email verification check. This works for normal user creation. However, the error is only for external user such as Facebook login.

I have also noticed that this issue does not occur in localhost even for external user login. Appreciated if anyone can help me on this. I have given code sample and logs.

[HttpPost]
        
public async Task<ExternalAuthenticateResultModel> ExternalAuthenticate([FromBody] ExternalAuthenticateModel model)
        
{
            try
            {
                var externalUser = await GetExternalUserInfo(model);

                var loginResult = await _logInManager.LoginAsync(new UserLoginInfo(model.AuthProvider, model.ProviderKey, model.AuthProvider), GetTenancyNameOrNull());

                switch (loginResult.Result)
                {
                    case AbpLoginResultType.Success:
                        {
                            var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));

                            var returnUrl = model.ReturnUrl;

                            if (model.SingleSignIn.HasValue && model.SingleSignIn.Value && loginResult.Result == AbpLoginResultType.Success)
                            {
                                loginResult.User.SetSignInToken();
                                returnUrl = AddSingleSignInParametersToReturnUrl(model.ReturnUrl, loginResult.User.SignInToken, loginResult.User.Id, loginResult.User.TenantId);
                            }

                            return new ExternalAuthenticateResultModel
                            {
                                AccessToken = accessToken,
                                EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
                                ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds,
                                ReturnUrl = returnUrl
                            };
                        }
                    case AbpLoginResultType.UnknownExternalLogin:
                        {
                            var newUser = await RegisterExternalUserAsync(externalUser);

                            //commented to implement the email sending
                            //TODO email sending
                            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()
                                );
                            }
                            else //login success
                            {
                                //TODO map user if possible
                                // bool isMapSuccess = await IsSocialUserMapSuccess(externalUser.Provider, externalUser.ProviderKey, externalUser.Name);
                            }

                            var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
                            return new ExternalAuthenticateResultModel
                            {
                                AccessToken = accessToken,
                                EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
                                ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds
                            };
                        }
                    default:
                        {
                            throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(
                                loginResult.Result,
                                model.ProviderKey,
                                GetTenancyNameOrNull()
                            );
                        }
                }
            }
            catch (Exception ex)
            {

                Logger.Error(ex.Message);
                throw new UserFriendlyException("cannot create external user");
            }
        
}

this is the external authentication method.its calling RegisterExternalUserAsync method.in that one its calling register user method.

public async Task<User> RegisterAsync(string name, string surname, string emailAddress, string userName, string plainPassword, bool isEmailConfirmed, string emailActivationLink)
        {
            CheckForTenant();
            CheckSelfRegistrationIsEnabled();

            var tenant = await GetActiveTenantAsync();
            var isNewRegisteredUserActiveByDefault = await SettingManager.GetSettingValueAsync<bool>(AppSettings.UserManagement.IsNewRegisteredUserActiveByDefault);

            await _userPolicy.CheckMaxUserCountAsync(tenant.Id);

            var user = new User
            {
                TenantId = tenant.Id,
                Name = name,
                Surname = surname,
                EmailAddress = emailAddress,
                IsActive = isNewRegisteredUserActiveByDefault,
                UserName = userName,
                IsEmailConfirmed = isEmailConfirmed,
                Roles = new List<UserRole>()
            };

            user.SetNormalizedNames();

            user.Password = _passwordHasher.HashPassword(user, plainPassword);
            var defaultRoles = await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync();

            if (defaultRoles!=null && defaultRoles.Count!=0)
            {
                foreach (var defaultRole in defaultRoles)
                {
                    user.Roles.Add(new UserRole(tenant.Id, user.Id, defaultRole.Id));
                } 
            }

            CheckErrors(await _userManager.CreateAsync(user));
            await CurrentUnitOfWork.SaveChangesAsync();

            if (!user.IsEmailConfirmed)
            {
                user.SetNewEmailConfirmationCode();
                await _userEmailer.SendEmailActivationLinkAsync(user, emailActivationLink);
            }

            //Notifications
            await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(user.ToUserIdentifier());
            await _appNotifier.WelcomeToTheApplicationAsync(user);
            await _appNotifier.NewUserRegisteredAsync(user);

            return user;
        }

Below is the log

INFO  2018-07-25 09:27:10,060 [10   ] ore.Mvc.Internal.ControllerActionInvoker - Executing action method OnePoint.Web.Controllers.TokenAuthController.ExternalAuthenticate (OnePoint.Web.Core) with arguments (OnePoint.Web.Models.TokenAuth.ExternalAuthenticateModel) - ModelState is Valid
ERROR 2018-07-25 09:27:11,688 [10   ] oint.Web.Controllers.TokenAuthController - There is no such an entity. Entity type: OnePoint.Authorization.Users.User, id: 105
WARN  2018-07-25 09:27:11,735 [10   ] Mvc.ExceptionHandling.AbpExceptionFilter - cannot create external user
Abp.UI.UserFriendlyException: cannot create external user
   at OnePoint.Web.Controllers.TokenAuthController.<ExternalAuthenticate>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at lambda_method(Closure , Object )
   at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextExceptionFilterAsync>d__23.MoveNext()

3 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Could you create an issue here <a class="postlink" href="https://github.com/aspnetzero/aspnet-zero-core/issues">https://github.com/aspnetzero/aspnet-zero-core/issues</a> ? We will test and fix this.

    Thanks,

  • User Avatar
    0
    firnas created

    <cite>ismcagdas: </cite> Could you create an issue here <a class="postlink" href="https://github.com/aspnetzero/aspnet-zero-core/issues">https://github.com/aspnetzero/aspnet-zero-core/issues</a> ? We will test and fix this.

    Thanks,

    Link is broken?

  • User Avatar
    0
    alper created
    Support Team

    you need to be signed in GitHub.com to be able to see that link. if you have granted access to the repository, you can successfully see that page