Exemple #1
0
        public void Configure(XmlElement configurationElement)
        {
            var validatorEl = configurationElement.GetElementsByTagName("validator")
                              .OfType <XmlElement>().FirstOrDefault(x => x.HasAttribute("type"));

            if (validatorEl == null)
            {
                throw new ConfigurationErrorsException("Missing required validator element for Basic Authentication authentication provider.");
            }

            var validatorType = Type.GetType(validatorEl.GetAttribute("type"));

            if (validatorType == null)
            {
                throw new ConfigurationErrorsException(String.Format("Cannot resolve validator type '{0}'", validatorEl.GetAttribute("type")));
            }

            var userValidator = Activator.CreateInstance(validatorType) as IUserValidator;

            if (userValidator == null)
            {
                throw new ConfigurationErrorsException(String.Format("Type {0} does not implement the IUserValidator interface.", validatorType.FullName));
            }

            if (userValidator is IConfigurableUserValidator)
            {
                (userValidator as IConfigurableUserValidator).Configure(validatorEl);
            }

            var realmEl = configurationElement.GetElementsByTagName("realm").OfType <XmlElement>().FirstOrDefault();
            var realm   = realmEl == null ? "BrightstarDB" : realmEl.InnerText;

            _configuration = new BasicAuthenticationConfiguration(userValidator, realm);
        }
        public void Post_request_hook_should_not_return_a_challenge_on_an_ajax_request_when_set_to_nonajax()
        {
            // Given
            var config = new BasicAuthenticationConfiguration(A.Fake <IUserValidator>(), "realm", UserPromptBehaviour.NonAjax);
            var hooks  = new Pipelines();

            BasicAuthentication.Enable(hooks, config);
            var headers = new Dictionary <string, IEnumerable <string> >();

            headers.Add(ajaxRequestHeaderKey, new [] { ajaxRequestHeaderValue });

            var context = new NancyContext()
            {
                Request = new FakeRequest("GET", "/", headers)
            };

            context.Response = new Response {
                StatusCode = HttpStatusCode.Unauthorized
            };

            // When
            hooks.AfterRequest.Invoke(context, new CancellationToken());

            // Then
            context.Response.Headers.ContainsKey("WWW-Authenticate").ShouldBeFalse();
        }
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            var configuration = new BasicAuthenticationConfiguration(container.Resolve <IUserValidator>(),
                                                                     "MyRealm",
                                                                     UserPromptBehaviour.NonAjax);

            pipelines.EnableBasicAuthentication(configuration);
        }
Exemple #4
0
        private void EnableBasicAuth(IUnityContainer container, IPipelines pipelines)
        {
            var config =
                new BasicAuthenticationConfiguration(
                    container.Resolve <IUserValidator>()
                    , "you need login"
                    , UserPromptBehaviour.NonAjax);

            BasicAuthentication.Enable(pipelines, config);
        }
 public BasicAuthenticationFixture()
 {
     this.config = new BasicAuthenticationConfiguration(A.Fake<IUserValidator>(), "realm");
     this.context = new NancyContext()
     {
         Request = new FakeRequest("GET", "/")
     };
     this.hooks = new FakeApplicationPipelines();
     BasicAuthentication.Enable(this.hooks, this.config);
 }
