Esempio n. 1
0
        public IdentityClientStoreTests()
        {
            var repository = new Mock<IIdentityRepository>();

            _client = new Client
            {
                ClientId = Guid.NewGuid().ToString()
            };
            IList<Client> clientData = new List<Client> { _client };

            repository.Setup(r => r.GetOneAsync(It.IsAny<Expression<Func<Client, bool>>>()))
                .Returns(() => Task.FromResult(clientData.FirstOrDefault(x => x.ClientId == _client.ClientId)));

            _store = new CustomClientStore(repository.Object);
        }
Esempio n. 2
0
        /// <summary>
        /// Настроить Owin-приложение как identity server для работы с обычными (не windows) пользователями.
        /// </summary>
        /// <param name="app">Owin-приложение.</param>
        private void ConfigureIdentityServer(IAppBuilder app)
        {
            // Настраиваем сервер аутентификации
            app.Map(
                "/identity",
                idsrvApp =>
            {
                var tokenApiScope = new Scope
                {
                    Name         = "api1",
                    Type         = ScopeType.Resource,
                    ScopeSecrets = new List <Secret>
                    {
                        new Secret("secret".Sha256()),
                    },
                };

                var scopes = StandardScopes.All.Concat(new[] { tokenApiScope });

                var factory = new IdentityServerServiceFactory().UseInMemoryScopes(scopes);

                var clientRepository = new RestClientRepository(new ClientRestClient(this.WebApiURL));
                var clientStore      = new CustomClientStore(clientRepository, scopes);
                factory.ClientStore  = new Registration <IClientStore>(resolver => clientStore);

                var userRepository  = new RestUserRepository(new UserRestClient(this.WebApiURL));
                var logger          = new FileAuthLogger($"{AppDomain.CurrentDomain.BaseDirectory}\\IdSrv.Server.identity.log");
                var userService     = new LoggedUserServiceDecorator(new CustomUserService(userRepository), logger);
                factory.UserService = new Registration <IUserService>(resolver => userService);

                // Устанавливаем наш CustomViewService, чтобы после выхода пользователя в сообщении не выводилось
                // неправильное имя клиентского приложения (выводится то, на котором был произведён вход).
                factory.ViewService = new DefaultViewServiceRegistration <CustomViewService>();

                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    LoggingOptions = new LoggingOptions
                    {
                        EnableWebApiDiagnostics    = true,
                        WebApiDiagnosticsIsVerbose = true,
                    },

                    // Имя сервера аутентификации, можно будет наблюдать вверху страницы
                    SiteName = "Embedded IdentityServer",

                    IssuerUri = "https://localhost:44363",

                    // Загружаем сертификат
                    SigningCertificate = Startup.LoadCertificate(),

                    // Для примера все пользователи и клиенты берутся из памяти
                    Factory = factory,

                    AuthenticationOptions = new AuthenticationOptions
                    {
                        // После нажатия кнопки "Выход" на сайте, мы автоматически перенапрам пользователя (см. поле Client.PostLogoutRedirectUris)
                        EnablePostSignOutAutoRedirect = true,
                        RequireSignOutPrompt          = false,
                        EnableSignOutPrompt           = false,

                        // После нажатия на кнопку выхода, выведется страница с ссобщением об успешном выходе.
                        // Здесь указывается, через сколько секунд после вывода этой страницы надо перенаправить пользоватя обратно на сайт.
                        PostSignOutAutoRedirectDelay = 3,

                        // Указываем время жизни куков сервера аутентификации, необходимо, можно ставить
                        // равным или меньшим значия Client.IdentityTokenLifetime (если будет больше, то сервер аутентификации не будет
                        // забывать логины и пароли пользователей)
                        CookieOptions = new IdentityServer3.Core.Configuration.CookieOptions
                        {
                            // Время жизни сессий клиентов
                            ExpireTimeSpan = TimeSpan.FromMinutes(60),
                        },
                    },
                });
            });

            /*app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
             * {
             *  Authority = "https://localhost:44363/identity",
             *  RequiredScopes = new[] { "api1" },
             *  DelayLoadMetadata = true,
             *
             *  ClientId = "api1",
             *  ClientSecret = "secret"
             * });*/
        }
