Validating a user in WCF using ASP.net Identity 2.

2019-08-11 10:43发布

问题:

I have built a custom Identity.Models framework by simply extending the new asp.net identity framework 2.0 so that I can store the username and other relevant user data in my custom database instead of the default entity database which gets generated and it is working fine.

Now I am building a WCF service from where I would like to authenticate these users and leverage the asp.net identity 2.0 functionalities , but unable to do so.

In my WCF service I made a new Validator class extending UsernamePasswordValidator but it is not working as expected.

public class IdentityValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            using (var context = new MyIdentityDbContext())
            {
                using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)))
                {
                    var user = userManager.Find(userName, password);
                    if (user == null)
                    {
                        var msg = String.Format("Unknown Username {0} or incorrect password {1}", userName, password);
                        Trace.TraceWarning(msg);
                        throw new FaultException(msg);
                    }
                }

            }

        }
    }

Any suggestions would be highly appreciated.

回答1:

You are almost there, however, you need one more step to tell the WCF service to be well behaved through introducing service behavior, generally in config. For more details, please read

Authentication and Authorization with ASP.NET Identity 2.0 for WCF Services