コード例 #1
0
        /// <summary>
        /// Enables forms authentication for a module
        /// </summary>
        /// <param name="module">Module to add handlers to (usually "this")</param>
        /// <param name="configuration">Forms authentication configuration</param>
        public static void Enable(INancyModule module, FormsAuthenticationConfiguration configuration)
        {
            if (module == null)
            {
                throw new ArgumentNullException("module");
            }

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            configuration.EnsureConfigurationIsValid();

            module.RequiresAuthentication();

            currentConfiguration = configuration;

            module.Before.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));

            if (!configuration.DisableRedirect)
            {
                module.After.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration));
            }
        }
コード例 #2
0
ファイル: Bootstrap.cs プロジェクト: julianjelfs/geeks-nancy
        protected override void ApplicationStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            CookieBasedSessions.Enable(pipelines);

            Conventions.ViewLocationConventions.Add((viewName, model, context) => string.Concat("views/", viewName));

            Conventions.StaticContentsConventions.Add(
                StaticContentConventionBuilder.AddDirectory("assets", @"assets")
            );

            container.Register<IFlexUserStore, FlexMembershipUserStore<User, Role>>();
            container.Register(typeof(IDocumentStore), InitDocStore());
            container.Register(typeof(IDocumentSession), (c, overloads) =>
                c.Resolve<IDocumentStore>().OpenSession());

            var cryptographyConfiguration = new CryptographyConfiguration(
                new RijndaelEncryptionProvider(new PassphraseKeyGenerator(Configuration.EncryptionKey, new byte[] { 8, 2, 10, 4, 68, 120, 7, 14 })),
                new DefaultHmacProvider(new PassphraseKeyGenerator(Configuration.HmacKey, new byte[] { 1, 20, 73, 49, 25, 106, 78, 86 })));

            var authenticationConfiguration =
                new FormsAuthenticationConfiguration()
                {
                    CryptographyConfiguration = cryptographyConfiguration,
                    RedirectUrl = "/login",
                    UserMapper = container.Resolve<IUserMapper>(),
                };

            FormsAuthentication.Enable(pipelines, authenticationConfiguration);

            FlexMembershipProvider.RegisterClient(
                new GoogleOpenIdClient(),
                "Google", new Dictionary<string, object>());
        }
コード例 #3
0
ファイル: Bootstrapper.cs プロジェクト: henrikrtfm/Seerefine
        public static void ApplicationConfiguration(TinyIoCContainer container, IPipelines pipelines)
        {
            var cryptographyConfiguration = new CryptographyConfiguration(
                new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] {1, 2, 3, 4, 5, 6, 7, 8})),
                new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] {1, 2, 3, 4, 5, 6, 7, 8})));

            pipelines.AfterRequest.AddItemToEndOfPipeline(x =>
                {
                    x.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                    x.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS");
                });

            var formsAuthentication = new FormsAuthenticationConfiguration()
                {
                    CryptographyConfiguration = cryptographyConfiguration,
                    RedirectUrl = "~/weblogin",
                    UserMapper = container.Resolve<IUserMapper>(),
                };

            Nancy.Json.JsonSettings.MaxJsonLength = int.MaxValue;

            FormsAuthentication.Enable(pipelines, formsAuthentication);
            GlobalHost.DependencyResolver = new TinyIoCDependencyResolver(container);

            container.Register(typeof (StartableManager), new StartableManager(container));
        }
コード例 #4
0
        /// <summary>
        /// Initialise the bootstrapper - can be used for adding pre/post hooks and
        ///             any other initialisation tasks that aren't specifically container setup
        ///             related
        /// </summary>
        /// <param name="container">Container instance for resolving types if required.</param>
        /// <param name="pipelines">The pipelines used in this application.</param>
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            this.SetupDatabaseConnection();

            base.ApplicationStartup(container, pipelines);

            StaticConfiguration.EnableRequestTracing = true;

            pipelines.OnError += (ctx, ex) =>
            {
                Logger.Trace(ex, "On error message was triggered: {0}", ex.Message);
                return null;
            };

            SetUpTrackingCodes();

            var formsAuthConfiguration =
                new FormsAuthenticationConfiguration()
                {
                    RedirectUrl = "~/login",
                    UserMapper = container.Resolve<IUserMapper>()
                };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
        }
