private void Add(Scope scope)
        {
            Console.Write("\t{0}: ", scope.Name);

            using (var db = CreateContext())
            {
                var s = db.Scopes.SingleOrDefault(x => x.Name == scope.Name);
                if (s != null)
                {
                    Console.WriteLine("error: already exists.");
                    return;
                }

                var entity = scope.ToEntity();
                db.Scopes.Add(entity);
                try
                {
                    db.SaveChanges();
                    Console.WriteLine("success");
                }
                catch(Exception ex)
                {
                    Console.WriteLine("error: {0}", ex.Message);
                }
            }
        }
        public Task<Dictionary<string, object>> ProcessAsync(IntrospectionRequestValidationResult validationResult, Scope scope)
        {
            Logger.Info("Creating introspection response");

            var response = new Dictionary<string, object>();
            
            if (validationResult.IsActive == false)
            {
                Logger.Info("Creating introspection response for inactive token.");

                response.Add("active", false);
                return Task.FromResult(response);
            }

            if (scope.AllowUnrestrictedIntrospection)
            {
                Logger.Info("Creating unrestricted introspection response for active token.");

                response = validationResult.Claims.ToClaimsDictionary();
                response.Add("active", true);
            }
            else
            {
                Logger.Info("Creating restricted introspection response for active token.");

                response = validationResult.Claims.Where(c => c.Type != Constants.ClaimTypes.Scope).ToClaimsDictionary();
                response.Add("active", true);
                response.Add("scope", scope.Name);
            }

            return Task.FromResult(response);
        }
 public BsonDocument Serialize(Scope scope)
 {
     var doc = new BsonDocument();
     doc["_id"] = scope.Name;
     doc["_version"] = 1;
     doc.SetIfNotNull("displayName", scope.DisplayName);
     var claims = new BsonArray();
     foreach (ScopeClaim scopeClaim in scope.Claims)
     {
         var claim = new BsonDocument();
         claim["name"] = scopeClaim.Name;
         claim["alwaysIncludeInIdToken"] = scopeClaim.AlwaysIncludeInIdToken;
         claim.SetIfNotNull("description", scopeClaim.Description);
         claims.Add(claim);
     }
     doc["claims"] = claims;
     doc.SetIfNotNull("claimsRule", scope.ClaimsRule);
     doc.SetIfNotNull("description", scope.Description);
     doc["emphasize"] = scope.Emphasize;
     doc["enabled"] = scope.Enabled;
     doc["includeAllClaimsForUser"] = scope.IncludeAllClaimsForUser;
     doc["required"] = scope.Required;
     doc["showInDiscoveryDocument"] = scope.ShowInDiscoveryDocument;
     doc["type"] = scope.Type.ToString();
     return doc;
 }
        public void CanSerializeAndDeserializeAScope()
        {
            var s1 = new Scope
            {
                Name = "email",
                Required = true,
                Type = ScopeType.Identity,
                Emphasize = true,
                DisplayName = "email foo",
                Description = "desc foo",
                Claims = new List<ScopeClaim> {
                    new ScopeClaim{Name = "email", Description = "email"}
                }
            };
            var s2 = new Scope
            {
                Name = "read",
                Required = true,
                Type = ScopeType.Resource,
                Emphasize = true,
                DisplayName = "foo",
                Description = "desc",
            };
            var converter = new ScopeConverter(new InMemoryScopeStore(new Scope[] { s1, s2 }));

            var settings = new JsonSerializerSettings();
            settings.Converters.Add(converter);
            var json = JsonConvert.SerializeObject(s1, settings);

            var result = JsonConvert.DeserializeObject<Scope>(json, settings);
            Assert.Same(s1, result);
        }
        protected override void PreInit()
        {
            var api = new Scope
            {
                Name = "api",
                Type = ScopeType.Resource,

                ScopeSecrets = new List<Secret>
                {
                    new Secret("secret".Sha256())
                }
            };

            host.Scopes.Add(StandardScopes.OpenId);
            host.Scopes.Add(StandardScopes.OfflineAccess);
            host.Scopes.Add(api);

            host.Clients.Add(new Client
            {
                Enabled = true,
                ClientId = client_id,
                ClientSecrets = new List<Secret>
                {
                    new Secret(client_secret.Sha256())
                },

                Flow = Flows.AuthorizationCode,
                AllowAccessToAllScopes = true,

                RequireConsent = false,
                RedirectUris = new List<string>
                {
                    redirect_uri
                }
            });

            host.Clients.Add(new Client
            {
                Enabled = true,
                ClientId = client_id_reference,
                ClientSecrets = new List<Secret>
                {
                    new Secret(client_secret.Sha256())
                },

                Flow = Flows.AuthorizationCode,
                AllowAccessToAllScopes = true,
                AccessTokenType = AccessTokenType.Reference,
                UpdateAccessTokenClaimsOnRefresh = false,

                RequireConsent = false,
                RedirectUris = new List<string>
                {
                    redirect_uri
                }
            });
        }
 protected async Task SaveAsync(Scope scope)
 {
     BsonDocument doc = new ScopeSerializer().Serialize(scope);
     IMongoCollection<BsonDocument> collection = _data.Database.GetCollection<BsonDocument>(Settings.ScopeCollection);
     var result = await collection.ReplaceOneAsync(
         Filter.ById(scope.Name),
         doc,
         PerformUpsert
         ).ConfigureAwait(false);
     Debug.WriteLine(result);
 }
 private void Add(Scope[] scopes)
 {
     if (scopes != null && scopes.Any())
     {
         Console.WriteLine();
         Console.WriteLine(" Adding Scopes");
         foreach (var scope in scopes)
         {
             Add(scope);
         }
     }
 }
            public async Task CanFindASingleScope(NpgsqlScopeStore store, Scope scope)
            {
                // Given
                await store.SaveScopeAsync(scope);

                // When
                var scopes = await store.FindScopesAsync(new[] { scope.Name });

                // Then
                scopes.Count().ShouldBe(1);

            }
