Exemple #1
0
        public static ClaimsPrincipal Principal(bool hasUserKey       = true,
                                                bool hasSecurityStamp = true, bool hasSecurityStampValidated = true,
                                                FakeSystemClock clock = null)
        {
            clock = clock ?? new FakeSystemClock(DateTimeOffset.UtcNow);
            var options = new ClaimOptions();
            var claims  = new List <Claim>();

            if (hasUserKey)
            {
                claims.Add(new Claim(options.ClaimTypes.UserKey, "key"));
            }

            if (hasSecurityStamp)
            {
                claims.Add(new Claim(options.ClaimTypes.SecurityStamp, "stamp"));
            }

            if (hasSecurityStampValidated)
            {
                claims.Add(new Claim(options.ClaimTypes.SecurityStampValidated,
                                     clock.UtcNow.UtcTicks.ToString()));
            }

            return(new ClaimsPrincipal(
                       new ClaimsIdentity(claims, options.AuthenticationScheme)));
        }
Exemple #2
0
 public Claim(ClaimOptions claimType, string description, double amount, DateTime incidentDate, DateTime claimDate, bool validation)
 {
     ClaimType      = claimType;
     Description    = description;
     ClaimAmount    = amount;
     DateOfIncident = incidentDate;
     DateOfClaim    = claimDate;
 }
                public void WhenCalled_SetsValue()
                {
                    var options = new IdentityOptions();
                    var claimOptions = new ClaimOptions();

                    options.Claims = claimOptions;

                    Assert.Equal(claimOptions, options.Claims);
                }
Exemple #4
0
 public FakeClaimsAuthenticationServiceBase(FakeUserStore userStore,
                                            ClaimOptions options, FakeSystemClock clock)
     : base(userStore, options, clock)
 {
 }
Exemple #5
0
        public static IMvcCoreBuilder AddSuperUserTokenController <TKey>(this IMvcCoreBuilder mvcBuilder, Func <IServiceProvider, DateTimeOffset> timestamps,
                                                                         Action <ClaimOptions> configureClaimsAction        = null,
                                                                         Action <TokenOptions> configureTokensAction        = null,
                                                                         Action <SuperUserOptions> configureSuperUserAction = null)
            where TKey : IEquatable <TKey>
        {
            if (configureClaimsAction != null)
            {
                mvcBuilder.Services.Configure(configureClaimsAction);
            }

            if (configureTokensAction != null)
            {
                mvcBuilder.Services.Configure(configureTokensAction);
            }

            if (configureSuperUserAction != null)
            {
                mvcBuilder.Services.Configure(configureSuperUserAction);
            }

            var claims = new ClaimOptions();

            configureClaimsAction?.Invoke(claims);

            var tokens = new TokenOptions();

            configureTokensAction?.Invoke(tokens);

            var superUser = new SuperUserOptions();

            configureSuperUserAction?.Invoke(superUser);

            var credentials = new
            {
                SigningKeyString    = tokens.SigningKey,
                EncryptingKeyString = tokens.EncryptingKey
            }.QuackLike <ITokenCredentials>();

            AuthenticationExtensions.MaybeSetSecurityKeys(credentials);

            var scheme = superUser.Scheme ?? tokens.Scheme;

            mvcBuilder.Services.AddAuthentication().AddJwtBearer(scheme, o =>
            {
                if (tokens.Encrypt)
                {
                    o.TokenValidationParameters = new TokenValidationParameters
                    {
                        TokenDecryptionKeyResolver = (token, securityToken, kid, parameters) => new[] { credentials.EncryptingKey.Key },
                        ValidateIssuerSigningKey   = false,
                        ValidIssuer         = tokens.Issuer,
                        ValidateLifetime    = true,
                        ValidateAudience    = true,
                        ValidAudience       = tokens.Audience,
                        RequireSignedTokens = false,
                        IssuerSigningKey    = credentials.SigningKey.Key,
                        TokenDecryptionKey  = credentials.EncryptingKey.Key,
                        ClockSkew           = TimeSpan.FromSeconds(tokens.ClockSkewSeconds),
                        RoleClaimType       = claims.RoleClaim,
                        NameClaimType       = claims.UserNameClaim
                    };
                }
                else
                {
                    o.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        ValidIssuer         = tokens.Issuer,
                        ValidateLifetime    = true,
                        ValidateAudience    = true,
                        ValidAudience       = tokens.Audience,
                        RequireSignedTokens = true,
                        IssuerSigningKey    = credentials.SigningKey.Key,
                        ClockSkew           = TimeSpan.FromSeconds(tokens.ClockSkewSeconds),
                        RoleClaimType       = claims.RoleClaim,
                        NameClaimType       = claims.UserNameClaim
                    };
                }
            });

            mvcBuilder.Services.TryAddSingleton <IIdentityClaimNameProvider, DefaultIdentityClaimNameProvider>();
            mvcBuilder.Services.TryAddSingleton <ITokenFabricator <TKey> >(r => new DefaultTokenFabricator <TKey>(() => timestamps(r), r.GetRequiredService <IOptionsSnapshot <TokenOptions> >()));

            mvcBuilder.AddActiveRoute <SuperUserTokenController <TKey>, SuperUserFeature, SuperUserOptions>();
            return(mvcBuilder);
        }
