public static void AddAppWebSecurity(this IServiceCollection services, IHostingEnvironment env)
        {
            //RSAKeyUtils.GenerateKeyAndSave(env.ContentRootPath + "\\App_Data\\RSAkey.txt");
            RSAParameters keyParams = RSAKeyUtils.GetKeyParameters(env.ContentRootPath + "\\App_Data\\RSAkey.txt");
            var           key       = new RsaSecurityKey(keyParams);

            services.Configure <TokenAuthOptions>(tokenAuthOptions =>
            {
                tokenAuthOptions.Audience           = GetAudience();
                tokenAuthOptions.Issuer             = GetIssuer();
                tokenAuthOptions.SigningCredentials =
                    new SigningCredentials(key,
                                           SecurityAlgorithms.RsaSha256Signature);
                tokenAuthOptions.IssuerSigningKey = key;
            });


            services.AddAuthorization(auth =>
            {
                auth.AddPolicy(ApiConstants.ApiPolicy, new AuthorizationPolicyBuilder()
                               //.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​, CookieAuthenticationDefaults.AuthenticationScheme)
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                               .RequireAuthenticatedUser()
                               .Build());
            })
            .AddAuthentication(o =>
            {
                o.DefaultChallengeScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.Cookie.Name      = ".BaseApp.Web-Core-AUTH";
                options.LoginPath        = new PathString("/Account/LogOn/");
                options.LogoutPath       = new PathString("/Account/LogOff/");
                options.AccessDeniedPath = new PathString("/Account/Forbidden/");
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = key,
                    ValidateIssuer           = true,
                    ValidIssuer      = GetIssuer(),
                    ValidateAudience = true,
                    ValidAudience    = GetAudience(),
                    ValidateLifetime = true,
                    // This defines the maximum allowable clock skew - i.e. provides a tolerance on the token expiry time
                    // when validating the lifetime. As we're creating the tokens locally and validating them on the same
                    // machines which should have synchronised time, this can be set to zero. Where external tokens are
                    // used, some leeway here could be useful.
                    ClockSkew = TimeSpan.FromMinutes(0)
                };

                options.RequireHttpsMetadata = false;
            });
        }
예제 #2
0
        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();
                });
            });
        }