예제 #9
0
        public static ICollection<Scope> Get()
        {
            var leagueComparerScope = new Scope()
            {
                Name = "LeagueComparer"
            };

            return new List<Scope>
            {
                leagueComparerScope
            };
        }
        public async Task<IntrospectionRequestValidationResult> ValidateAsync(NameValueCollection parameters, Scope scope)
        {
            var fail = new IntrospectionRequestValidationResult { IsError = true };

            // retrieve required token
            var token = parameters.Get("token");
            if (token == null)
            {
                fail.IsActive = false;
                fail.FailureReason = IntrospectionRequestValidationFailureReason.MissingToken;
                return fail;
            }

            // validate token
            var tokenValidationResult = await _tokenValidator.ValidateAccessTokenAsync(token);

            // invalid or unknown token
            if (tokenValidationResult.IsError)
            {
                fail.IsActive = false;
                fail.FailureReason = IntrospectionRequestValidationFailureReason.InvalidToken;
                fail.Token = token;
                return fail;
            }

            // check expected scope
            var expectedScope = tokenValidationResult.Claims.FirstOrDefault(
                c => c.Type == Constants.ClaimTypes.Scope && c.Value == scope.Name);

            // expected scope not present
            if (expectedScope == null)
            {
                fail.IsActive = false;
                fail.IsError = true;
                fail.FailureReason = IntrospectionRequestValidationFailureReason.InvalidScope;
                fail.Token = token;
                return fail;
            }

            // all is good
            var success = new IntrospectionRequestValidationResult
            {
                IsActive = true,
                IsError = false,
                Token = token,
                Claims = tokenValidationResult.Claims
            };

            return success;
        }
        public void AutomapperConfigurationIsValid()
        {
            Models.Scope s = new Models.Scope() { };

            var e = Models.MappingExtensions.ToEntity<int>(s);

            var s2 = new Scope<int>()
            {
                ScopeClaims = new HashSet<ScopeClaim<int>>()
            };
            var m = s2.ToModel();

            Mapper.AssertConfigurationIsValid();
        }
        public void AutomapperConfigurationIsValid()
        {
            IdentityServer3.Core.Models.Scope s = new IdentityServer3.Core.Models.Scope()
            {
            };
            var e = s.ToEntity();

            IdentityServer3.EntityFramework.Entities.Scope s2 = new IdentityServer3.EntityFramework.Entities.Scope()
            {
                ScopeClaims = new HashSet<IdentityServer3.EntityFramework.Entities.ScopeClaim>()
            };
            var m = s2.ToModel();

            Mapper.AssertConfigurationIsValid();
        }
