コード例 #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            securityKey  = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
            tokenOptions = new TokenProviderOptions
            {
                Audience           = "ExampleAudience",
                Issuer             = "ExampleIssuer",
                SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256),
            };

            services.AddSingleton <TokenProviderOptions>(tokenOptions);
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser().Build());
            });
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });
            // Add framework services.
            services.AddMvc();
        }
コード例 #2
0
ファイル: Startup.cs プロジェクト: xareas/scaffolder
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="loggerFactory"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //add NLog to ASP.NET Core
            loggerFactory.AddNLog();

            //needed for non-NETSTANDARD platforms: configure nlog.config in your project root
            //env.ConfigureNLog("nlog.config");

            app.UseDefaultFiles();
            app.UseStaticFiles();

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            //Add CORS middleware before MVC
            app.UseCors("CorsPolicy");

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

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = AppSettings.Issuer,

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience    = AppSettings.Audience,

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = tokenValidationParameters,
                SaveToken = true
            });

            var options = new TokenProviderOptions
            {
                Issuer             = AppSettings.Issuer,
                Audience           = AppSettings.Audience,
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
                WorkingDirectory   = _workingDirectory
            };

            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(options));

            app.UseMvc();
        }
コード例 #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            // Consumption
            TokenOAuthConsumption(app);

            var secretKey = Configuration["Auth:Secret"];

            // Add JWT generation endpoint:
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
            var options    = new TokenProviderOptions
            {
                Audience           = Configuration["Auth:Audience"],
                Issuer             = Configuration["Auth:Issuer"],
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
            };

            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(options));

            app.UseMvc();

            app.UseDeveloperExceptionPage();
        }
コード例 #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

            // Add JWT generation endpoint:
            var jwtOptions = new TokenProviderOptions
            {
                Audience           = audience,
                Issuer             = issuer,
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
            };

            app.UseJWTTokenProviderMiddleware(Options.Create(jwtOptions));

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });
        }
コード例 #5
0
        public Exception GetExceptionWhenInvalid(TokenProviderOptions options)
        {
            if (string.IsNullOrEmpty(options.Path))
            {
                return(new ArgumentNullException(nameof(TokenProviderOptions.Path)));
            }

            if (string.IsNullOrEmpty(options.Issuer))
            {
                return(new ArgumentNullException(nameof(TokenProviderOptions.Issuer)));
            }

            if (string.IsNullOrEmpty(options.Audience))
            {
                return(new ArgumentNullException(nameof(TokenProviderOptions.Audience)));
            }

            if (options.Expiration == TimeSpan.Zero)
            {
                return(new ArgumentException("Must be a non-zero TimeSpan.", nameof(TokenProviderOptions.Expiration)));
            }

            if (options.SigningCredentials == null)
            {
                return(new ArgumentNullException(nameof(TokenProviderOptions.SigningCredentials)));
            }

            if (options.NonceGenerator == null)
            {
                return(new ArgumentNullException(nameof(TokenProviderOptions.NonceGenerator)));
            }

            return(null);
        }
コード例 #6
0
        public async Task <IActionResult> Login([FromForm] ApiLoginModel model)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Name, model.Pwd, true, false);

            if (result.Succeeded)
            {
                var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Value.SecretKey));
                var options    = new TokenProviderOptions()
                {
                    Issuer             = "EntityAbstract",
                    Audience           = "EntityAbstractAudience",
                    SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
                };
                var tpm   = new TokenProvider(options);
                var token = await tpm.GenerateToken(model.Name, model.Pwd);

                var user = await _userManager.FindByNameAsync(model.Name);

                return(token != null ? (IActionResult)Json(token) : BadRequest());
            }

            if (result.IsLockedOut)
            {
                return(BadRequest("Lockout"));
            }
            return(BadRequest("Invalid login attempt"));
        }
