programmatic login with .net membership provider

随声附和 提交于 2019-11-29 19:38:45

问题


I'm trying to unit test a piece of code that needs a currently logged in user in the test. Using the .Net 2.0 Membership Provider, how can I programmatically log in as a user for this test?


回答1:


if(Membership.ValidateUser("user1",P@ssw0rd))
        {
            FormsAuthentication.SetAuthCookie("user1",true); 
}



回答2:


I've found it most convenient to create a disposable class that handles setting and resetting Thread.CurrentPrincipal.

    public class TemporaryPrincipal : IDisposable {
        private readonly IPrincipal _cache;

        public TemporaryPrincipal(IPrincipal tempPrincipal) {
            _cache = Thread.CurrentPrincipal;
            Thread.CurrentPrincipal = tempPrincipal;
        }

        public void Dispose() {
            Thread.CurrentPrincipal = _cache;
        }
    }

In the test method you just wrap your call with a using statement like this:

using (new TemporaryPrincipal(new AnonymousUserPrincipal())) {
    ClassUnderTest.MethodUnderTest();
}



回答3:


Does your code actually need a user logged in via ASP.NET, or does it just need a CurrentPrincipal? I don't think you need to programmatically log in to your site. You can create a GenericPrincipal, set the properties you need, and attach it to, for example Thread.CurrentPrincipal or a mocked HttpContext. If your code actually needs RolePrincipal or something then I would change the code to be less coupled to ASP.NET membership.




回答4:


Using your Membership Provider you can validate a user using Membership.ValidateUser. Then you can set the authentication cookie using FormsAuthentication.SetAuthCookie. As long as you have a cookie container this should allow you to log in a user.



来源:https://stackoverflow.com/questions/243851/programmatic-login-with-net-membership-provider

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