コード例 #5
0
        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            var formsAuthConfiguration =
                new FormsAuthenticationConfiguration()
                {
                    RedirectUrl = "~/login",
                    UserMapper = container.Resolve<IUserMapper>(),
                };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
            CookieBasedSessions.Enable(pipelines);

            pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx =>
                {
                    if (Helper.Settings.Instance.Client.CanConnect)
                        return null;
                    else
                    {
                        if (String.Compare(ctx.Request.Path, "/notavailable", true) == 0)
                        {
                            return null;
                        }
                        return new RedirectResponse("/notavailable");
                    }
                });

            base.RequestStartup(container, pipelines, context);
        }
コード例 #6
0
ファイル: TestUsersModule.cs プロジェクト: chrissie1/NancyVB
 public void FixtureSetup()
 {
     var formsAuthenticationConfiguration = new FormsAuthenticationConfiguration()
         {
             RedirectUrl = "~/login",
             UserMapper = new FakeUserMapper(new UserService())
         };
     var configuration = A.Fake<IRazorConfiguration>();
     var bootstrapper = new ConfigurableBootstrapper(config =>
         {
             config.Module<UsersModule>();
             config.Module<LoginModule>();
             config.ViewEngine(new RazorViewEngine(configuration));
         });
     var bootstrapper2 = new ConfigurableBootstrapper(config =>
         {
             config.Module<UsersModule>();
             config.Module<LoginModule>();
             config.ViewEngine(new RazorViewEngine(configuration));
             config.RequestStartup((x, pipelines, z) => FormsAuthentication.Enable(pipelines, formsAuthenticationConfiguration));
         });
     _notLoggedInBrowser = new Browser(bootstrapper);
     _loggedInBrowserResponse = new Browser(bootstrapper2).Post("/login", x =>
         {
             x.HttpRequest();
             x.FormValue("Username", "Chris1");
             x.FormValue("Password", "123");
         });
 }
コード例 #7
0
        /// <summary>
        /// Enables forms authentication for the application
        /// </summary>
        /// <param name="pipelines">Pipelines to add handlers to (usually "this")</param>
        /// <param name="configuration">Forms authentication configuration</param>
        public static void Enable(IPipelines pipelines, FormsAuthenticationConfiguration configuration)
        {
            if (pipelines == null)
            {
                throw new ArgumentNullException("pipelines");
            }

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (!configuration.IsValid)
            {
                throw new ArgumentException("Configuration is invalid", "configuration");
            }

            currentConfiguration = configuration;

            pipelines.BeforeRequest.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));
            if (!configuration.DisableRedirect)
            {
                pipelines.AfterRequest.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration));
            }
        }
コード例 #8
0
        //protected override void ConfigureApplicationContainer(TinyIoC.TinyIoCContainer container)
        //{
        //    // We don't call "base" here to prevent auto-discovery of
        //    // types/dependencies
        //}
        //protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
        //{
        //    base.ConfigureRequestContainer(container, context);
        //    // Here we register our user mapper as a per-request singleton.
        //    // As this is now per-request we could inject a request scoped
        //    // database "context" or other request scoped services.
        //    container.Register<IUserMapper, UserDatabase>();
        //}
        protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
        {
            // At request startup we modify the request pipelines to
            // include forms authentication - passing in our now request
            // scoped user name mapper.
            //
            // The pipelines passed in here are specific to this request,
            // so we can add/remove/update items in them as we please.
            var formsAuthConfiguration =
                new FormsAuthenticationConfiguration()
                {
                    RedirectUrl = "~/login",
                    UserMapper = requestContainer.Resolve<IUserMapper>(),
                };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);

            pipelines.AfterRequest.AddItemToEndOfPipeline(x =>
            {
                if (x.CurrentUser != null)
                    x.ViewBag.CurrentUserName = x.CurrentUser.UserName;
                else
                    x.ViewBag.CurrentUserName = null;
            });
        }
 public NancyAuthMiddleware(Func<IDictionary<string, object>, Task> next,
     FormsAuthenticationConfiguration formsAuthenticationConfiguration, 
     IUserManager userManager)
 {
     _next = next;
     _formsAuthenticationConfiguration = formsAuthenticationConfiguration;
     _userManager = userManager;
 }
