public static IVaultService AuthenticateUsingToken(this DefaultVaultService vaultService, string token)
        {
            var auth = new TokenAuthentication(vaultService, token);

            vaultService.AuthenticateAsync(auth).ConfigureAwait(false).GetAwaiter().GetResult();
            return(vaultService);
        }
Beispiel #2
0
        protected override void RequestStartup(ILifetimeScope container, IPipelines pipelines, NancyContext context)
        {
            var tokenizer          = container.Resolve <ITokenizer>();
            var tokenConfiguration = new TokenAuthenticationConfiguration(tokenizer);

            TokenAuthentication.Enable(pipelines, tokenConfiguration);
        }
Beispiel #3
0
        public TokenMgmtModule()
        {
            this.RequiresAuthentication();

            Get["/tkn"] = x => {
                dynamic vmod = new ExpandoObject();
                vmod.Tokens = TokenAuthentication.Show();
                return(View["page-tknmgmt", vmod]);
            };

            Post["/tkn"] = x => {
                string u = Request.Form.Username;
                string t = Request.Form.Token;
                TokenAuthentication.AssignOtpToken(u, t);
                return(Response.AsJson(true));
            };

            Post["/tkn/remove"] = x => {
                string u = Request.Form.Username;
                TokenAuthentication.DeleteRelation(u);
                return(Response.AsJson(true));
            };

            Post["/tkn/u2f"] = x => {
                string u = Request.Form.Username;
                string p = Request.Form.Password;
                string t = Request.Form.Token;
                var    v = TokenAuthentication.Validate(u, p, t);
                return(v ? HttpStatusCode.OK : HttpStatusCode.Forbidden);
            };
        }
        public void Should_throw_with_null_config_passed_to_enable_with_application()
        {
            // Given, When
            var result = Record.Exception(() => TokenAuthentication.Enable(A.Fake <IPipelines>(), null));

            // Then
            result.ShouldBeOfType(typeof(ArgumentNullException));
        }
        public void Should_throw_with_null_module_passed_to_enable_with_config()
        {
            // Given, When
            var result = Record.Exception(() => TokenAuthentication.Enable((INancyModule)null, null));

            // Then
            result.ShouldBeOfType(typeof(ArgumentNullException));
        }
Beispiel #6
0
        void tokenAuthSignIn_Click(object sender, EventArgs e)
        {
            var baseUri = new Uri(baseUriTextBox.Text);
            var token   = tokenAuthToken.Text;
            var auth    = new TokenAuthentication(token);
            var form    = new ExplorerForm(baseUri, auth);

            form.Show();
        }
 public ContentServiceOld(
     ApiEndPoints apiEndPoints,
     TokenAuthentication tokenAuthentication,
     ILogger <ContentServiceOld> logger,
     IHttpClientFactory httpClientFactory)
 {
     _httpClientFactory       = httpClientFactory;
     this._apiEndPoints       = apiEndPoints ?? throw new ArgumentNullException(nameof(apiEndPoints));
     this.tokenAuthentication = tokenAuthentication ?? throw new ArgumentNullException(nameof(tokenAuthentication));
     this._logger             = logger ?? throw new ArgumentNullException(nameof(logger));
 }
        public void Should_add_both_token_and_requires_auth_pre_hook_in_module_when_enabled()
        {
            // Given
            var module = new FakeModule();

            // When
            TokenAuthentication.Enable(module, this.config);

            // Then
            module.Before.PipelineDelegates.ShouldHaveCount(2);
        }
Beispiel #9
0
        protected override void RequestStartup(Autofac.ILifetimeScope container, Nancy.Bootstrapper.IPipelines pipelines, NancyContext context)
        {
            TokenAuthentication.Enable(pipelines, new TokenAuthenticationConfiguration(container.Resolve<ITokenizer>()));
            pipelines.AfterRequest.AddItemToEndOfPipeline(AddCorsHeaders());

            pipelines.OnError.AddItemToEndOfPipeline((ctx, err) =>
                HandleExceptions(err, ctx)
                );

        
            base.RequestStartup(container, pipelines, context);
        }