コード例 #7
0
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            _signingKey =
                new SymmetricSecurityKey(
                    Encoding.ASCII.GetBytes(Configuration.GetSection("TokenAuthentication:SecretKey").Value));

            _tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = _signingKey,
                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = Configuration.GetSection("TokenAuthentication:Issuer").Value,
                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience    = Configuration.GetSection("TokenAuthentication:Audience").Value,
                // Validate the token expiry
                ValidateLifetime = true,
                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            _tokenProviderOptions = new TokenProviderOptions
            {
                Path               = Configuration.GetSection("TokenAuthentication:TokenPath").Value,
                Audience           = Configuration.GetSection("TokenAuthentication:Audience").Value,
                Issuer             = Configuration.GetSection("TokenAuthentication:Issuer").Value,
                SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256)
            };
        }
コード例 #8
0
        private void ConfigureAuth(IApplicationBuilder app)
        {
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("TokenAuthentication:SecretKey").Value));

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,
                ValidIssuer      = Configuration.GetSection("TokenAuthentication:Issuer").Value,
                ValidateAudience = true,
                ValidAudience    = Configuration.GetSection("TokenAuthentication:Audience").Value,
                ValidateLifetime = true,
                ClockSkew        = TimeSpan.Zero
            };

            var tokenProviderOptions = new TokenProviderOptions
            {
                Path               = Configuration.GetSection("TokenAuthentication:TokenPath").Value,
                Audience           = Configuration.GetSection("TokenAuthentication:Audience").Value,
                Issuer             = Configuration.GetSection("TokenAuthentication:Issuer").Value,
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
            };

            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(tokenProviderOptions));
            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = tokenValidationParameters
            });
        }
コード例 #9
0
        private IReadOnlyKernel RegisterApplicationComponents(IApplicationBuilder app, ILoggerFactory loggerFactory, TokenValidationParameters tokenParams)
        {
            IKernelConfiguration config = new KernelConfiguration();
            // Add JWT generation endpoint:
            var secretKey = Configuration["secret"];

            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
            var options    = new TokenProviderOptions
            {
                Audience           = tokenParams.ValidAudience,
                Issuer             = tokenParams.ValidIssuer,
                SigningCredentials = new SigningCredentials(tokenParams.IssuerSigningKey, SecurityAlgorithms.HmacSha256)
            };

            config.Bind <TokenProviderOptions>().ToConstant(options).InSingletonScope();
            // Register application services
            //config.Bind(app.GetControllerTypes()).ToSelf().InScope(RequestScope);//todo fix
            config.Bind <HomeController>().ToSelf().InScope(RequestScope);
            config.Bind <BooksController>().ToSelf().InScope(RequestScope);
            var dataContext = new DataContext(Configuration.GetConnectionString("DefaultConnection"));

            //config.Bind<IUserService>().To<AspNetUserService>().InScope(RequestScope);
            config.Bind <IDataContext>().ToConstant(dataContext).InSingletonScope();
            config.Bind <IUserRepository>().ToConstant(dataContext.Users).InSingletonScope();
            config.Bind <IBookRepository>().ToConstant(dataContext.Books).InSingletonScope();
            //config.Bind<CustomMiddleware>().ToSelf();

            // Cross-wire required framework services
            config.BindToMethod(app.GetRequestService <IViewBufferScope>);
            config.Bind <ILoggerFactory>().ToConstant(loggerFactory);

            return(config.BuildReadonlyKernel());
        }
コード例 #10
0
ファイル: TokenProvider.cs プロジェクト: igmer/plantilla
 public TokenProvider(ApplicationDbContext dbcontext, SigningConfigurations signingConfigurations, IPasswordHasher passwordHaser, IOptions <TokenProviderOptions> tokenOptionsSnapshot)
 {
     _tokenOptions          = tokenOptionsSnapshot.Value;
     _passwordHaser         = passwordHaser;
     _signingConfigurations = signingConfigurations;
     _dbContext             = dbcontext;
 }