コード例 #10
0
        /// <summary>
        /// Encrypt and sign the cookie contents
        /// </summary>
        /// <param name="cookieValue">Plain text cookie value</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Encrypted and signed string</returns>
        private static string EncryptAndSignCookie(string cookieValue, FormsAuthenticationConfiguration configuration)
        {
            var encryptedCookie = configuration.CryptographyConfiguration.EncryptionProvider.Encrypt(cookieValue);
            var hmacBytes       = GenerateHmac(encryptedCookie, configuration);
            var hmacString      = Convert.ToBase64String(hmacBytes);

            return(String.Format("{1}{0}", encryptedCookie, hmacString));
        }
コード例 #11
0
ファイル: Bootstrapper.cs プロジェクト: GraemeF/NerdBeers
        protected override void InitialiseInternal(TinyIoC.TinyIoCContainer container)
        {
            base.InitialiseInternal(container);
            var formsAuthConfiguration =
                new FormsAuthenticationConfiguration()
                {
                    Passphrase = "SuperSecretPass",
                    Salt = "AndVinegarCrisps",
                    HmacPassphrase = "UberSuperSecure",
                    RedirectUrl = "/authentication/login",
                    UsernameMapper = container.Resolve<IUsernameMapper>(),
                };

            FormsAuthentication.Enable(this, formsAuthConfiguration);

            BeforeRequest += ctx =>
            {
                var rootPathProvider =
                    container.Resolve<IRootPathProvider>();

                var staticFileExtensions =
                    new Dictionary<string, string>
                    {
                        { "jpg", "image/jpg" },
                        { "png", "image/png" },
                        { "gif", "image/gif" },
                        { "css", "text/css" },
                        { "js",  "text/javascript" }
                    };

                var requestedExtension =
                    Path.GetExtension(ctx.Request.Uri);

                if (!string.IsNullOrEmpty(requestedExtension))
                {
                    var extensionWithoutDot =
                        requestedExtension.Substring(1);

                    if (staticFileExtensions.Keys.Any(x => x.Equals(extensionWithoutDot, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        var fileName =
                            Path.GetFileName(ctx.Request.Uri);

                        if (fileName == null)
                        {
                            return null;
                        }

                        var filePath =
                            Path.Combine(rootPathProvider.GetRootPath(), "content", fileName);

                        return !File.Exists(filePath) ? null : new StaticFileResponse(filePath, staticFileExtensions[extensionWithoutDot]);
                    }
                }

                return null;
            };
        }
コード例 #12
0
 protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
 {
     var formsAuthConfiguration = new FormsAuthenticationConfiguration
     {
         RedirectUrl = "~/",
         UserMapper = requestContainer.Resolve<IUserMapper>(),
     };
     FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
 }
コード例 #13
0
ファイル: Bootstrapper.cs プロジェクト: slieser/sandbox
 protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context) {
     base.RequestStartup(container, pipelines, context);
     var formsAuthConfiguration =
         new FormsAuthenticationConfiguration {
             RedirectUrl = "~/login",
             UserMapper = new UserMapper(),
         };
     FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
 }
コード例 #14
0
 /// <summary>
 /// Gets the post request hook for redirecting to the login page
 /// </summary>
 /// <param name="configuration">Forms authentication configuration to use</param>
 /// <returns>Post request hook delegate</returns>
 private static Action <NancyContext> GetRedirectToLoginHook(FormsAuthenticationConfiguration configuration)
 {
     return(context =>
     {
         if (context.Response.StatusCode == HttpStatusCode.Unauthorized)
         {
             context.Response = new RedirectResponse(string.Format("{0}?{1}={2}", configuration.RedirectUrl, REDIRECT_QUERYSTRING_KEY, context.Request.Uri));
         }
     });
 }
コード例 #15
0
ファイル: MyBootstrapper.cs プロジェクト: ken200/Tokenken2
 protected override void RequestStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, NancyContext context)
 {
     base.RequestStartup(container, pipelines, context);
     var formsAuthConfiguration = new FormsAuthenticationConfiguration()
     {
         RedirectUrl = "/login", //認証失敗時のリダイレクト先
         UserMapper = container.Resolve<IUserMapper>()
     };
     FormsAuthentication.Enable(pipelines, formsAuthConfiguration);  //フォーム認証の有効化
 }
