Exemple #1
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);
        }
        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);
            });
        }
Exemple #3
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);
        }
        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 TokenAuthenticationFixture()
 {
     this.config = new TokenAuthenticationConfiguration(A.Fake<ITokenizer>());
     this.hooks = new Pipelines();
     TokenAuthentication.Enable(this.hooks, this.config);
 }
        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)).Returns(fakeUser);

            var cfg = new TokenAuthenticationConfiguration(tokenizer);

            TokenAuthentication.Enable(fakePipelines, cfg);

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

            // Then
            context.CurrentUser.ShouldBeSameAs(fakeUser);
        }
 public TokenAuthenticationFixture()
 {
     this.config = new TokenAuthenticationConfiguration(A.Fake <ITokenizer>());
     this.hooks  = new Pipelines();
     TokenAuthentication.Enable(this.hooks, this.config);
 }
Exemple #8
0
        public static IServiceCollection AddAuth(this IServiceCollection services, TokenAuthenticationConfiguration config, string dbConnectionString, bool isTest = false)
        {
            if (isTest)
            {
                services.AddDbContext <AuthServiceDbContext>(options =>
                                                             options.UseLazyLoadingProxies()
                                                             .EnableSensitiveDataLogging()
                                                             .UseInMemoryDatabase("TestingDB"));
            }
            else
            {
                services.AddDbContext <AuthServiceDbContext>(options =>
                {
                    options.UseLazyLoadingProxies()
                    .UseSqlServer(dbConnectionString);
                });
            }

            services.AddScoped <IUnitOfWork>(provider => new UnitOfWork(provider.GetService <AuthServiceDbContext>()));
            services.AddScoped <IAuthClientRepository>(provider => new AuthClientRepository(provider.GetService <AuthServiceDbContext>()));

            if (config.EnableTokenBlocking)
            {
                services.AddMvcCore(options =>
                {
                    options.Filters.Insert(0, new AuthorizeTokenFilter());
                });
            }

            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config.SecretKey));

            services.AddSingleton(config);

            services.Configure <TokenProviderOptions>(options =>
            {
                options.Path                   = config.Path;
                options.Audience               = config.Audience;
                options.Issuer                 = config.Issuer;
                options.SigningCredentials     = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
                options.Expiration             = new TimeSpan(0, 0, config.Expiration);
                options.RefreshTokenSigningKey = config.SecretKey;
            });
            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = config.Issuer,
                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience    = config.Audience,
                // Validate the token expiry
                ValidateLifetime = true,
                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(o => { o.TokenValidationParameters = tokenValidationParameters; });

            services.AddSingleton <IAuthService, AuthService>();
            services.AddScoped <IAuthClientService, AuthClientService>();
            services.AddSingleton <IAuthenticationValidation, AuthenticationValidation>();

            return(services);
        }