コード例 #1
0
        public void Validator(string nameIdentifier, string givenName, string surname, string email, bool isValid)
        {
            var command = new AddNewUserAccountCommand()
            {
                Email = email, NameIdentifier = nameIdentifier, GivenName = givenName, Surname = surname
            };

            var result = _validator.Validate(command);

            result.IsValid.ShouldEqual(isValid);
        }
コード例 #2
0
        public async Task Execute()
        {
            using (var db = _dbHelper.GetDbContext())
            {
                db.Users.RemoveRange(db.Users);
                db.SaveChanges();
            }

            var command = new AddNewUserAccountCommand()
            {
                Email = "*****@*****.**", GivenName = "A", NameIdentifier = "123", Surname = "A"
            };
            await _handler.ExecuteAsync(command);

            using (var db = _dbHelper.GetDbContext())
            {
                db.Users.Single().NameIdentifier.ShouldEqual(command.NameIdentifier);
            }
        }
コード例 #3
0
        public void InvalidWhenAddingExistingUser()
        {
            var user = new User()
            {
                Id             = Guid.NewGuid(),
                IsActive       = true,
                NameIdentifier = "123",
                UserClaims     = new List <UserClaim>()
                {
                    new UserClaim()
                    {
                        Type = ClaimTypes.Email, Value = "A"
                    },
                    new UserClaim()
                    {
                        Type = ClaimTypes.GivenName, Value = "B"
                    },
                    new UserClaim()
                    {
                        Type = ClaimTypes.Surname, Value = "*****@*****.**"
                    }
                }
            };

            using (var db = _dbHelper.GetDbContext())
            {
                user.SystemRoleId     = db.SystemRoles.First().Id;
                db.Attach(user).State = EntityState.Added;
                db.SaveChanges();
            }
            var command = new AddNewUserAccountCommand()
            {
                NameIdentifier = user.NameIdentifier,
                Email          = user.UserClaims.Where(c => c.Type == ClaimTypes.Email).Select(c => c.Value).SingleOrDefault(),
                GivenName      = user.UserClaims.Where(c => c.Type == ClaimTypes.GivenName).Select(c => c.Value).SingleOrDefault(),
                Surname        = user.UserClaims.Where(c => c.Type == ClaimTypes.Surname).Select(c => c.Value).SingleOrDefault()
            };
            var result = _validator.Validate(command);

            result.IsValid.ShouldBeFalse();
        }
コード例 #4
0
        public void ConfigureServices(IServiceCollection services)
        {
            ValidatorOptions.Global.LanguageManager = new LocalizedLanguageManager();


            services
            .AddControllers()
            .AddNewtonsoftJson(options => options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc)
            .ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressConsumesConstraintForFormFileParameters = true;
                options.SuppressInferBindingSourcesForParameters        = true;
                options.SuppressModelStateInvalidFilter = true;
                options.SuppressMapClientErrors         = true;
                options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404";
            });

            services
            .AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority = _identityConfig.Authority;
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidAudiences = _identityConfig.ValidAudiences
                };
                options.RequireHttpsMetadata = false;
                options.Events = new JwtBearerEvents
                {
                    OnTokenValidated = async context =>
                    {
                        Serilog.Log.Information("sign in");

                        if (!(context.Principal.Identity is ClaimsIdentity identity))
                        {
                            throw new ArgumentNullException(nameof(context.Principal.Identity));
                        }

                        var commandSender = _container.GetInstance <ICommandSender>();

                        if (identity.HasClaim(e => e.Type == "aud" && e.Value == _identityConfig.ClientAudience))
                        {
                            // get user data from claims
                            var command = new AddNewUserAccountCommand()
                            {
                                NameIdentifier = identity.FindFirst(ClaimTypes.NameIdentifier).Value,
                                GivenName      = identity.FindFirst(ClaimTypes.GivenName).Value,
                                Surname        = identity.FindFirst(ClaimTypes.Surname).Value,
                                Email          = identity.FindFirst(ClaimTypes.Email).Value,
                            };

                            // when valid, create user
                            if ((await commandSender.ValidateAsync(command)).IsValid)
                            {
                                await commandSender.SendAsync(command);
                            }
                            Serilog.Log.Information($"signin for {_identityConfig.ClientAudience}");
                        }

                        if (identity.HasClaim(e => e.Type == "aud" && e.Value == _identityConfig.GisAudience))
                        {
                            Serilog.Log.Information($"signin for {_identityConfig.GisAudience}");
                        }
                    }
                };
            });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder
                                  .WithOrigins(_identityConfig.Client)
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "API", Version = "v1"
                });

                options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme()
                {
                    Type = SecuritySchemeType.OAuth2,

                    Flows = new OpenApiOAuthFlows
                    {
                        Implicit = new OpenApiOAuthFlow
                        {
                            AuthorizationUrl = new Uri($"{_identityConfig.Authority}/connect/authorize", UriKind.Absolute),
                            Scopes           = new Dictionary <string, string>
                            {
                                { _identityConfig.ClientScope, _identityConfig.ClientScope },
                            }
                        }
                    }
                });

                options.OperationFilter <AuthorizeCheckOperationFilter>();
            });

            _bootstrapper
            .Initialize(services, options =>
            {
                // AddAspNetCore() wraps web requests in a Simple Injector scope and
                // allows request-scoped framework services to be resolved.
                options.AddAspNetCore()

                // Ensure activation of a specific framework type to be created by
                // Simple Injector instead of the built-in configuration system.
                // All calls are optional. You can enable what you need. For instance,
                // ViewComponents, PageModels, and TagHelpers are not needed when you
                // build a Web API.
                .AddControllerActivation()
                //.AddViewComponentActivation()
                //.AddPageModelActivation()
                //.AddTagHelperActivation()
                ;

                // Optionally, allow application components to depend on the non-generic
                // ILogger (Microsoft.Extensions.Logging) or IStringLocalizer
                // (Microsoft.Extensions.Localization) abstractions.
                //options.AddLogging();
                //options.AddLocalization();
            })
            .WithAuditing()
            .WithAuthorization <ExampleDbContext>()
            .WithCqrs(AppDomain.CurrentDomain.GetAssemblies().Where(e => e.FullName.Contains("Business")).ToArray())
            ;

            InitializeContainer();
        }