コード例 #16
0
        private void FormsAuthenticationRequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            var config = new FormsAuthenticationConfiguration
                             {
                                 RedirectUrl = "~/login",
                                 UserMapper = container.Resolve<IUserMapper>()
                             };

            FormsAuthentication.Enable(pipelines, config);
        }
コード例 #17
0
        protected override void ApplicationStartup(TinyIoC.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            var formsAuthConfig = new FormsAuthenticationConfiguration
                                      {
                                          RedirectUrl = "~/facebook/login",
                                          UserMapper = container.Resolve<IUserMapper>()
                                      };
            FormsAuthentication.Enable(pipelines, formsAuthConfig);
        }
コード例 #18
0
ファイル: Bootstrapper.cs プロジェクト: dgg/Dgg.10gen_M101
		protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
		{
			base.RequestStartup(container, pipelines, context);

			var authConfig = new FormsAuthenticationConfiguration()
			{
				RedirectUrl = "/login",
				UserMapper = container.Resolve<IUserMapper>(),
			};
			FormsAuthentication.Enable(ApplicationPipelines, authConfig);
		}
コード例 #19
0
    protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
    {
      CookieBasedSessions.Enable(pipelines);

      var formsAuthConfiguration = new FormsAuthenticationConfiguration
                                     {
                                       RedirectUrl = "~/login",
                                       UserMapper = container.Resolve<IUserMapper>(),
                                     };

      FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
    }
コード例 #20
0
        //private static Guid  = new Guid("2605D78D-C122-4F80-BDC6-1BB03D6F2289");
        //private static Guid Secure = new Guid("D88B72A4-BF95-4359-A0C4-CAF15FF020E6");
        //protected override CryptographyConfiguration CryptographyConfiguration => new CryptographyConfiguration(
        //    new RijndaelEncryptionProvider(new PassphraseKeyGenerator("CloudPass", Pass.ToByteArray())),
        //    new DefaultHmacProvider(new PassphraseKeyGenerator("CloudSecure", Secure.ToByteArray())));
        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(container, pipelines, context);

            var formsAuthConfiguration = new FormsAuthenticationConfiguration
            {
                CryptographyConfiguration = this.CryptographyConfiguration,
                UserMapper = container.Resolve<IUserMapper>(),
            };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
        }
コード例 #21
0
ファイル: Bootstrapper.cs プロジェクト: wang2650/nancyfx
 //}
 protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
 {
     Nancy.Security.Csrf.Enable(pipelines);
     var formsAuthConfiguration =
         new FormsAuthenticationConfiguration()
         {
             RedirectUrl = "~/Login",
             UserMapper = requestContainer.Resolve<IUserMapper>(),
         };
     AllowAccessToConsumingSite(pipelines);
     FormsAuthentication.Enable(pipelines, formsAuthConfiguration); //启用Forms 认证
 }
コード例 #22
0
        protected override void RequestStartup(TinyIoC.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            var formsAuthConfiguration =
                new FormsAuthenticationConfiguration
                    {
                    RedirectUrl = "~/login",
                    UserMapper = container.Resolve<IUserMapper>(),
                };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
            base.RequestStartup(container, pipelines);
        }
