public void SetUp()
 {
     _helper   = MockRepository.GenerateMock <IFormsAuthenticationHelper>();
     _provider = FormsAuthenticationProvider.CreateWithNoRedirectOnFailedAuthentication(_helper);
     _request  = MockRepository.GenerateMock <HttpRequestBase>();
     _response = _provider.GetFailedAuthenticationResponseAsync(_request).Result;
 }
        /// <summary>
        /// Inspects the environment and checks to see if this is a POST containing the HTML form fields in the login.html page.
        /// </summary>
        /// <param name="environment"></param>
        /// <param name="formsAuthenticationProvider"></param>
        public LoginContext(IDictionary <string, object> environment, FormsAuthenticationProvider formsAuthenticationProvider)
        {
            _environment = environment;
            Request      = new OwinRequest(environment);
            Response     = new OwinResponse(environment);

            _formsAuthenticationProvider = formsAuthenticationProvider;

            _responseStream = Response.Body;

            var requestContentType = Request.GetHeader("Content-Type");

            _isFormUrlEncodedPost = Request.Method == "POST" && !string.IsNullOrEmpty(requestContentType) && requestContentType.StartsWith("application/x-www-form-urlencoded");

            if (_isFormUrlEncodedPost && Request.Body != null)
            {
                _formData = Request.ReadForm().Result;

                var username   = _formData["login_username"];
                var password   = _formData["login_password"];
                var rememberMe = _formData["remember_me"] != null && _formData["remember_me"] == "yes";

                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    environment["formsauthn.username"] = username;
                    environment["formsauthn.password"] = password;
                    environment["formsauthn.remember"] = rememberMe;
                }
            }
        }
예제 #3
0
 public static IAppBuilder UseProcessLoginPostback(this IAppBuilder builder, FormsAuthenticationProvider formsAuthenticationProvider)
 {
     if (builder == null)
     {
         throw new ArgumentNullException("builder");
     }
     return(builder.Use(typeof(LoginFormMiddleware), formsAuthenticationProvider));
 }
예제 #4
0
        public static void LogOff(this IUser user)
        {
            AuthenticationProvider.LogOff(user);

            HttpContext.Current.Session.Perform(s => s.Abandon());

            // In case of migration to Owin, the legacy cookie should be removed for users already logged in.
            FormsAuthenticationProvider.LogOffFormsAuthentication();
        }
예제 #5
0
        /// <summary>
        /// Validates wheether the current user and password fits together.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="args">
        /// The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.
        /// </param>
        private static void OnValidate(object source, ServerValidateEventArgs args)
        {
            ICustomerManager<CustomerInfo> customerManager = Ecommerce.Context.Entity.Resolve<ICustomerManager<CustomerInfo>>();
              string username = customerManager.CurrentUser.NickName;

              var provider = new FormsAuthenticationProvider();
              var helper = new AuthenticationHelper(provider);
              args.IsValid = helper.ValidateUser(username, args.Value);
        }
예제 #6
0
        /// <summary>
        /// Validates wheether the current user and password fits together.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="args">
        /// The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.
        /// </param>
        private static void OnValidate(object source, ServerValidateEventArgs args)
        {
            ICustomerManager <CustomerInfo> customerManager = Ecommerce.Context.Entity.Resolve <ICustomerManager <CustomerInfo> >();
            string username = customerManager.CurrentUser.NickName;

            var provider = new FormsAuthenticationProvider();
            var helper   = new AuthenticationHelper(provider);

            args.IsValid = helper.ValidateUser(username, args.Value);
        }
 public void SetUp()
 {
     _urlResolver = MockRepository.GenerateMock <IUrlResolver>();
     _urlResolver.Stub(arg => arg.Absolute("relative")).Return("/absolute");
     _helper   = MockRepository.GenerateMock <IFormsAuthenticationHelper>();
     _provider = FormsAuthenticationProvider.CreateWithRelativeUrlRedirectOnFailedAuthentication(_helper, _urlResolver, "relative", null);
     _request  = MockRepository.GenerateMock <HttpRequestBase>();
     _request.Stub(arg => arg.HttpMethod).Return("POST");
     _response = _provider.GetFailedAuthenticationResponseAsync(_request).Result;
 }
 public void SetUp()
 {
     _urlResolver = MockRepository.GenerateMock <IUrlResolver>();
     _urlResolver.Stub(arg => arg.Route("route")).Return("/route");
     _helper   = MockRepository.GenerateMock <IFormsAuthenticationHelper>();
     _provider = FormsAuthenticationProvider.CreateWithRouteRedirectOnFailedAuthentication(_helper, _urlResolver, "route");
     _request  = MockRepository.GenerateMock <HttpRequestBase>();
     _request.Stub(arg => arg.RawUrl).Return("/return");
     _response = _provider.GetFailedAuthenticationResponseAsync(_request).Result;
 }