コード例 #11
0
        private void ConfigureAuth(IApplicationBuilder app)
        {
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("TokenAuthentication:SecretKey").Value));

            var tokenProviderOptions = new TokenProviderOptions
            {
                Path               = Configuration.GetSection("TokenAuthentication:TokenPath").Value,
                Audience           = Configuration.GetSection("TokenAuthentication:Audience").Value,
                Issuer             = Configuration.GetSection("TokenAuthentication:Issuer").Value,
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
                IdentityResolver   = GetIdentity
            };

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = Configuration.GetSection("TokenAuthentication:Issuer").Value,

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience    = Configuration.GetSection("TokenAuthentication:Audience").Value,

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            var jwtBearerOptions = new JwtBearerOptions
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                AuthenticationScheme      = JwtBearerDefaults.AuthenticationScheme,
                TokenValidationParameters = tokenValidationParameters
            };

            ////jwtBearerOptions.SecurityTokenValidators.Clear();
            ////jwtBearerOptions.SecurityTokenValidators.Add(new TicketDataFormatTokenValidator());

            app.UseJwtBearerAuthentication(jwtBearerOptions);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                AuthenticationScheme  = "Cookie",
                CookieName            = Configuration.GetSection("TokenAuthentication:CookieName").Value,
                TicketDataFormat      = new CustomJwtDataFormat(
                    SecurityAlgorithms.HmacSha256,
                    tokenValidationParameters)
            });

            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(tokenProviderOptions));
        }
コード例 #12
0
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            IConfigurationSection auth = this.Configuration.GetSection("Authentication");

            TokenProviderOptions jwtOptions = new TokenProviderOptions
            {
                Audience           = auth["Audience"],
                Issuer             = auth["Issuer"],
                SigningCredentials = new SigningCredentials(this.SigningKey, SecurityAlgorithms.HmacSha256)
            };

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStatusCodePagesWithReExecute("/");
            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseAuthentication();
            app.UseCors("DefaultPolicy");
            app.UseMvc();
            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(jwtOptions));

            Console.WriteLine("Set up all app features");
        }
コード例 #13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            ////ILogger - log to local file
            //loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            //loggerFactory.AddDebug();
            //loggerFactory.AddFile("C:/Logs/NTS-{Date}.txt");

            // Add JWT generation endpoint:
            var signingKey = new SymmetricSecurityKey(secretKey);
            var options    = new TokenProviderOptions
            {
                Audience           = "ExampleAudience",
                Issuer             = "ExampleIssuer",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
            };

            app.UseMiddleware <ApplicationServices.ExceptionHandler.ExceptionMiddleware>();

            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(options));

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
コード例 #14
0
 public TokenProviderMiddleware(
     RequestDelegate next,
     IOptions <TokenProviderOptions> options)
 {
     _next    = next;
     _options = options.Value;
 }
コード例 #15
0
        private static void ThrowIfInvalidOptions(TokenProviderOptions options)
        {
            if (string.IsNullOrEmpty(options.Path))
            {
                throw new ArgumentNullException(nameof(TokenProviderOptions.Path));
            }

            if (string.IsNullOrEmpty(options.Issuer))
            {
                throw new ArgumentNullException(nameof(TokenProviderOptions.Issuer));
            }

            if (string.IsNullOrEmpty(options.Audience))
            {
                throw new ArgumentNullException(nameof(TokenProviderOptions.Audience));
            }

            if (options.Expiration == TimeSpan.Zero)
            {
                throw new ArgumentException("Must be a non-zero TimeSpan.", nameof(TokenProviderOptions.Expiration));
            }

            if (options.SigningCredentials == null)
            {
                throw new ArgumentNullException(nameof(TokenProviderOptions.SigningCredentials));
            }

            if (options.NonceGenerator == null)
            {
                throw new ArgumentNullException(nameof(TokenProviderOptions.NonceGenerator));
            }
        }