Exemple #6
0
            protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
            {
                base.ApplicationStartup(container, pipelines);

                var configuration = new BasicAuthenticationConfiguration(
                    container.Resolve <IUserValidator>(),
                    "MessageVault"
                    );

                pipelines.EnableBasicAuthentication(configuration);
            }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var path = Path.Combine(_path, _jsonFileName);

            services.AddSingleton <IDataStore>(new DataStore(path, reloadBeforeGetCollection: Configuration.GetValue <bool>("Common:EagerDataReload")));
            services.AddSingleton <IMessageBus, MessageBus>();
            services.AddSingleton(typeof(JobsService));

            services.Configure <AuthenticationSettings>(Configuration.GetSection("Authentication"));
            services.Configure <ApiSettings>(Configuration.GetSection("Api"));
            services.Configure <JobsSettings>(Configuration.GetSection("Jobs"));
            services.Configure <SimulateSettings>(Configuration.GetSection("Simulate"));

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAnyPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            if (Configuration.GetValue <bool>("Authentication:Enabled"))
            {
                if (Configuration.GetValue <string>("Authentication:AuthenticationType") == "token")
                {
                    TokenConfiguration.Configure(services);
                }
                else
                {
                    BasicAuthenticationConfiguration.Configure(services);
                }
            }
            else
            {
                AllowAllAuthenticationConfiguration.Configure(services);
            }

            services.AddMvc();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Fake JSON API", Version = "v1"
                });

                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "FakeServer.xml");
                c.IncludeXmlComments(xmlPath);
            });
        }
        private bool IsAuthorized(BasicAuthenticationConfiguration config, AuthenticationHeaderValue header)
        {
            var credentials = GetCredentials(header);

            if (credentials.Length != 2)
            {
                return(false);
            }

            var userName = credentials[0];
            var password = credentials[1];

            return(config.UserName == userName && config.Password == password);
        }
        public void Post_request_hook_should_not_return_a_challenge_when_set_to_never()
        {
            // Given
            var config = new BasicAuthenticationConfiguration(A.Fake<IUserValidator>(), "realm", UserPromptBehaviour.Never);
            var hooks = new Pipelines();
            BasicAuthentication.Enable(hooks, config);

            var context = new NancyContext()
            {
                Request = new FakeRequest("GET", "/")
            };

            context.Response = new Response { StatusCode = HttpStatusCode.Unauthorized };

            // When
            hooks.AfterRequest.Invoke(context);

            // Then
            context.Response.Headers.ContainsKey("WWW-Authenticate").ShouldBeFalse();
        }
        public void Post_request_hook_should_not_return_a_challenge_on_an_ajax_request_when_set_to_nonajax()
        {
            // Given
            var config = new BasicAuthenticationConfiguration(A.Fake<IUserValidator>(), "realm", UserPromptBehaviour.NonAjax);
            var hooks = new Pipelines();
            BasicAuthentication.Enable(hooks, config);
            var headers = new Dictionary<string,IEnumerable<string>>();
            headers.Add(ajaxRequestHeaderKey, new [] { ajaxRequestHeaderValue });

            var context = new NancyContext()
            {
                Request = new FakeRequest("GET", "/", headers)
            };

            context.Response = new Response { StatusCode = HttpStatusCode.Unauthorized };

            // When
            hooks.AfterRequest.Invoke(context);

            // Then
            context.Response.Headers.ContainsKey("WWW-Authenticate").ShouldBeFalse();
        }
        public void Post_request_hook_should_not_return_a_challenge_when_set_to_never()
        {
            // Given
            var config = new BasicAuthenticationConfiguration(A.Fake <IUserValidator>(), "realm", UserPromptBehaviour.Never);
            var hooks  = new Pipelines();

            BasicAuthentication.Enable(hooks, config);

            var context = new NancyContext()
            {
                Request = new FakeRequest("GET", "/")
            };

            context.Response = new Response {
                StatusCode = HttpStatusCode.Unauthorized
            };

            // When
            hooks.AfterRequest.Invoke(context, new CancellationToken());

            // Then
            context.Response.Headers.ContainsKey("WWW-Authenticate").ShouldBeFalse();
        }
        public void Should_set_user_in_context_with_valid_username_in_auth_header()
        {
            // Given
            var fakePipelines = new Pipelines();

            var validator = A.Fake <IUserValidator>();
            var fakeUser  = A.Fake <ClaimsPrincipal>();

            A.CallTo(() => validator.Validate("foo", "bar")).Returns(fakeUser);

            var cfg = new BasicAuthenticationConfiguration(validator, "realm");

            var context = CreateContextWithHeader(
                "Authorization", new [] { "Basic" + " " + EncodeCredentials("foo", "bar") });

            BasicAuthentication.Enable(fakePipelines, cfg);

            // When
            fakePipelines.BeforeRequest.Invoke(context, new CancellationToken());

            // Then
            context.CurrentUser.ShouldBeSameAs(fakeUser);
        }
