Web API 2 AccessFailedCount not Incrementing When using Token Based Authentication

泪湿孤枕 提交于 2019-12-05 12:02:26
Rohit Sharma

Finally I have resolved with this code

// To lock the user with userName ---- setting of maximum access 5 in IdentityConfig.cs File 
ApplicationUser userToLock = await userManager.FindByNameAsync(context.UserName);
if (userToLock != null)
{
    await userManager.AccessFailedAsync(userToLock.Id);
}

Now Access AccessFailedCount, LockoutEndDateUtc getting value

Thanks for the help guys. Special Thanks for @trailmax ... To divert my thinking to webapi

To increment AccessFailedCount on a user, every time the login is invalid you need to call for

await userManager.AccessFailedAsync(user.Id);

Otherwise this is not done for you in any way.

ApplicationSignInManager does this this for you but (as far as I know) this class only works with MVC, not WebAPI

silvajnr

Hi It may be too late but I got some code from ASP.Net Identity 2.0 AccessFailedCount not incrementing

and customized to Web API.

        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        ApplicationUser user = await userManager.FindByNameAsync(context.UserName);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        bool EmailConfirmed = await userManager.IsEmailConfirmedAsync(user.Id);

        if ( !EmailConfirmed)
        {
            context.SetError("inactive_user", "The user is not active. Please check your Register Email to verify.");
            return;
        }

        bool LockedOut = await userManager.IsLockedOutAsync(user.Id);
        if (userManager.SupportsUserLockout && LockedOut)
        {
            context.SetError("invalid_grant", "This account has been locked out, please try again later.");
            return;
        }

        int FailedCount = await userManager.GetAccessFailedCountAsync(user.Id);
        bool LockoutEnabled = await userManager.GetLockoutEnabledAsync(user.Id);
        if (userManager.CheckPassword(user, context.Password))
        {
            if (userManager.SupportsUserLockout && LockoutEnabled && FailedCount > 0)
            {
                await userManager.ResetAccessFailedCountAsync(user.Id);
            }
            // Authenticate user
        }
        else
        {

            if (userManager.SupportsUserLockout && LockoutEnabled)
            {
                await userManager.AccessFailedAsync(user.Id);
            }
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!