Beispiel #10
0
        protected override void RequestStartup(IContainer requestContainer, IPipelines pipelines, NancyContext context)
        {
            // Enable token authentication
            TokenAuthentication.Enable(pipelines, new TokenAuthenticationConfiguration(requestContainer.GetInstance <ITokenizer>()));

            // Set up unit of work
            pipelines.BeforeRequest += UnitOfWorkPipeline.BeforeRequest(requestContainer);
            pipelines.AfterRequest  += UnitOfWorkPipeline.AfterRequest();

            // Set up validation exception handling
            pipelines.OnError += HttpBadRequestPipeline.OnHttpBadRequest;
        }
        public void Should_add_a_pre_hook_in_application_when_enabled()
        {
            // Given
            var pipelines = A.Fake <IPipelines>();

            // When
            TokenAuthentication.Enable(pipelines, this.config);

            // Then
            A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A <Func <NancyContext, Response> > .Ignored))
            .MustHaveHappened(Repeated.Exactly.Once);
        }
        protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            var tokenizer = container.Resolve <ITokenizer>();
            var cfg       = new TokenAuthenticationConfiguration(tokenizer);

            TokenAuthentication.Enable(pipelines, cfg);

            pipelines.OnError.AddItemToStartOfPipeline((context, exception) =>
            {
                _logger.Error(exception, "Error in HTTP pipeline.");
                return(null);
            });
        }
Beispiel #13
0
        protected override void RequestStartup(ILifetimeScope container, IPipelines pipelines, NancyContext context)
        {
            var tokenConfig = new TokenAuthenticationConfiguration(container.Resolve <ITokenizer>());

            TokenAuthentication.Enable(pipelines, tokenConfig);

            pipelines.BeforeRequest.AddItemToEndOfPipeline(nancyContext =>
            {
                _log.TraceFormat("{0} {1}", nancyContext.Request.Method.PadRight(5, ' '), nancyContext.Request.Url);
                return((Response)null);
            });

            base.RequestStartup(container, pipelines, context);
        }
Beispiel #14
0
 public PriceCalculationService(
     ApiEndPoints apiEndPoints,
     TokenAuthentication tokenAuthentication,
     IConfigurationService configurationService,
     IHttpClientFactory httpClientFactory,
     IHttpContextAccessor httpContextAccessor,
     IServiceProvider serviceProvider,
     ILogger <PriceCalculationService> logger)
 {
     _httpClientFactory        = httpClientFactory;
     _apiEndPoints             = apiEndPoints ?? throw new ArgumentNullException(nameof(apiEndPoints));
     this.tokenAuthentication  = tokenAuthentication ?? throw new ArgumentNullException(nameof(tokenAuthentication));
     this.configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));
     this._httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
     _serviceProvider          = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Beispiel #15
0
 public ApplicationManager(ILogger <ApplicationManager> logger, IMiddlewareActionHandler actionHandler, IEnumerable <IManagerCommand> commands,
                           ITranslationLookup translationLookup, IConfigurationHandler <CommandConfiguration> commandConfiguration,
                           IConfigurationHandler <ApplicationConfiguration> appConfigHandler, IGameServerInstanceFactory serverInstanceFactory,
                           IEnumerable <IPlugin> plugins, IParserRegexFactory parserRegexFactory, IEnumerable <IRegisterEvent> customParserEvents,
                           IEventHandler eventHandler, IScriptCommandFactory scriptCommandFactory, IDatabaseContextFactory contextFactory, IMetaService metaService,
                           IMetaRegistration metaRegistration, IScriptPluginServiceResolver scriptPluginServiceResolver, ClientService clientService, IServiceProvider serviceProvider,
                           ChangeHistoryService changeHistoryService, ApplicationConfiguration appConfig, PenaltyService penaltyService)
 {
     MiddlewareActionHandler = actionHandler;
     _servers               = new ConcurrentBag <Server>();
     MessageTokens          = new List <MessageToken>();
     ClientSvc              = clientService;
     PenaltySvc             = penaltyService;
     ConfigHandler          = appConfigHandler;
     StartTime              = DateTime.UtcNow;
     PageList               = new PageList();
     AdditionalEventParsers = new List <IEventParser>()
     {
         new BaseEventParser(parserRegexFactory, logger, _appConfig)
     };
     AdditionalRConParsers = new List <IRConParser>()
     {
         new BaseRConParser(serviceProvider.GetRequiredService <ILogger <BaseRConParser> >(), parserRegexFactory)
     };
     TokenAuthenticator           = new TokenAuthentication();
     _logger                      = logger;
     _metaService                 = metaService;
     _tokenSource                 = new CancellationTokenSource();
     _commands                    = commands.ToList();
     _translationLookup           = translationLookup;
     _commandConfiguration        = commandConfiguration;
     _serverInstanceFactory       = serverInstanceFactory;
     _parserRegexFactory          = parserRegexFactory;
     _customParserEvents          = customParserEvents;
     _eventHandler                = eventHandler;
     _scriptCommandFactory        = scriptCommandFactory;
     _metaRegistration            = metaRegistration;
     _scriptPluginServiceResolver = scriptPluginServiceResolver;
     _serviceProvider             = serviceProvider;
     _changeHistoryService        = changeHistoryService;
     _appConfig                   = appConfig;
     Plugins                      = plugins;
 }