コード例 #16
0
        public TokenProviderMiddleware(
            RequestDelegate next,
            IOptions <TokenProviderOptions> options,
            ILogger <TokenProviderMiddleware> log,
            JwtTokenGenerator tokenGenerator,
            TokenProviderOptionsValidator validator)
        {
            this.next           = next;
            this.log            = log;
            this.tokenGenerator = tokenGenerator;

            this.options = options.Value;

            var exception = validator.GetExceptionWhenInvalid(this.options);

            if (exception != null)
            {
                throw exception;
            }

            serializerSettings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented
            };
        }
コード例 #17
0
 public TokenProvider(ITokenInfoStorage tokenInfoStorage, IDataProtectionFactory dataProtectionFactory,
                      IOptions <TokenProviderOptions> tokenProviderOptions)
 {
     _tokenInfoStorage      = tokenInfoStorage ?? throw new ArgumentNullException(nameof(tokenInfoStorage));
     _dataProtectionFactory = dataProtectionFactory ?? throw new ArgumentNullException(nameof(dataProtectionFactory));
     _tokenProviderOptions  = tokenProviderOptions.Value ?? throw new ArgumentNullException(nameof(tokenProviderOptions));
 }
コード例 #18
0
ファイル: Startup.cs プロジェクト: eswang37/webapi
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            connString       = Configuration.GetConnectionString("SQLSERVERDB");
            signingKey       = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Keys:UserAuthSecretKey"]));
            apiURL           = Configuration["Keys:APIURL"];
            emailUserName    = Configuration["EmailSettings:UserName"];
            emailPassword    = Configuration["EmailSettings:Passwrod"];
            userTokenOptions = new TokenProviderOptions
            {
                Audience           = "ConsumerUser",
                Issuer             = "Backend",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
            };

            services.AddDbContext <ContactContext>(options =>
                                                   options.UseSqlServer(connString));
            services.AddDbContext <PostContext>(options =>
                                                options.UseSqlServer(connString));

            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddMvc();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Andmap WebAPI", Version = "v1"
                });
            });
            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
        }
コード例 #19
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseCors("CorsPolicy");

            // Add JWT generation endpoint:
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("SecretKey").Value));
            var options    = new TokenProviderOptions
            {
                Audience           = "ShoppingApiAudience",
                Issuer             = "ShoppingApiIssuer",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
            };

            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(options));

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = "ShoppingApiIssuer",

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience    = "ShoppingApiAudience",

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = tokenValidationParameters
            });

            app.UseSwagger().UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My ShoppingCartApi V1");
            });

            var context = (ShoppingCartContext)app
                          .ApplicationServices.GetService(typeof(ShoppingCartContext));

            WaitForSqlAvailabilityAsync(context, loggerFactory, app, env).Wait();

            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
コード例 #20
0
        public TokenProviderMiddleware(IAuth oo,
                                       RequestDelegate next, IOptions <TokenProviderOptions> options)
        {
            _next    = next;
            _options = options.Value;

            db = oo;// options.Value.Auth;
        }