コード例 #23
0
ファイル: RequestStartup.cs プロジェクト: Firebuild/Firebuild
        private void EnableFormsAuthentication(IPipelines pipelines)
        {
            var formsAuthConfiguration = new FormsAuthenticationConfiguration
            {
                RedirectUrl = "/signin",
                RedirectQuerystringKey = "redirect",
                UserMapper = this.container.Resolve<IUserMapper>(),
                DisableRedirect = false
            };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
        }
コード例 #24
0
        /// <summary>
        /// Encrypt and sign the cookie contents
        /// </summary>
        /// <param name="cookieValue">Plain text cookie value</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Encrypted and signed string</returns>
        private static string EncryptAndSignCookie(string cookieValue, FormsAuthenticationConfiguration configuration)
        {
            var passPhrase         = configuration.Passphrase;
            var salt               = configuration.SaltBytes;
            var encryptionProvider = configuration.EncryptionProvider;

            var encryptedCookie = encryptionProvider.Encrypt(cookieValue, passPhrase, salt);
            var hmacBytes       = GenerateHmac(encryptedCookie, configuration);
            var hmacString      = Convert.ToBase64String(hmacBytes);

            return(String.Format("{1}{0}", encryptedCookie, hmacString));
        }
コード例 #25
0
 protected override void ApplicationStartup(IKernel kernel, IPipelines pipelines)
 {
     var formsAuthConfiguration = new FormsAuthenticationConfiguration()
     {
         RedirectUrl = "~/login",
         UserMapper = kernel.Get<IUserMapper>(),
         DisableRedirect = true
     };
     FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
     pipelines.OnError += (ctx, ex) => ArgumentExceptionReact(ex);
     pipelines.OnError += (ctx, ex) => ExceptionReact(ex);
     base.ApplicationStartup(kernel, pipelines);
 }
コード例 #26
0
ファイル: Program.cs プロジェクト: jonathanvdc/smarthomeweb
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            StaticConfiguration.DisableErrorTraces = false;
            StaticConfiguration.EnableRequestTracing = true;
            CookieBasedSessions.Enable(pipelines);

            var formsAuthConfiguration = new FormsAuthenticationConfiguration
                {
                    RedirectUrl = "~/login",
                    UserMapper = container.Resolve<IUserMapper>()
                };
            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
        }
コード例 #27
0
ファイル: Bootstrapper.cs プロジェクト: Breeto/MatchMaker
        protected override void RequestStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(container, pipelines, context);

            var formsAuthenticationConfiguration = new FormsAuthenticationConfiguration
            {
                RedirectUrl = Route.Login,
                UserMapper = container.Resolve<IUserMapper>(),
            };
            FormsAuthentication.Enable( pipelines, formsAuthenticationConfiguration );

            LayoutViewBagInitializer.Enable( pipelines, container.Resolve<IDatabase>() );
        }
コード例 #28
0
        protected override void InitialiseInternal(IContainer container)
        {
            base.InitialiseInternal(container);

            var formsAuthConfiguration =
                new FormsAuthenticationConfiguration()
                {
                    RedirectUrl = "~/login",
                    UsernameMapper = container.GetInstance<IUsernameMapper>()
                };

            FormsAuthentication.Enable(this, formsAuthConfiguration);
        }
コード例 #29
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            var formsAuthConfiguration =
                new FormsAuthenticationConfiguration()
                {
                    RedirectUrl = "~/login",
                    UserMapper = container.Resolve<IUserMapper>()
                };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
        }
コード例 #30
0
        protected override void InitialiseInternal(TinyIoC.TinyIoCContainer container)
        {
            base.InitialiseInternal(container);

            var formsAuthConfiguration =
                new FormsAuthenticationConfiguration()
                {
                    RedirectUrl = "~/login",
                    UserMapper = container.Resolve<IUserMapper>(),
                };

            FormsAuthentication.Enable(this, formsAuthConfiguration);
        }