Beispiel #16
0
        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            TokenAuthentication.Enable(pipelines, new TokenAuthenticationConfiguration(container.Resolve <ITokenizer>()));

            pipelines.BeforeRequest.AddItemToStartOfPipeline(c => {
                if (c.Request.Method != "OPTIONS")
                {
                    return(null);
                }

                return(new Response {
                    StatusCode = HttpStatusCode.NoContent
                }
                       .WithHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE")
                       .WithHeader("Access-Control-Allow-Headers", "Content-Type"));
            });

            pipelines.AfterRequest.AddItemToEndOfPipeline(c =>
                                                          c.Response.WithHeader("Access-Control-Allow-Origin", "*")
                                                          );
        }
        public void Should_set_user_in_context_with_valid_username_in_auth_header()
        {
            // Given
            var fakePipelines = new Pipelines();

            var context = CreateContextWithHeader(
                "Authorization", new[] { "Token" + " " + "mytoken" });

            var tokenizer = A.Fake <ITokenizer>();
            var fakeUser  = A.Fake <IUserIdentity>();

            A.CallTo(() => tokenizer.Detokenize("mytoken", context, A <IUserIdentityResolver> .Ignored)).Returns(fakeUser);

            var cfg = new TokenAuthenticationConfiguration(tokenizer);

            TokenAuthentication.Enable(fakePipelines, cfg);

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

            // Then
            context.CurrentUser.ShouldBeSameAs(fakeUser);
        }
 public VaultClientFacts()
 {
     _token = new TokenAuthentication(Configuration.Token);
     _appId = new AppIdAuthentication(Configuration.AppId, Configuration.UserId);
     _uri   = Configuration.VaultUri;
 }
 public VaultClientFacts()
 {
     _token = new TokenAuthentication(Configuration.Token);
     _appId = new AppIdAuthentication(Configuration.AppId, Configuration.UserId);
     _uri = Configuration.VaultUri;
 }
 protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
 {
     TokenAuthentication.Enable(pipelines, new TokenAuthenticationConfiguration(container.Resolve <ITokenizer>()));
 }
 public async Task WritingSecretsThrowsAVaultExceptionWhenNotAuthorized()
 {
     var badToken = new TokenAuthentication(Guid.NewGuid().ToString());
     var vault = new VaultClient(_uri, badToken);
     await Assert.ThrowsAsync<VaultException>(() => vault.WriteSecretAsync("foo", EMPTY_SECRET));
 }
 public Test_TokenAuthentication()
 {
     tokenAuth = new TokenAuthentication();
     authVar   = TMConsts.AUTH_TOKEN_REQUEST_VAR_NAME;
 }
Beispiel #23
0
 protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
 {
     CustomErrorHandler.Enable(pipelines, container.Resolve <IResponseNegotiator>());
     TokenAuthentication.Enable(pipelines, new TokenAuthenticationConfiguration(container.Resolve <ITokenizer>()));
 }
 public async Task WritingSecretsThrowsAVaultExceptionWhenNotAuthorized()
 {
     var badToken = new TokenAuthentication(Guid.NewGuid().ToString());
     var vault    = new VaultClient(_uri, badToken);
     await Assert.ThrowsAsync <VaultException>(() => vault.WriteSecretAsync("foo", EMPTY_SECRET));
 }
 public TokenAuthenticationFixture()
 {
     this.config = new TokenAuthenticationConfiguration(A.Fake <ITokenizer>());
     this.hooks  = new Pipelines();
     TokenAuthentication.Enable(this.hooks, this.config);
 }