コード例 #21
0
ファイル: Startup.Auth.cs プロジェクト: war-man/master-api
        private void ConfigAuth(IServiceCollection services)
        {
            // *** CHANGE THIS FOR PRODUCTION USE ***
            // Here, we're generating a random key to sign tokens - obviously this means
            // that each time the app is started the key will change, and multiple servers
            // all have different keys. This should be changed to load a key from a file
            // securely delivered to your application, controlled by configuration.
            //
            // See the RSAKeyUtils.GetKeyParameters method for an examle of loading from
            // a JSON file.
            var keyParams = RSAKeyUtils.GetKeyParameters(".config/rsaparams.json");

            // Create the key, and a set of token options to record signing credentials
            // using that key, along with the other parameters we will need in the
            // token controlller.
            _signingKey = new RsaSecurityKey(keyParams);

            _tokenOptions = new TokenProviderOptions
            {
                Audience           = AppSettings.Auth.TokenAudience,
                Issuer             = AppSettings.Auth.TokenIssuer,
                SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha256Signature),
                IdentityResolver   = GetIdentity
            };

            // Save the token options into an instance so they're accessible to the
            services.AddSingleton(typeof(TokenProviderOptions), _tokenOptions);

            // Enable Dual Authentication
            services.AddAuthentication()
            .AddCookie(cfg => cfg.SlidingExpiration = true)
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer      = AppSettings.Auth.TokenIssuer,
                    ValidAudience    = AppSettings.Auth.TokenAudience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                };
            });

            //services.AddAuthentication(options =>
            //{
            //    options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
            //});

            // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect.
            services.AddAuthorization(options =>
            {
                options.AddPolicy(AuthSchema, policy =>
                {
                    policy.AuthenticationSchemes.Add(AuthSchema);
                    policy.RequireAuthenticatedUser().Build();
                });
            });
        }
コード例 #22
0
ファイル: Startup.Auth.cs プロジェクト: Koelion/XOXO
        private void RegisterToken(IServiceCollection services)
        {
            string secretKey  = Configuration["Tokens:Key"];
            var    signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
            var    options    = new TokenProviderOptions
            {
                Audience           = Configuration["Tokens:Issuer"],
                Issuer             = Configuration["Tokens:Issuer"],
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
                Expiration         = TimeSpan.FromDays(1),
                CookieName         = Configuration["Tokens:CookieName"]
            };

            services.AddSingleton <IOptions <TokenProviderOptions> >(Options.Create(options));
            services.AddTransient <ITokenProvider, TokenProvider>();

            var tokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer           = true,
                ValidIssuer              = Configuration["Tokens:Issuer"],
                ValidateAudience         = true,
                ValidAudience            = Configuration["Tokens:Issuer"],
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])),
                ValidateLifetime         = true,
                ClockSkew = TimeSpan.Zero,
            };

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(opt =>
            {
                opt.Events.OnRedirectToLogin = (context) =>
                {
                    context.Response.StatusCode = 401;
                    return(Task.CompletedTask);
                };
            });
            //services.AddAuthentication(cfg =>
            //    {
            //        cfg.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            //        cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            //    })
            //    .AddJwtBearer(cfg =>
            //    {
            //        cfg.RequireHttpsMetadata = false;
            //        cfg.SaveToken = true;
            //        cfg.TokenValidationParameters = tokenValidationParameters;
            //    })
            //    .AddCookie(cfg =>
            //    {
            //        cfg.LoginPath = "/User/SignIn";
            //        cfg.LogoutPath = "/User/SignOut";
            //        cfg.Cookie.Name = CookieAuthenticationDefaults.AuthenticationScheme;
            //        cfg.TicketDataFormat = new CustomJwtDataFormat(
            //            SecurityAlgorithms.HmacSha256,
            //            tokenValidationParameters);
            //    });
        }
コード例 #23
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var secretKey  = "mysupersecret_secretkey!123";
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = "ExampleIssuer",

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience    = "ExampleAudience",

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                AuthenticationScheme  = "Cookie",
                CookieName            = "access_token",
                TicketDataFormat      = new CustomJwtDataFormat(
                    SecurityAlgorithms.HmacSha256,
                    tokenValidationParameters)
            });

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = tokenValidationParameters
            });

            // Add JWT generation endpoint:

            var options = new TokenProviderOptions
            {
                Audience           = "ExampleAudience",
                Issuer             = "ExampleIssuer",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
            };

            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(options));
            app.UseMvc();
        }
コード例 #24
0
 public TokenProviderMiddleware(RequestDelegate next,
                                IOptions <TokenProviderOptions> options,
                                IAccountRepository account, IRoleRepository role)
 {
     _next    = next;
     _options = options.Value;
     _account = account;
     _role    = role;
 }