Exemple #13
0
        private void ConfigureAuth(IServiceCollection services)
        {
            var authConfig = new BasicAuthenticationConfiguration();

            this._configuration.Bind("BasicAuthentication", authConfig);

            if (authConfig.IsDisabled)
            {
                return;
            }

            Func <(string username, string password), Task <bool> > verifyDelegate = null;

            if (!string.IsNullOrEmpty(authConfig.Proxy))
            {
                _loggerFactory.CreateLogger <Startup>().LogInformation("Using ProxyAuthentication: {proxy}", authConfig.Proxy);
                verifyDelegate = new ProxyCredentialVerifier(new Uri(authConfig.Proxy)).Verify;
            }
            else if (authConfig.IsSimple)
            {
                _loggerFactory.CreateLogger <Startup>().LogInformation("Using UsernameEqualsPasswordCredentialVerifier");
                verifyDelegate = new UsernameEqualsPasswordCredentialVerifier().Verify;
            }

            if (verifyDelegate != null)
            {
                services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
                .AddBasicAuthentication(verifyDelegate);
                return;
            }


            var msg = "Authentication is not configured";

            _loggerFactory.CreateLogger <Startup>().LogError(msg);
            throw new Exception(msg);
        }
 public BasicAuthenticationFixture()
 {
     this.config = new BasicAuthenticationConfiguration(A.Fake<IUserValidator>(), "realm");
     this.hooks = new FakeApplicationPipelines();
     BasicAuthentication.Enable(this.hooks, this.config);
 }
Exemple #15
0
 public BasicAuthAuthenticationProvider(BasicAuthenticationConfiguration configuration)
 {
     _configuration = configuration;
 }
 public BasicAuthenticationFixture()
 {
     this.config = new BasicAuthenticationConfiguration(A.Fake <IUserValidator>(), "realm", UserPromptBehaviour.Always);
     this.hooks  = new Pipelines();
     BasicAuthentication.Enable(this.hooks, this.config);
 }
 private bool IsDisabled(BasicAuthenticationConfiguration config)
 => config == null || !config.IsEnabled;