예제 #9
0
        public LoginFormMiddleware(Func <IDictionary <string, object>, Task> next, FormsAuthenticationProvider formsAuthenticationProvider)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            if (formsAuthenticationProvider == null)
            {
                throw new ArgumentNullException("formsAuthenticationProvider");
            }

            _next = next;
            _formsAuthenticationProvider = formsAuthenticationProvider;
        }
예제 #10
0
 public AutoRouteCollection FormsAuthenticationWithRouteRedirectWhenAttributePresent(IFormsAuthenticationHelper helper, IUrlResolver urlResolver, Guid routeId, string returnUrlQueryStringField = "ReturnURL")
 {
     return(Authenticate(FormsAuthenticationProvider.CreateWithRouteRedirectOnFailedAuthentication(helper, urlResolver, routeId, returnUrlQueryStringField), new AuthenticateAttributeStrategy()));
 }
예제 #11
0
 public AutoRouteCollection FormsAuthenticationWithNoRedirectWhenAttributePresent(IFormsAuthenticationHelper helper)
 {
     return(Authenticate(FormsAuthenticationProvider.CreateWithNoRedirectOnFailedAuthentication(helper), new AuthenticateAttributeStrategy()));
 }
예제 #12
0
        public void Configuration(IAppBuilder builder)
        {
            var rootDirectory  = Environment.CurrentDirectory;
            var loginDirectory = Path.Combine(rootDirectory, "login");

            var fs      = new PhysicalFileSystem(rootDirectory);
            var loginFs = new PhysicalFileSystem(loginDirectory);

            var dfo = new DefaultFilesOptions();

            dfo.DefaultFileNames.Add("index.html");
            dfo.FileSystem = fs;

            var sfo = new StaticFileOptions
            {
                FileSystem = fs
            };
            var loginSfo = new StaticFileOptions
            {
                FileSystem = loginFs
            };

            builder.SetDataProtectionProvider(new DpapiDataProtectionProvider());
            var formsAuthenticationProvider = new FormsAuthenticationProvider();


            formsAuthenticationProvider.OnValidateLogin = context =>
            {
                Console.WriteLine("Validating Login");
                Console.WriteLine("================");
                Console.WriteLine("  Context.AuthType: " + context.AuthenticationType);
                Console.WriteLine("  Context.Identity: " + (context.Identity != null ? context.Identity.Name : "Not set"));
                Console.WriteLine("  Context.Environment:");

                var response = new OwinResponse(context.Environment);

                if (LoginContext.GetIsLoginRequest(context.Environment))
                {
                    // Need to retrieve username and password from environment b/c it doesn't
                    // come through in the context (even though the context constructor accepts them)

                    var username = context.Environment["formsauthn.username"].ToString();
                    var password = context.Environment["formsauthn.password"].ToString();
                    var remember = bool.Parse(context.Environment["formsauthn.remember"].ToString());

                    Console.WriteLine("  Request.Username: "******"  Request.Password: "******"  Request.Remember: " + remember);

                    if (username == password)
                    {
                        var identity = new ClaimsIdentity(
                            new GenericIdentity(username, context.AuthenticationType),
                            new[]
                        {
                            new Claim(ClaimTypes.IsPersistent, remember.ToString())
                        }
                            );

                        // I assumed that this would take care of populating the cookie for me... but not so much.
                        context.Signin(identity);

                        var msg = "Access granted.";
                        Console.WriteLine(msg);
                        var msgBytes = Encoding.UTF8.GetBytes(msg);
                        return(response.Body.WriteAsync(msgBytes, 0, msgBytes.Length));
                    }
                    else
                    {
                        var msg = "Access denied.  Try with username=password";
                        Console.WriteLine(msg);
                        var msgBytes = Encoding.UTF8.GetBytes(msg);
                        return(response.Body.WriteAsync(msgBytes, 0, msgBytes.Length));
                    }
                }
                else
                {
                    foreach (var item in context.Environment)
                    {
                        Console.WriteLine("  {0}={1}",
                                          item.Key,
                                          item.Value != null
                                              ? (item.Value is string?(string)item.Value: item.Value.GetType().FullName)
                                              : "Not set"
                                          );
                    }
                }

                return(response.Body.WriteAsync(new byte[] { }, 0, 0));
            };


            builder.UseFormsAuthentication(
                new FormsAuthenticationOptions
            {
                CookieHttpOnly     = true,
                CookieName         = "AuthCookie",
                CookiePath         = "/",
                CookieSecure       = false,
                LoginPath          = "/login/",
                ExpireTimeSpan     = TimeSpan.FromHours(1),
                ReturnUrlParameter = "returnUrl",
                SlidingExpiration  = true,
                Provider           = formsAuthenticationProvider
            }
                );
            builder.UseApplicationSignInCookie();
            builder.UseDefaultFiles(dfo);
            builder.UseErrorPage();
            builder.MapPath("/login", loginBuilder => loginBuilder.UseProcessLoginPostback(formsAuthenticationProvider).UseStaticFiles(loginSfo));
            builder.UseDenyAnonymous().UseStaticFiles(sfo);
        }