private static void SetUpCookieAuth(IServiceCollection services, IConfiguration configuration)
        {
            //services.Configure<SecurityConfig>(Configuration.GetSection("Security"));
            //services.Configure<JsonWebTokenConfig>(Configuration.GetSection("JsonWebToken"));

            SecurityConfig     security           = new SecurityConfig();
            JsonWebTokenConfig jsonWebTokenConfig = new JsonWebTokenConfig();

            configuration.GetSection("SecurityConfig").Bind(security);
            configuration.GetSection("JsonWebTokenConfig").Bind(jsonWebTokenConfig);

            CookieBuilder cookie = new CookieBuilder();

            cookie.Domain       = security.AppDomain;
            cookie.Name         = security.CookieName;
            cookie.HttpOnly     = true;
            cookie.Path         = "/";
            cookie.SameSite     = SameSiteMode.None;
            cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            cookie.MaxAge       = TimeSpan.FromMinutes(60 * 24 * 90);

            // If you don't want the cookie to be automatically authenticated and assigned to
            // HttpContext.User, remove the CookieAuthenticationDefaults.AuthenticationScheme
            // parameter passed to AddAuthentication.
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.Cookie            = cookie;
                options.SlidingExpiration = true;
                options.TicketDataFormat  = new Sabio.Web.Core.Services.TokenSecureDataFormat(jsonWebTokenConfig);
                options.AccessDeniedPath  = "/unauthorized";
                options.LoginPath         = "/login";
                options.LogoutPath        = "/logout";
                options.Events            = new CookieAuthenticationEvents();
                options.Events.OnRedirectToAccessDenied = RedirectContext;
                options.Events.OnRedirectToLogin        = RedirectContext;
            });

            services.AddAuthorization(authorizeOptions =>
            {
                authorizeOptions.AddPolicy("defaultpolicy", b =>
                {
                    b.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
                    b.RequireAuthenticatedUser();
                });
            });
        }
Пример #2
0
 public TokenSecureDataFormat(JsonWebTokenConfig config)
 {
     _secret         = config.Secret;
     _expirationDays = config.ExpirationDays;
     _config         = config;
 }