Exemple #18
0
        public void ConfigureServices(IServiceCollection services)
        {
            var folder = Configuration["staticFolder"];

            if (!string.IsNullOrEmpty(folder))
            {
                services.AddSpaStaticFiles((spa) =>
                {
                    spa.RootPath = folder;
                });

                // No need to define anything else as this can only be used as a SPA server
                return;
            }

            var jsonFilePath = Path.Combine(Configuration["currentPath"], Configuration["file"]);

            services.AddSingleton <IDataStore>(new DataStore(jsonFilePath, reloadBeforeGetCollection: Configuration.GetValue <bool>("Common:EagerDataReload")));
            services.AddSingleton <IMessageBus, MessageBus>();
            services.AddSingleton <JobsService>();

            services.Configure <AuthenticationSettings>(Configuration.GetSection("Authentication"));
            services.Configure <ApiSettings>(Configuration.GetSection("Api"));
            services.Configure <JobsSettings>(Configuration.GetSection("Jobs"));
            services.Configure <SimulateSettings>(Configuration.GetSection("Simulate"));

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAnyPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            var useAuthentication = Configuration.GetValue <bool>("Authentication:Enabled");

            if (useAuthentication)
            {
                if (Configuration["Authentication:AuthenticationType"] == "token")
                {
                    var blacklistService = new TokenBlacklistService();
                    services.AddSingleton(blacklistService);

                    TokenConfiguration.Configure(services);
                }
                else
                {
                    BasicAuthenticationConfiguration.Configure(services);
                }
            }
            else
            {
                AllowAllAuthenticationConfiguration.Configure(services);
            }

            services.AddMvc();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Fake JSON API", Version = "v1"
                });

                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "FakeServer.xml");
                c.IncludeXmlComments(xmlPath);

                if (useAuthentication)
                {
                    c.OperationFilter <AddAuthorizationHeaderParameterOperationFilter>();

                    if (Configuration["Authentication:AuthenticationType"] == "token")
                    {
                        c.DocumentFilter <AuthTokenOperation>();
                    }
                }
            });
        }
        public void Should_set_username_in_context_with_valid_username_in_auth_header()
        {
            // Given
            var fakePipelines = new FakeApplicationPipelines();

            var validator = A.Fake<IUserValidator>();
            A.CallTo(() => validator.Validate("foo", "bar")).Returns(true);

            var cfg = new BasicAuthenticationConfiguration(validator, "realm");

            var context = CreateContextWithHeader(
               "Authorization", new [] { "Basic" + " " + EncodeCredentials("foo", "bar") });

            BasicAuthentication.Enable(fakePipelines, cfg);

            // When
            fakePipelines.BeforeRequest.Invoke(context);

            // Then
            context.Items[SecurityConventions.AuthenticatedUsernameKey].ShouldEqual("foo");
        }
        public void Should_set_user_in_context_with_valid_username_in_auth_header()
        {
            // Given
            var fakePipelines = new Pipelines();

            var validator = A.Fake<IUserValidator>();
            var fakeUser = A.Fake<IUserIdentity>();
            A.CallTo(() => validator.Validate("foo", "bar")).Returns(fakeUser);

            var cfg = new BasicAuthenticationConfiguration(validator, "realm");

            var context = CreateContextWithHeader(
               "Authorization", new [] { "Basic" + " " + EncodeCredentials("foo", "bar") });

            BasicAuthentication.Enable(fakePipelines, cfg);

            // When
            fakePipelines.BeforeRequest.Invoke(context, new CancellationToken());

            // Then
            context.CurrentUser.ShouldBeSameAs(fakeUser);
        }
 public BasicAuthenticationFixture()
 {
     this.config = new BasicAuthenticationConfiguration(A.Fake<IUserValidator>(), "realm", UserPromptBehaviour.Always);
     this.hooks = new Pipelines();
     BasicAuthentication.Enable(this.hooks, this.config);
 }
 public BasicAuthenticationFixture()
 {
     this.config = new BasicAuthenticationConfiguration(A.Fake <IUserValidator>(), "realm");
     this.hooks  = new FakeApplicationPipelines();
     BasicAuthentication.Enable(this.hooks, this.config);
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var jsonFilePath = Path.Combine(Configuration.GetValue <string>("currentPath"), Configuration.GetValue <string>("file"));

            services.AddSingleton <IDataStore>(new DataStore(jsonFilePath, reloadBeforeGetCollection: Configuration.GetValue <bool>("Common:EagerDataReload")));
            services.AddSingleton <IMessageBus, MessageBus>();
            services.AddSingleton(typeof(JobsService));

            services.Configure <AuthenticationSettings>(Configuration.GetSection("Authentication"));
            services.Configure <ApiSettings>(Configuration.GetSection("Api"));
            services.Configure <JobsSettings>(Configuration.GetSection("Jobs"));
            services.Configure <SimulateSettings>(Configuration.GetSection("Simulate"));

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAnyPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            var useAuthentication = Configuration.GetValue <bool>("Authentication:Enabled");

            if (useAuthentication)
            {
                if (Configuration.GetValue <string>("Authentication:AuthenticationType") == "token")
                {
                    var blacklistService = new TokenBlacklistService();
                    services.AddSingleton(blacklistService);

                    TokenConfiguration.Configure(services, blacklistService);
                }
                else
                {
                    BasicAuthenticationConfiguration.Configure(services);
                }
            }
            else
            {
                AllowAllAuthenticationConfiguration.Configure(services);
            }

            services.AddMvc();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Generic JSON SQL Api", Version = "v1"
                });

                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "FakeServer.xml");
                c.IncludeXmlComments(xmlPath);

                if (useAuthentication)
                {
                    c.OperationFilter <AddAuthorizationHeaderParameterOperationFilter>();

                    if (Configuration.GetValue <string>("Authentication:AuthenticationType") == "token")
                    {
                        c.DocumentFilter <AuthTokenOperation>();
                    }
                }
            });
        }