Build a custom user check password in Asp.Net Identity 2

家住魔仙堡 提交于 2019-12-06 04:59:09

问题


I need to build a custom user password check in an application implemented in asp.net MVC 5 and using Asp.Net Identity 2.

I read in a stackoverflow post (Writing a custom IUserPasswordStore and SignInManager.PasswordSignInAsync in Identity 2.1) that I only need to override the CheckPasswordAsync method in UserManager.

I try to override this method in IdentityConfig.cs file. Here is the code that I add to the ApplicationUserManager class just for test this solution:

public override async Task<bool> CheckPasswordAsync(ApplicationUser user,   string password)
{
        return await Task.Run(() => {
            return true;
        });
}

The problem is that this code is never run in the login process, and the login always fail. To sign in the user I’m using the SignInManager.PasswordSignInAsync to log in the user, this is the default when creating a new web application in asp.net MVC 5. Shouldn’t this method call the ApplicationUserManager. CheckPasswordAsync? Or there is another configuration needed to this work?


回答1:


It should work. I've just used the standard ASP.NET MVC template, updated all the libraries involved through NuGet, and it must work.

I guess the problems is the way you are overriding the method.

In your ApplicationUserManager try to change your code like this:

public override Task<bool> CheckPasswordAsync(ApplicationUser user, string password)
{
    return Task.FromResult<bool>(true);
}

or:

public override Task<bool> CheckPasswordAsync(ApplicationUser user, string password)
{
    return Task.Run(() => MyCheckPasswordAsync());
}

private bool MyCheckPasswordAsync()
{
    return true;
}

and you will see it goes through:




回答2:


The problem was that I was trying to login with a user that do not exists in the system.

The SignInManager.PasswordSignInAsync never invoke the ApplicationUserManager. CheckPasswordAsync if the user not exists in the user store repository.

In conclusion, I have to store the users in my application or implement a custom user store mechanism.




回答3:


This may not be a direct answer however it provides a full solution to the problem. He implements a custom authorisation filter which you can then customise to do what you want.

https://weblog.west-wind.com/posts/2013/Apr/18/A-WebAPI-Basic-Authentication-Authorization-Filter

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class BasicAuthenticationFilter : AuthorizationFilterAttribute

It can then be used like this instead of the [Authorize] attribute

[MyBasicAuthenticationFilter]
public class QueueController : ApiController


来源:https://stackoverflow.com/questions/31559088/build-a-custom-user-check-password-in-asp-net-identity-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!