コード例 #25
0
 public CustomJwtDataFormat(
     string algorithm,
     TokenValidationParameters validationParameters,
     TokenProviderOptions options)
 {
     _algorithm            = algorithm;
     _validationParameters = validationParameters;
     _options = options;
 }
コード例 #26
0
 public TokenProviderMiddleware(
     RequestDelegate next,
     IOptions <TokenProviderOptions> options,
     IIdentityProvider identityProvider)
 {
     _next             = next;
     _options          = options.Value;
     _identityProvider = identityProvider;
 }
コード例 #27
0
 public TokenProviderMiddleware(
     RequestDelegate next,
     IOptions <TokenProviderOptions> options,
     UserManager <AppUser> userManager)
 {
     _next        = next;
     _options     = options.Value;
     _userManager = userManager;
 }
コード例 #28
0
ファイル: Startup.cs プロジェクト: zosimanoz/eapp
        public void Register(IApplicationBuilder app)
        {
            string issuer               = Configuration.GetSection("TokenAuthentication:Issuer").Value;
            string audience             = Configuration.GetSection("TokenAuthentication:Audience").Value;
            var    secret               = Encoding.UTF8.GetBytes(Configuration.GetSection("TokenAuthentication:SecretKey").Value);
            var    tokenProviderOptions = new TokenProviderOptions
            {
                Path               = Configuration.GetSection("TokenAuthentication:IntervieweeTokenPath").Value,
                Audience           = audience,
                Issuer             = issuer,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(secret), SecurityAlgorithms.HmacSha256),
                IdentityResolver   = GetIdentity
            };
            var userTokenProvider = new TokenProviderOptions
            {
                Path               = Configuration.GetSection("TokenAuthentication:UserTokenPath").Value,
                Audience           = audience,
                Issuer             = issuer,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(secret), SecurityAlgorithms.HmacSha256),
                IdentityResolver   = GetUserIdentity
            };

            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                AuthenticationScheme      = "Bearer",
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer              = issuer,
                    ValidAudience            = audience,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(secret),
                    ValidateLifetime         = true
                }
            });
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = false,
                AutomaticChallenge    = false,
                AuthenticationScheme  = "Cookie",
                CookieName            = "access_token",
                TicketDataFormat      = new CustomTokenFormat(
                    SecurityAlgorithms.HmacSha256,
                    new TokenValidationParameters()
                {
                    ValidIssuer              = issuer,
                    ValidAudience            = audience,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(secret),
                    ValidateLifetime         = true
                })
            });

            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(tokenProviderOptions));
            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(userTokenProvider));
        }
コード例 #29
0
 public AuthMiddleware(
     RequestDelegate next,
     IOptions <TokenProviderOptions> options,
     DataContext db)
 {
     _next    = next;
     _options = options.Value;
     _db      = db;
 }
コード例 #30
0
 public TokenCreatorMiddleware(
     IServiceProvider serviceProvider,
     RequestDelegate next,
     IOptions <TokenProviderOptions> options)
 {
     this.serviceProvider = serviceProvider;
     skip = next;
     opts = options.Value;
 }
コード例 #31
0
ファイル: Startup.cs プロジェクト: sergey-smirnov/JwtAuth
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var audienceConfig = Configuration.GetSection("Audience");
            var symmetricKeyAsBase64 = audienceConfig["Secret"];
            var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey = new SymmetricSecurityKey(keyByteArray);

            var options = new TokenProviderOptions
            {
                Audience = "ExampleAudience",
                Issuer = "ExampleIssuer",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
            };

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = options.Issuer,

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience = options.Audience,

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = tokenValidationParameters,

            });

            app.UseMiddleware<CustomTokenProviderMiddleware>(Options.Create(options));

            app.UseMvc();
        }
コード例 #32
0
 public CustomTokenProviderMiddleware(RequestDelegate next, IOptions<TokenProviderOptions> options)
 {
     _next = next;
     _options = options.Value;
 }