コード例 #31
0
        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(container, pipelines, context);

            var formsAuthConfiguration = new FormsAuthenticationConfiguration
            {
                RedirectUrl = "http://localhost:3579/account/login",
                UserMapper = container.Resolve<IUserMapper>()
            };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
           
        }
コード例 #32
0
        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(container, pipelines, context);

            var formsAuthConfiguration =
                new FormsAuthenticationConfiguration()
                {
                    RedirectUrl = "~/signin",
                    UserMapper = container.Resolve<IUserMapper>(),
                };

            Csrf.Enable(pipelines);
            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
        }
コード例 #33
0
        protected override void RequestStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, Nancy.NancyContext context)
        {
            base.RequestStartup(container, pipelines, context);

            var formsAuthConfiguration = new FormsAuthenticationConfiguration
            {
                RedirectUrl = "~/login",
                UserMapper = new UserMapper(),
                RequiresSSL = true,
                DisableRedirect = (context.Request.Headers.Keys.Contains("Client") && context.Request.Headers["Client"].Contains("RichClient")) || context.Request.Url.Path.Contains("/login")
            };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
        }
コード例 #34
0
ファイル: FormsAuthentication.cs プロジェクト: rmueller/Nancy
 /// <summary>
 /// Gets the post request hook for redirecting to the login page
 /// </summary>
 /// <param name="configuration">Forms authentication configuration to use</param>
 /// <returns>Post request hook delegate</returns>
 private static Action <NancyContext> GetRedirectToLoginHook(FormsAuthenticationConfiguration configuration)
 {
     return(context =>
     {
         if (context.Response.StatusCode == HttpStatusCode.Unauthorized)
         {
             context.Response = context.GetRedirect(
                 string.Format("{0}?{1}={2}",
                               configuration.RedirectUrl,
                               REDIRECT_QUERYSTRING_KEY,
                               context.ToFullPath("~" + context.Request.Path + HttpUtility.UrlEncode(context.Request.Url.Query))));
         }
     });
 }
コード例 #35
0
        /// <summary>
        /// Builds a cookie for logging a user out
        /// </summary>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Nancy cookie instance</returns>
        private static INancyCookie BuildLogoutCookie(FormsAuthenticationConfiguration configuration)
        {
            var cookie = new NancyCookie(formsAuthenticationCookieName, String.Empty, true, configuration.RequiresSSL, DateTime.Now.AddDays(-1));

            if (!string.IsNullOrEmpty(configuration.Domain))
            {
                cookie.Domain = configuration.Domain;
            }

            if (!string.IsNullOrEmpty(configuration.Path))
            {
                cookie.Path = configuration.Path;
            }

            return(cookie);
        }
コード例 #36
0
        /// <summary>
        /// Gets the redirect query string key from <see cref="FormsAuthenticationConfiguration"/>
        /// </summary>
        /// <param name="configuration">The forms authentication configuration.</param>
        /// <returns>Redirect Querystring key</returns>
        private static string GetRedirectQuerystringKey(FormsAuthenticationConfiguration configuration)
        {
            string redirectQuerystringKey = null;

            if (configuration != null)
            {
                redirectQuerystringKey = configuration.RedirectQuerystringKey;
            }

            if (string.IsNullOrWhiteSpace(redirectQuerystringKey))
            {
                redirectQuerystringKey = FormsAuthenticationConfiguration.DefaultRedirectQuerystringKey;
            }

            return(redirectQuerystringKey);
        }