Exemple #6
0
        public static void AddAuthentication(this IServiceCollection services,
                                             SecurityOptions security,
                                             SuperUserOptions superUser,
                                             TokenOptions tokens,
                                             CookieOptions cookies,
                                             ClaimOptions claims)
        {
            lock (Sync)
            {
                AuthenticationBuilder authBuilder = null;

                var scheme = tokens.Scheme;

                if (tokens.Enabled || superUser.Enabled || cookies.Enabled)
                {
                    authBuilder = services.AddAuthentication(x =>
                    {
                        x.DefaultScheme             = scheme;
                        x.DefaultAuthenticateScheme = scheme;
                        x.DefaultForbidScheme       = scheme;
                        x.DefaultSignInScheme       = scheme;
                        x.DefaultSignOutScheme      = scheme;
                        x.DefaultChallengeScheme    = scheme;
                    });
                }

                if (tokens.Enabled || superUser.Enabled)
                {
                    var parameters = BuildTokenValidationParameters(security, tokens, claims);

                    authBuilder.AddJwtBearer(scheme, x =>
                    {
                        x.Events = new JwtBearerEvents();
                        x.Events.OnTokenValidated       += OnTokenValidated;
                        x.Events.OnMessageReceived      += OnMessageReceived;
                        x.Events.OnAuthenticationFailed += OnAuthenticationFailed;
                        x.Events.OnChallenge            += OnChallenge;
                        x.SaveToken = true;
                        x.TokenValidationParameters = parameters;
#if DEBUG
                        x.IncludeErrorDetails  = true;
                        x.RequireHttpsMetadata = false;
#else
                        x.IncludeErrorDetails  = false;
                        x.RequireHttpsMetadata = true;
#endif
                    });
                }

                if (cookies.Enabled)
                {
                    authBuilder.AddCookie(cookies.Scheme ?? scheme, cfg =>
                    {
                        cfg.LoginPath          = cookies.SignInPath;
                        cfg.LogoutPath         = cookies.SignOutPath;
                        cfg.AccessDeniedPath   = cookies.ForbidPath;
                        cfg.ReturnUrlParameter = cookies.ReturnOperator;
                        cfg.Events             = new CookieAuthenticationEvents
                        {
                            OnSigningIn = context =>
                            {
                                if (string.IsNullOrWhiteSpace(cookies.Domain))
                                {
                                    context.Options.Cookie.Domain = context.HttpContext.Request.Host.Value;
                                }
                                return(Task.CompletedTask);
                            }
                        };
                        cfg.SlidingExpiration = tokens.AllowRefresh;
                        cfg.ClaimsIssuer      = tokens.Issuer;

                        cfg.Cookie.Name         = cookies.IdentityName;
                        cfg.Cookie.Expiration   = TimeSpan.FromSeconds(tokens.TimeToLiveSeconds);
                        cfg.Cookie.Path         = "/";
                        cfg.Cookie.HttpOnly     = true;
                        cfg.Cookie.IsEssential  = true;
                        cfg.Cookie.SameSite     = SameSiteMode.Strict;
                        cfg.Cookie.MaxAge       = cfg.Cookie.Expiration;
                        cfg.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                    });
                }
            }
        }
Exemple #7
0
        private static TokenValidationParameters BuildTokenValidationParameters(SecurityOptions security, TokenOptions tokens, ClaimOptions claims)
        {
            MaybeSetSecurityKeys(new TokenFabricationRequest
            {
                TokenAudience          = tokens.Audience,
                Encrypt                = tokens.Encrypt,
                EncryptingKey          = security.Encrypting,
                EncryptingKeyString    = tokens.EncryptingKey,
                SigningKey             = security.Signing,
                SigningKeyString       = tokens.SigningKey,
                TokenIssuer            = tokens.Issuer,
                TokenTimeToLiveSeconds = tokens.TimeToLiveSeconds
            });

            var name = claims.UserNameClaim;
            var role = claims.RoleClaim;

            if (tokens.Encrypt)
            {
                return(new TokenValidationParameters
                {
                    TokenDecryptionKeyResolver = (token, securityToken, kid, parameters) => new[] { security.Encrypting.Key },
                    ValidateIssuerSigningKey = false,
                    ValidIssuer = tokens.Issuer,
                    ValidateLifetime = true,
                    ValidateAudience = true,
                    ValidAudience = tokens.Audience,
                    RequireSignedTokens = false,
                    IssuerSigningKey = security.Signing.Key,
                    TokenDecryptionKey = security.Encrypting.Key,
                    ClockSkew = TimeSpan.FromSeconds(tokens.ClockSkewSeconds),
                    RoleClaimType = role,
                    NameClaimType = name
                });
            }

            return(new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                ValidIssuer = tokens.Issuer,
                ValidateLifetime = true,
                ValidateAudience = true,
                ValidAudience = tokens.Audience,
                RequireSignedTokens = true,
                IssuerSigningKey = security.Signing.Key,
                ClockSkew = TimeSpan.FromSeconds(tokens.ClockSkewSeconds),
                RoleClaimType = role,
                NameClaimType = name
            });
        }
 public FakeClaimsAuthenticationService2(FakeHttpContextAccessor httpContextAccessor,
                                         FakeUserStore userStore, ClaimOptions options, FakeSystemClock clock)
     : base(httpContextAccessor, userStore, options, clock)
 {
 }