예제 #13
0
        public void AutomapperConfigurationIsValid()
        {
            IdentityServer3.Core.Models.Scope s = new IdentityServer3.Core.Models.Scope()
            {
            };
            var e = s.ToEntity();

            IdentityServer3.EntityFramework.Entities.Scope s2 = new IdentityServer3.EntityFramework.Entities.Scope()
            {
                ScopeClaims = new HashSet <IdentityServer3.EntityFramework.Entities.ScopeClaim>()
            };
            var m = s2.ToModel();

            Mapper.AssertConfigurationIsValid();
        }
        public void AutomapperConfigurationIsValid()
        {
            Models.Scope s = new Models.Scope()
            {
            };

            var e = ModelsMap.ToEntity(s);

            var s2 = new Scope()
            {
                ScopeClaims = new HashSet <ScopeClaim>()
            };
            var m = s2.ToModel();

            Mapper.AssertConfigurationIsValid();
        }
예제 #15
0
        public static IdentityScope ToEntity(this IdentityServer3.Core.Models.Scope s)
        {
            if (s == null)
            {
                return(null);
            }

            if (s.Claims == null)
            {
                s.Claims = new List <ScopeClaim>();
            }
            if (s.ScopeSecrets == null)
            {
                s.ScopeSecrets = new List <Secret>();
            }

            return(Config.CreateMapper().Map <IdentityServer3.Core.Models.Scope, IdentityScope>(s));
        }
        internal async Task<IHttpActionResult> ProcessRequest(NameValueCollection parameters, Scope scope)
        {
            var validationResult = await _requestValidator.ValidateAsync(parameters, scope);

            if (validationResult.IsActive)
            {
                var response = validationResult.Claims.ToClaimsDictionary();
                response.Add("active", true);
                response.Add("scope", scope.Name);

                await RaiseSuccessEventAsync(validationResult.Token, "active", scope.Name);

                return Json(response);
            }

            if (validationResult.IsError)
            {
                if (validationResult.FailureReason == IntrospectionRequestValidationFailureReason.MissingToken)
                {
                    Logger.Error("Missing token");

                    await RaiseFailureEventAsync(validationResult.ErrorDescription, validationResult.Token, scope.Name);
                    return BadRequest("missing_token");
                }

                if (validationResult.FailureReason == IntrospectionRequestValidationFailureReason.InvalidToken)
                {
                    await RaiseSuccessEventAsync(validationResult.Token, "inactive", scope.Name);
                    return Json(new { active = false });
                }

                if (validationResult.FailureReason == IntrospectionRequestValidationFailureReason.InvalidScope)
                {
                    await RaiseFailureEventAsync("Scope not authorized to introspect token", validationResult.Token, scope.Name);
                    return Json(new { active = false });
                }
            }

            throw new InvalidOperationException("Invalid token introspection outcome");
        }
        public void AutomapperConfigurationIsValid()
        {
            IdentityServer3.Core.Models.Scope s = new IdentityServer3.Core.Models.Scope()
            {
            };
            var e = s.ToEntity();

            IdentityServer3.Core.Models.Client c = new IdentityServer3.Core.Models.Client()
            {
            };
            var e2 = c.ToEntity();

            IdentityServer3.EntityFramework.Entities.Scope s2 = new IdentityServer3.EntityFramework.Entities.Scope()
            {
                ScopeClaims = new HashSet<IdentityServer3.EntityFramework.Entities.ScopeClaim>(),
                ScopeSecrets = new HashSet<IdentityServer3.EntityFramework.Entities.ScopeSecret>(),
            };
            var m = s2.ToModel();

            IdentityServer3.EntityFramework.Entities.EntitiesMap.Mapper.ConfigurationProvider.AssertConfigurationIsValid();
            IdentityServer3.Core.Models.EntitiesMap.Mapper.ConfigurationProvider.AssertConfigurationIsValid();
        }
        public void AutomapperConfigurationIsValid()
        {
            IdentityServer3.Core.Models.Scope s = new IdentityServer3.Core.Models.Scope()
            {
            };
            var e = s.ToEntity();

            IdentityServer3.Core.Models.Client c = new IdentityServer3.Core.Models.Client()
            {
            };
            var e2 = c.ToEntity();

            IdentityServer3.EntityFramework.Entities.Scope s2 = new IdentityServer3.EntityFramework.Entities.Scope()
            {
                ScopeClaims  = new HashSet <IdentityServer3.EntityFramework.Entities.ScopeClaim>(),
                ScopeSecrets = new HashSet <IdentityServer3.EntityFramework.Entities.ScopeSecret>(),
            };
            var m = s2.ToModel();

            IdentityServer3.EntityFramework.Entities.EntitiesMap.Mapper.ConfigurationProvider.AssertConfigurationIsValid();
            IdentityServer3.Core.Models.EntitiesMap.Mapper.ConfigurationProvider.AssertConfigurationIsValid();
        }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     var source = serializer.Deserialize<ScopeLite>(reader);
     var scope = new Scope { Name = source.Name, };
     return scope;
 }
 public async Task Insert(NpgsqlScopeStore store, Scope scope)
 {
     await store.SaveScopeAsync(scope);
 }
        public void SetAsync_WhenScopeObject_ExpectSuccess()
        {
            // arrange
            const string Key = @"SetAsync_WhenScopeObject_ExpectSuccess";
            var scope = new Scope { Claims = new List<ScopeClaim> { new ScopeClaim(@"fdf") } };

            var scopes = new List<Scope> { scope, scope, scope };

            var timeSpan = TimeSpan.FromSeconds(10);

            var mockConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>();
            mockConfiguration.Setup(r => r.Get).Returns(() => new RedisCacheConfigurationEntity { CacheDuration = 3600, UseObjectCompression = true, RedisCacheDefaultPrefix = @"RedisCacheManagerTests" });

            var mockJsonSettingsFactory = new Mock<IJsonSettingsFactory>();

            // act
            var redisCacheManager = new RedisCacheManager<IEnumerable<Scope>>(
                RedisHelpers.ConnectionMultiplexer,
                mockConfiguration.Object,
                new JsonSerializerSettings());
            redisCacheManager.SetAsync(Key, scopes, timeSpan).Wait();

            var result = redisCacheManager.GetAsync(Key).Result;

            // assert
            Console.WriteLine(@"Fetched From Cache:{0}", JsonConvert.SerializeObject(result));
            Assert.That(result.GetType() == typeof(List<Scope>));
        }
 private static Scope Version1(BsonDocument doc)
 {
     var scope = new Scope
     {
         Name = doc["_id"].AsString,
         DisplayName = doc.GetValueOrDefault("displayName", Default.DisplayName),
         Claims = new List<ScopeClaim>(
             doc.GetValueOrDefault(
                 "claims",
                 claimDoc =>
                 {
                     var claim = new ScopeClaim();
                     claim.Name = claimDoc.GetValueOrDefault("name", claim.Name);
                     claim.AlwaysIncludeInIdToken = claimDoc.GetValueOrDefault("alwaysIncludeInIdToken",
                         claim.AlwaysIncludeInIdToken);
                     claim.Description = claimDoc.GetValueOrDefault("description", claim.Description);
                     return claim;
                 },
                 new ScopeClaim[] { }
                 )),
     };
     scope.ClaimsRule = doc.GetValueOrDefault("claimsRule", scope.ClaimsRule);
     scope.Description = doc.GetValueOrDefault("description", scope.Description);
     scope.Emphasize = doc.GetValueOrDefault("emphasize", scope.Emphasize);
     scope.Enabled = doc.GetValueOrDefault("enabled", scope.Enabled);
     scope.IncludeAllClaimsForUser = doc.GetValueOrDefault("includeAllClaimsForUser",
         scope.IncludeAllClaimsForUser);
     scope.Required = doc.GetValueOrDefault("required", scope.Required);
     scope.ShowInDiscoveryDocument = doc.GetValueOrDefault("showInDiscoveryDocument",
         scope.ShowInDiscoveryDocument);
     scope.Type = doc.GetValueOrDefault("type", scope.Type);
     return scope;
 }
        public Task SaveScopeAsync(Scope scope)
        {
            string query = $"INSERT INTO {_schema}.scopes(name, is_public, model) " +
                           "VALUES (@name, @public, @model)";

            return _conn.ExecuteCommand(query,
                async cmd =>
                {
                    var serialized = _serializer.Serialize(scope);

                    cmd.Parameters.AddWithValue("name", scope.Name);
                    cmd.Parameters.AddWithValue("public", scope.ShowInDiscoveryDocument);
                    cmd.Parameters.AddWithValue("model", serialized);

                    await cmd.ExecuteNonQueryAsync();

                    return 0;
                });
        }
        public static StoredScope ToDbFormat(Scope scope)
        {
            return new StoredScope
            {
                Id = "scopes/" + scope.Name,
                ShowInDiscoveryDocument = scope.ShowInDiscoveryDocument,
                Name =  scope.Name,
                AllowUnrestrictedIntrospection = scope.AllowUnrestrictedIntrospection,
                ClaimsRule = scope.ClaimsRule,
                Description =  scope.Description,
                DisplayName = scope.DisplayName,
                Emphasize = scope.Emphasize,
                Enabled = scope.Enabled,
                IncludeAllClaimsForUser = scope.IncludeAllClaimsForUser,
                Required = scope.Required,
                Type = scope.Type.ToString(),

                Claims = (from c in scope.Claims select StoredScopeClaim.ToDbFormat(c)).ToList(),
                ScopeSecrets = (from s in scope.ScopeSecrets select StoredSecret.ToDbFormat(s)).ToList()
            };
        }
        public void ToSimpleEntity_WhenComplexEntity_ExpectMapSuccess()
        {
            // Arrange#
            var mockPropertyMapper = new Mock<IPropertyGetSettersTyped<Scope>>();

            mockPropertyMapper.Setup(r => r.GetGetters(It.IsAny<Type>()))
                .Returns(new Dictionary<string, Func<Scope, object>>());

            var scopeMappers = new ScopeMappers<Scope>(mockPropertyMapper.Object);

            var scopeClaim = new ScopeClaim("Name", true) { Description = "Description" };
            var secret = new Secret("Value", "Description", new DateTimeOffset(new DateTime(2016, 1, 1))) { Type = "Type" };

            var scope = new Scope
            {
                Claims = new List<ScopeClaim> { scopeClaim },
                Type = ScopeType.Identity,
                Enabled = true,
                AllowUnrestrictedIntrospection = true,
                ScopeSecrets = new List<Secret> { secret },
                DisplayName = "DisplayName",
                Emphasize = true,
                ClaimsRule = "ClaimsRule",
                IncludeAllClaimsForUser = true,
                Name = "Name",
                Required = true,
                ShowInDiscoveryDocument = true,
                Description = "Description"
            };

            // Act
            var stopwatch = Stopwatch.StartNew();
            var simpleEntity = scopeMappers.ToSimpleEntity(scope);
            stopwatch.Stop();

            // Assert
            this.WriteTimeElapsed(stopwatch);

            Assert.That(simpleEntity, Is.Not.Null);

            Assert.That(simpleEntity.Claims, Is.Not.Null);
            Assert.That(simpleEntity.Claims.Count, Is.EqualTo(1));

            Assert.That(simpleEntity.Type, Is.EqualTo(ScopeType.Identity));
            Assert.That(simpleEntity.Enabled, Is.True);
            Assert.That(simpleEntity.AllowUnrestrictedIntrospection, Is.True);

            Assert.That(simpleEntity.ScopeSecrets, Is.Not.Null);
            Assert.That(simpleEntity.ScopeSecrets.Count, Is.EqualTo(1));

            Assert.That(simpleEntity.DisplayName, Is.EqualTo("DisplayName"));
            Assert.That(simpleEntity.Emphasize, Is.True);
            Assert.That(simpleEntity.ClaimsRule, Is.EqualTo("ClaimsRule"));
            Assert.That(simpleEntity.IncludeAllClaimsForUser, Is.True);
            Assert.That(simpleEntity.Name, Is.EqualTo("Name"));
            Assert.That(simpleEntity.Required, Is.True);
            Assert.That(simpleEntity.ShowInDiscoveryDocument, Is.True);
            Assert.That(simpleEntity.Description, Is.EqualTo("Description"));
        }