コード例 #37
0
        /// <summary>
        /// Gets the authenticated user GUID from the incoming request cookie if it exists
        /// and is valid.
        /// </summary>
        /// <param name="context">Current context</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Returns user guid, or Guid.Empty if not present or invalid</returns>
        private static Guid GetAuthenticatedUserFromCookie(NancyContext context, FormsAuthenticationConfiguration configuration)
        {
            if (!context.Request.Cookies.ContainsKey(formsAuthenticationCookieName))
            {
                return(Guid.Empty);
            }

            var cookieValue = DecryptAndValidateAuthenticationCookie(context.Request.Cookies[formsAuthenticationCookieName], configuration);

            Guid returnGuid;

            if (String.IsNullOrEmpty(cookieValue) || !Guid.TryParse(cookieValue, out returnGuid))
            {
                return(Guid.Empty);
            }

            return(returnGuid);
        }
コード例 #38
0
        /// <summary>
        /// Gets the pre request hook for loading the authenticated user's details
        /// from the cookie.
        /// </summary>
        /// <param name="configuration">Forms authentication configuration to use</param>
        /// <returns>Pre request hook delegate</returns>
        private static Func <NancyContext, Response> GetLoadAuthenticationHook(FormsAuthenticationConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            return(context =>
            {
                var userGuid = GetAuthenticatedUserFromCookie(context, configuration);

                if (userGuid != Guid.Empty)
                {
                    context.CurrentUser = configuration.UserMapper.GetUserFromIdentifier(userGuid, context);
                }

                return null;
            });
        }
コード例 #39
0
ファイル: FormsAuthentication.cs プロジェクト: rmueller/Nancy
        /// <summary>
        /// Enables forms authentication for the application
        /// </summary>
        /// <param name="applicationPipelines">Pipelines to add handlers to (usually "this")</param>
        /// <param name="configuration">Forms authentication configuration</param>
        public static void Enable(IApplicationPipelines applicationPipelines, FormsAuthenticationConfiguration configuration)
        {
            if (applicationPipelines == null)
            {
                throw new ArgumentNullException("applicationPipelines");
            }

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (!configuration.IsValid)
            {
                throw new ArgumentException("Configuration is invalid", "configuration");
            }

            currentConfiguration = configuration;

            applicationPipelines.BeforeRequest.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));
            applicationPipelines.AfterRequest.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration));
        }
コード例 #40
0
        /// <summary>
        /// Enables forms authentication for the application
        /// </summary>
        /// <param name="pipelines">Pipelines to add handlers to (usually "this")</param>
        /// <param name="configuration">Forms authentication configuration</param>
        public static void Enable(IPipelines pipelines, FormsAuthenticationConfiguration configuration)
        {
            if (pipelines == null)
            {
                throw new ArgumentNullException("pipelines");
            }

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            configuration.EnsureConfigurationIsValid();

            currentConfiguration = configuration;

            pipelines.BeforeRequest.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));
            if (!configuration.DisableRedirect)
            {
                pipelines.AfterRequest.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration));
            }
        }
コード例 #41
0
        /// <summary>
        /// Gets the pre request hook for loading the authenticated user's details
        /// from the cookie.
        /// </summary>
        /// <param name="configuration">Forms authentication configuration to use</param>
        /// <returns>Pre request hook delegate</returns>
        private static Func <NancyContext, Response> GetLoadAuthenticationHook(FormsAuthenticationConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            return(context =>
            {
                var userGuid = GetAuthenticatedUserFromCookie(context, configuration);

                if (userGuid == Guid.Empty)
                {
                    return null;
                }

                context.Items[SecurityConventions.AuthenticatedUsernameKey] =
                    configuration.UsernameMapper.GetUsernameFromIdentifier(userGuid);

                return null;
            });
        }
