Пример #1
0
        public static IServiceCollection AddJwtCookieAuthentication(this IServiceCollection services, Action <JwtCookieOptions> builder)
        {
            var options = new JwtCookieOptions();

            builder?.Invoke(options);
            if (string.IsNullOrWhiteSpace(options.SecurityKey))
            {
                throw new ArgumentNullException(nameof(options.SecurityKey));
            }
            if (options.SecurityKey.Length < 16)
            {
                throw new ArgumentOutOfRangeException(nameof(options.SecurityKey), "SecurityKey length cannot be less than 16.");
            }
            var signingKey           = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(options.SecurityKey));
            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateLifetime         = true,
                ClockSkew = TimeSpan.Zero
            };

            if (!string.IsNullOrWhiteSpace(options.ValidIssuer) || options.ValidIssuers != null && options.ValidIssuers.Any())
            {
                validationParameters.ValidateIssuer = true;
                validationParameters.ValidIssuer    = options.ValidIssuer;
                validationParameters.ValidIssuers   = options.ValidIssuers;
            }

            if (!string.IsNullOrWhiteSpace(options.ValidAudience) || options.ValidAudiences != null && options.ValidAudiences.Any())
            {
                validationParameters.ValidateAudience = true;
                validationParameters.ValidAudience    = options.ValidAudience;
                validationParameters.ValidAudiences   = options.ValidAudiences;
            }

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(option =>
            {
                option.Cookie           = options.Cookie;
                option.LoginPath        = options.LoginPath;
                option.AccessDeniedPath = options.AccessDeniedPath;
                //option.TicketDataFormat = new JwtCookieDataFormat(validationParameters, options);
                option.SlidingExpiration = options.SlidingExpiration;
                option.ExpireTimeSpan    = options.ExpireTimeSpan;
                if (options.Events != null)
                {
                    option.Events = options.Events;
                }
            });

            return(services);
        }
Пример #2
0
 public JwtCookieDataFormat(TokenValidationParameters validationParameters, JwtCookieOptions options)
 {
     ValidationParameters = validationParameters;
     Options = options;
     Handler = new JwtSecurityTokenHandler();
 }