Esempio n. 3
0
        /// <summary>
        /// Настроить Owin-приложение как identity server для работы с windows пользователями.
        /// </summary>
        /// <param name="app">Owin-приложение.</param>
        private void ConfigureWindowsIdentityServer(IAppBuilder app)
        {
            app.Map("/windows", Startup.ConfigureWindowsTokenProvider);

            IEnumerable <Scope> scopes = StandardScopes.All.Concat(new[]
            {
                new Scope
                {
                    Name                    = "idmgr",
                    DisplayName             = "IdentityManager",
                    Type                    = ScopeType.Resource,
                    Emphasize               = true,
                    ShowInDiscoveryDocument = false,
                    Claims                  = new List <ScopeClaim>
                    {
                        new ScopeClaim(Constants.ClaimTypes.Name),
                        new ScopeClaim(Constants.ClaimTypes.Role),
                    },
                },
            });

            var factory = new IdentityServerServiceFactory()
                          .UseInMemoryScopes(scopes);

            var clientRepository = new RestClientRepository(new ClientRestClient(this.WebApiURL));
            var userRepository   = new RestUserRepository(new UserRestClient(this.WebApiURL));
            var clientStore      = new CustomClientStore(clientRepository, scopes, isWindowsAuth: true);
            var logger           = new FileAuthLogger($"{AppDomain.CurrentDomain.BaseDirectory}\\IdSrv.Server.winidentity.log");

            factory.Register(new Registration <IAuthLogger>(r => logger));
            factory.Register(new Registration <IUserRepository>(r => userRepository));
            factory.Register(new Registration <IClientRepository>(r => clientRepository));
            factory.ClientStore = new Registration <IClientStore>(r => clientStore);
            factory.Register(new Registration <ExternalRegistrationUserService>());
            factory.UserService = new Registration <IUserService>(r =>
                                                                  new LoggedUserServiceDecorator(r.Resolve <ExternalRegistrationUserService>(), r.Resolve <IAuthLogger>()));
            factory.Register(new Registration <CustomGrantValidator>());
            factory.CustomGrantValidators.Add(new Registration <ICustomGrantValidator>(r =>
                                                                                       new LoggedGrantValidatorDecorator(r.Resolve <CustomGrantValidator>(), r.Resolve <IAuthLogger>())));
            factory.ViewService = new DefaultViewServiceRegistration <CustomViewService>();
            app.Map(
                "/winidentity",
                idsrvApp =>
            {
                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    SigningCertificate    = Startup.LoadCertificate(),
                    Factory               = factory,
                    AuthenticationOptions = new AuthenticationOptions
                    {
                        EnableLocalLogin  = false,
                        IdentityProviders = this.ConfigureIdentityProviders,

                        // После нажатия кнопки "Выход" на сайте, мы автоматически перенапрам пользователя (см. поле Client.PostLogoutRedirectUris)
                        EnablePostSignOutAutoRedirect = true,

                        // После нажатия на кнопку выхода, выведется страница с ссобщением об успешном выходе.
                        // Здесь указывается, через сколько секунд после вывода этой страницы надо перенаправить пользоватя обратно на сайт.
                        PostSignOutAutoRedirectDelay = 3,

                        // Указываем время жизни куков сервера аутентификации, необходимо, можно ставить
                        // равным или меньшим значия Client.IdentityTokenLifetime (если будет больше, то сервер аутентификации не будет
                        // забывать логины и пароли пользователей)
                        CookieOptions = new IdentityServer3.Core.Configuration.CookieOptions
                        {
                            // Время жизни сессий клиентов
                            ExpireTimeSpan = TimeSpan.FromMinutes(60),
                        },
                    },
                });
            });

            var options = new IdentityServerOptions
            {
                SigningCertificate    = LoadCertificate(),
                Factory               = factory,
                AuthenticationOptions = new AuthenticationOptions
                {
                    EnableLocalLogin  = false,
                    IdentityProviders = this.ConfigureIdentityProviders,
                },
            };

            app.UseIdentityServer(options);
        }