コード例 #42
0
        /// <summary>
        /// Decrypt and validate an encrypted and signed cookie value
        /// </summary>
        /// <param name="cookieValue">Encrypted and signed cookie value</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Decrypted value, or empty on error or if failed validation</returns>
        public static string DecryptAndValidateAuthenticationCookie(string cookieValue, FormsAuthenticationConfiguration configuration)
        {
            var hmacStringLength = Base64Helpers.GetBase64Length(configuration.CryptographyConfiguration.HmacProvider.HmacLength);

            var encryptedCookie = cookieValue.Substring(hmacStringLength);
            var hmacString      = cookieValue.Substring(0, hmacStringLength);

            var encryptionProvider = configuration.CryptographyConfiguration.EncryptionProvider;

            // Check the hmacs, but don't early exit if they don't match
            var hmacBytes = Convert.FromBase64String(hmacString);
            var newHmac   = GenerateHmac(encryptedCookie, configuration);
            var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, configuration.CryptographyConfiguration.HmacProvider.HmacLength);

            var decrypted = encryptionProvider.Decrypt(encryptedCookie);

            // Only return the decrypted result if the hmac was ok
            return(hmacValid ? decrypted : string.Empty);
        }
コード例 #43
0
        /// <summary>
        /// Build the forms authentication cookie
        /// </summary>
        /// <param name="userIdentifier">Authenticated user identifier</param>
        /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Nancy cookie instance</returns>
        private static INancyCookie BuildCookie(Guid userIdentifier, DateTime?cookieExpiry, FormsAuthenticationConfiguration configuration)
        {
            var cookieContents = EncryptAndSignCookie(userIdentifier.ToString(), configuration);

            var cookie = new NancyCookie(formsAuthenticationCookieName, cookieContents, true, configuration.RequiresSSL)
            {
                Expires = cookieExpiry
            };

            return(cookie);
        }
コード例 #44
0
        /// <summary>
        /// Decrypt and validate an encrypted and signed cookie value
        /// </summary>
        /// <param name="cookieValue">Encrypted and signed cookie value</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Decrypted value, or empty on error or if failed validation</returns>
        public static string DecryptAndValidateAuthenticationCookie(string cookieValue, FormsAuthenticationConfiguration configuration)
        {
            // TODO - shouldn't this be automatically decoded by nancy cookie when that change is made?
            var decodedCookie = Helpers.HttpUtility.UrlDecode(cookieValue);

            var hmacStringLength = Base64Helpers.GetBase64Length(configuration.CryptographyConfiguration.HmacProvider.HmacLength);

            var encryptedCookie = decodedCookie.Substring(hmacStringLength);
            var hmacString      = decodedCookie.Substring(0, hmacStringLength);

            var encryptionProvider = configuration.CryptographyConfiguration.EncryptionProvider;

            // Check the hmacs, but don't early exit if they don't match
            var hmacBytes = Convert.FromBase64String(hmacString);
            var newHmac   = GenerateHmac(encryptedCookie, configuration);
            var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, configuration.CryptographyConfiguration.HmacProvider.HmacLength);

            var decrypted = encryptionProvider.Decrypt(encryptedCookie);

            // Only return the decrypted result if the hmac was ok
            return(hmacValid ? decrypted : string.Empty);
        }
コード例 #45
0
        /// <summary>
        /// Build the forms authentication cookie
        /// </summary>
        /// <param name="userIdentifier">Authenticated user identifier</param>
        /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Nancy cookie instance</returns>
        private static INancyCookie BuildCookie(Guid userIdentifier, DateTime?cookieExpiry, FormsAuthenticationConfiguration configuration)
        {
            var cookieContents = EncryptAndSignCookie(userIdentifier.ToString(), configuration);

            var cookie = new NancyCookie(formsAuthenticationCookieName, cookieContents, true, configuration.RequiresSSL, cookieExpiry);

            if (!string.IsNullOrEmpty(configuration.Domain))
            {
                cookie.Domain = configuration.Domain;
            }

            if (!string.IsNullOrEmpty(configuration.Path))
            {
                cookie.Path = configuration.Path;
            }

            return(cookie);
        }
コード例 #46
0
 /// <summary>
 /// Generate a hmac for the encrypted cookie string
 /// </summary>
 /// <param name="encryptedCookie">Encrypted cookie string</param>
 /// <param name="configuration">Current configuration</param>
 /// <returns>Hmac byte array</returns>
 private static byte[] GenerateHmac(string encryptedCookie, FormsAuthenticationConfiguration configuration)
 {
     return(configuration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedCookie));
 }