private static void PrepareUrlPathBuilder(
            JsonApiSerializer jsonApiSerializer,
            HttpRequestMessage request,
            JsonApiConfiguration config,
            ApiResource resource)
        {
            var result = config.UrlPathBuilder;
            if (resource == null)
            {
                result = result ?? new DefaultUrlPathBuilder();
            }
            else if (!request.Properties.ContainsKey("MS_RequestContext"))
            {
                result = result ?? new DefaultUrlPathBuilder();
            }
            else
            {
                var routeTemplate = (request.Properties["MS_RequestContext"] as HttpRequestContext)
                    ?.RouteData.Route.RouteTemplate;
                result = result ?? new DefaultUrlPathBuilder(
                    routeTemplate, resource);
            }

            jsonApiSerializer.UrlPathBuilder = result;
        }
 /// <summary>
 /// Returns a path in the form `/resource.UrlPath/id/relationships/relationship.UrlPath/`.
 /// </summary>
 /// <param name="resource">The resource this path is related to.</param>
 /// <param name="id">The unique id of the resource.</param>
 /// <param name="relationship">The relationship this path refers to.</param>
 /// <returns>A <see cref="string"/> containing the path.</returns>
 public virtual string BuildRelationshipPath(ApiResource resource, string id, ResourceRelationship relationship)
 {
     return '/'.TrimJoin(
         BuildCanonicalPath(resource, id), "relationships", relationship.UrlPath)
         .EnsureStartsWith("/")
         .EnsureEndsWith("/");
 }
 /// <summary>
 /// Returns a path in the form `/resource.UrlPath/id/`.
 /// </summary>
 /// <param name="resource">The resource this path refers to.</param>
 /// <param name="id">The unique id of the resource.</param>
 /// <returns>A <see cref="string"/> containing the path.</returns>
 public virtual string BuildCanonicalPath(ApiResource resource, string id)
 {
     return '/'.TrimJoin(
         BuildCanonicalPath(resource), id)
         .EnsureStartsWith("/")
         .EnsureEndsWith("/");
 }
Example #4
0
        public static string GetResourceUrl(ServerRegion region, ApiResource resource)
        {
            string apiBaseUrl = GetApiBaseUrl(region);
            string resourceUrl = string.Format(apiResource[resource], regionString[region]);

            return apiBaseUrl + resourceUrl;
        }
        public ReturnsResourceAttribute(Type resourceType)
        {
            if (!typeof(ApiResource).GetTypeInfo().IsAssignableFrom(resourceType.GetTypeInfo()))
            {
                throw new ArgumentException("Resource types must implement from Saule.IApiResource");
            }

            Resource = resourceType.CreateInstance<ApiResource>();
        }
        private static JToken EnsureHasId(IDictionary<string, JToken> properties, ApiResource resource)
        {
            var id = GetId(properties, resource);
            if (id == null)
            {
                throw new JsonApiException(ErrorType.Server, "Resources must have an id");
            }

            return id;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ResourceRelationship"/> class.
 /// </summary>
 /// <param name="name">The name of the reference on the resource that defines the relationship.</param>
 /// <param name="urlPath">
 /// The url path of this relationship relative to the resource url that holds
 /// the relationship.
 /// </param>
 /// <param name="kind">The kind of relationship.</param>
 /// <param name="relationshipResource">The specification of the related resource.</param>
 protected ResourceRelationship(
     string name,
     string urlPath,
     RelationshipKind kind,
     ApiResource relationshipResource)
 {
     Name = name.ToDashed();
     UrlPath = urlPath.ToDashed();
     RelatedResource = relationshipResource;
     Kind = kind;
 }
        public PreprocessResult PreprocessContent(object @object, ApiResource resource, Uri requestUri)
        {
            var result = new PreprocessResult
            {
                JsonConverters = JsonConverters
            };
            if (requestUri == null)
            {
                throw new ArgumentNullException(nameof(requestUri));
            }

            try
            {
                var error = GetAsError(@object);
                if (error != null)
                {
                    result.ErrorContent = error;
                    return result;
                }

                var dataObject = @object;

                if (QueryContext?.Filtering != null)
                {
                    dataObject = Query.ApplyFiltering(dataObject, QueryContext.Filtering, resource);
                }

                if (QueryContext?.Sorting != null)
                {
                    dataObject = Query.ApplySorting(dataObject, QueryContext.Sorting, resource);
                }

                if (QueryContext?.Pagination != null)
                {
                    dataObject = Query.ApplyPagination(dataObject, QueryContext.Pagination, resource);
                }

                var serializer = new ResourceSerializer(
                    value: dataObject,
                    type: resource,
                    baseUrl: requestUri,
                    urlBuilder: UrlPathBuilder,
                    paginationContext: QueryContext?.Pagination);

                result.ResourceSerializer = serializer;
            }
            catch (Exception ex)
            {
                result.ErrorContent = GetAsError(ex);
            }

            return result;
        }
 /// <summary>
 /// Returns a path in the form `/relatedResource.UrlPath/relatedResource.Id/`.
 /// </summary>
 /// <param name="resource">The resource this path is related to.</param>
 /// <param name="id">The unique id of the resource.</param>
 /// <param name="relationship">The relationship this path refers to.</param>
 /// <param name="relatedResourceId">The id of the related resource.</param>
 /// <returns>A <see cref="string"/> containing the path.</returns>
 public override string BuildRelationshipPath(
     ApiResource resource,
     string id,
     ResourceRelationship relationship,
     string relatedResourceId)
 {
     // empty if no id, because e.g. /api/people != /api/companies/1/employees
     // (all people is not the same as all employees for a company)
     return string.IsNullOrEmpty(relatedResourceId)
         ? null
         : BuildCanonicalPath(relationship.RelatedResource, relatedResourceId);
 }
        internal DefaultUrlPathBuilder(string template, ApiResource resource)
        {
            var templateParts = template.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var dynamicCount = templateParts.Count(t => t.StartsWith("{"));
            var preDynamic = templateParts.TakeWhile(t => !t.StartsWith("{")).ToList();

            if (dynamicCount < 2)
            {
                preDynamic = preDynamic.Take(preDynamic.Count - 1).ToList();
            }

            _prefix = '/'.TrimJoin(preDynamic.ToArray());
        }
 public ResourceSerializer(
     object value,
     ApiResource type,
     Uri baseUrl,
     IUrlPathBuilder urlBuilder,
     PaginationContext paginationContext)
 {
     _urlBuilder = urlBuilder;
     _resource = type;
     _value = value;
     _baseUrl = baseUrl;
     _paginationContext = paginationContext;
     _includedSection = new JArray();
 }
Example #12
0
        public static object ApplyFiltering(object data, FilteringContext context, ApiResource resource)
        {
            var queryable = data as IQueryable;
            if (queryable != null)
            {
                return new FilteringInterpreter(context, resource).Apply(queryable);
            }

            var enumerable = data as IEnumerable;
            if (enumerable != null)
            {
                // all queryables are enumerable, so this needs to be after
                // the queryable case
                return new FilteringInterpreter(context, resource).Apply(enumerable);
            }

            return data;
        }
        public static ResourceResult PreprocessResult(object result, ApiResource resource, QueryContext queryContext)
        {
            if (queryContext?.Filtering != null)
            {
                result = Query.ApplyFiltering(result, queryContext.Filtering, resource);
            }

            if (queryContext?.Sorting != null)
            {
                result = Query.ApplySorting(result, queryContext.Sorting, resource);
            }

            if (queryContext?.Pagination != null)
            {
                result = Query.ApplyPagination(result, queryContext.Pagination, resource);
            }

            return new ResourceResult
            {
                Resource = resource,
                Result = result,
                QueryContext = queryContext
            };
        }
Example #14
0
        /// <summary>
        /// 定义用户可以访问的资源
        /// </summary>
        /// <returns></returns>
        public static List <ApiResource> GetApiResources()
        {
            var oidc = new ApiResource
            {
                Name        = "OAuth.ApiName", //这是资源名称
                Description = "2",
                DisplayName = "33",
                Scopes      =
                {
                    new Scope {
                        Name        = "OtherInfo",
                        Description = "描述",
                        DisplayName = "获取你的其他信息",
                    },
                    new Scope {
                        Name        = "oidc1", //这里是指定客户端能使用的范围名称 , 是唯一的
                        Description = "描述",
                        DisplayName = "获得你的个人信息,好友关系",
                        Emphasize   = true,
                        Required    = true,
                        //ShowInDiscoveryDocument=true,
                    },
                    new Scope {
                        Name        = "oidc2",
                        Description = "描述",
                        DisplayName = "分享内容到你的博客",
                        Emphasize   = true,
                        Required    = true,
                    }
                }
            };

            return(new List <ApiResource> {
                /*
                 * 具有单个作用域的简单API,这样定义的话,作用域(scope)和Api名称(ApiName)相同
                 */
                //new ApiResource("api","描述"),

                //如果需要更多控制,则扩展版本
                //new ApiResource{
                //    Name="userinfo", //资源名称,对应客户端的:ApiName,必须是唯一的
                //    Description="描述",
                //    DisplayName="", //显示的名称

                //    //ApiSecrets =
                //    //{
                //    //    new Secret("secret11".Sha256())
                //    //},

                //    //作用域,对应下面的Cliet的 AllowedScopes
                //    Scopes={
                //        new Scope
                //        {
                //            Name = "apiInfo.read_full",
                //            DisplayName = "完全的访问权限",
                //            UserClaims={ "super" }
                //        },
                //        new Scope
                //        {
                //            Name = "apiinfo.read_only",
                //            DisplayName = "只读权限"
                //        }
                //    },
                //},
                oidc
            });
        }
Example #15
0
 public string BuildRelationshipPath(ApiResource resource, string id, ResourceRelationship relationship,
                                     string relatedResourceId)
 {
     return(string.Empty);
 }
Example #16
0
 public async Task AddApiResource(ApiResource entity)
 {
     await _apiResources.InsertOneAsync(entity);
 }
Example #17
0
        private static ApiResource GetSetApiResponse()
        {
            var localvalue = Kooboo.Data.GlobalDb.GlobalSetting.Store.FullScan(o => o.Name == "ApiResource").FirstOrDefault();

            if (localvalue != null && localvalue.Expiration > DateTime.Now && localvalue.HasKey("AccountUrl"))
            {
                var res = new ApiResource();
                res.AccountUrl = localvalue.KeyValues["AccountUrl"];
                res.ThemeUrl   = localvalue.KeyValues["ThemeUrl"];
                res.ConvertUrl = localvalue.KeyValues["ConvertUrl"];
                res.Expiration = localvalue.Expiration;
                return(res);
            }
            else
            {
                List <string> apis = new List <string>();

                // add the local value.
                if (localvalue != null && localvalue.HasKey("AccountUrl"))
                {
                    var accounturl = localvalue.GetValue("AccountUrl");
                    if (!string.IsNullOrWhiteSpace(accounturl))
                    {
                        if (accounturl.ToLower().StartsWith("https://"))
                        {
                            accounturl = accounturl.Replace("https://", "http://");
                        }
                        apis.Add(accounturl);
                    }
                }

                apis.Add("http://159.138.24.241");
                apis.Add("http://51.15.11.145");
                apis.Add("http://us.koobooapi.com");
                apis.Add("http://eu.koobooapi.com");

                ApiResource apires = null;

                string apiurl = "/account/system/apiresource";
                if (IsOnlineServer)
                {
                    apiurl += apiurl += "?online=true";
                }

                foreach (var item in apis)
                {
                    string url = item + apiurl;
                    try
                    {
                        apires = HttpHelper.Get <ApiResource>(url);
                    }
                    catch (Exception ex)
                    {
                    }
                    if (apires != null && !string.IsNullOrWhiteSpace(apires.AccountUrl))
                    {
                        break;
                    }
                }

                if (apires != null)
                {
                    if (!CustomSslCheck)
                    {
                        apires.AccountUrl = apires.AcccountDomain;
                    }

                    //Kooboo.Data.Helper.ApiHelper.EnsureAccountUrl(apires);

                    var localsetting = new GlobalSetting()
                    {
                        Name = "ApiResource", LastModified = DateTime.Now
                    };
                    localsetting.KeyValues["AccountUrl"] = apires.AccountUrl;
                    localsetting.KeyValues["ThemeUrl"]   = apires.ThemeUrl;
                    localsetting.KeyValues["ConvertUrl"] = apires.ConvertUrl;
                    localsetting.Expiration = apires.Expiration;
                    GlobalDb.GlobalSetting.AddOrUpdate(localsetting);
                    return(apires);
                }
                else
                {
                    if (localvalue != null)
                    {
                        var res = new ApiResource();
                        res.AccountUrl = localvalue.KeyValues["AccountUrl"];
                        res.ThemeUrl   = localvalue.KeyValues["ThemeUrl"];
                        res.ConvertUrl = localvalue.KeyValues["ConvertUrl"];
                        res.Expiration = DateTime.Now.AddDays(1);
                        return(res);
                    }
                }
            }

            return(new ApiResource()
            {
                AccountUrl = "http://159.138.24.241", Expiration = DateTime.Now.AddMinutes(10)
            });
        }
 public async Task AddApiResource(ApiResource entity)
 {
     await _configurationDbContext.ApiResources.AddAsync(entity.ToEntity());
 }
Example #19
0
 public List <ApiSecret> GetApiSecretsByParentId([Service] ApplicationDbContext db, [Parent] ApiResource apiResource)
 {
     return(db.ApiSecrets.Where(x => x.ApiResourceId == apiResource.Id).ToList());
 }
 public FilesClient(ApiResource parent, IDictionary <string, string> pathContext) :
     base(parent, pathContext)
 {
 }
        private JToken SerializeData(ApiResource resource, IDictionary<string, JToken> properties)
        {
            var data = SerializeMinimalData(properties);

            data["attributes"] = SerializeAttributes(properties);
            data["relationships"] = SerializeRelationships(resource, properties);

            if (_isCollection)
            {
                data["links"] = AddUrl(
                    new JObject(),
                    "self",
                    _urlBuilder.BuildCanonicalPath(_resource, (string)EnsureHasId(properties, _resource)));
            }

            return data;
        }
Example #22
0
        public async Task OnPostAsync()
        {
            // Arrange
            const string scope1OriginalName = "Original Name";
            const string scope1EditedName   = "Edited Name";
            const string newScopeName       = "New Name";
            var          databaseName       = $"{DatabaseNamePrefix}.{nameof(OnPostAsync)}";
            var          options            = new DbContextOptionsBuilder <OidcDbContext>()
                                              .UseInMemoryDatabase(databaseName)
                                              .Options;
            ScopesModel   scopes;
            IActionResult post;
            var           scope1 = new ApiScope
            {
                Id   = Random.Next(),
                Name = scope1OriginalName
            };
            var scope2 = new ApiScope {
                Id = Random.Next()
            };
            var client = new ApiResource
            {
                Id     = Random.Next(),
                Scopes = new List <ApiScope>
                {
                    scope1,
                    scope2
                }
            };

            using (var context = new OidcDbContext(options))
            {
                context.Add(client);
                await context.SaveChangesAsync().ConfigureAwait(false);
            }

            // Act
            using (var context = new OidcDbContext(options))
            {
                scopes = new ScopesModel(context)
                {
                    ApiResource = new ApiResource
                    {
                        Id     = client.Id,
                        Scopes = new List <ApiScope>
                        {
                            new ApiScope
                            {
                                Id   = scope1.Id,
                                Name = scope1EditedName
                            },
                            new ApiScope {
                                Name = newScopeName
                            }
                        }
                    }
                };
                post = await scopes.OnPostAsync().ConfigureAwait(false);
            }

            // Assert
            using (var context = new OidcDbContext(options))
            {
                client = await context.ApiResources
                         .Include(x => x.Scopes)
                         .SingleOrDefaultAsync(x => x.Id.Equals(client.Id))
                         .ConfigureAwait(false);

                scope1 = client.Scopes.SingleOrDefault(x => x.Id.Equals(scope1.Id));
                scope2 = client.Scopes.SingleOrDefault(x => x.Id.Equals(scope2.Id));
                var newScope = client.Scopes.SingleOrDefault(x => x.Name.Equals(newScopeName));

                Assert.NotNull(scope1);
                Assert.Equal(scope1EditedName, scope1.Name);
                Assert.Null(scope2);
                Assert.NotNull(newScope);
            }

            var result = Assert.IsType <RedirectToPageResult>(post);

            Assert.Equal("../Details/Scopes", result.PageName);
            Assert.Collection(result.RouteValues, routeValue =>
            {
                var(key, value) = routeValue;
                Assert.Equal(nameof(ApiResource.Id), key);
                Assert.Equal(scopes.ApiResource.Id, value);
            });
        }
 /// <summary>
 /// Returns the UrlPath of the resource, ensuring it starts and ends with '/'
 /// </summary>
 /// <param name="resource">The resource this path refers to.</param>
 /// <returns>A <see cref="string"/> containing the path.</returns>
 public virtual string BuildCanonicalPath(ApiResource resource)
 {
     return '/'.TrimJoin(_prefix, resource.UrlPath)
         .EnsureStartsWith("/")
         .EnsureEndsWith("/");
 }
        private JToken SerializeRelationship(ApiResource resource, ResourceRelationship relationship, IDictionary<string, JToken> properties)
        {
            var relationshipValues = GetValue(relationship.Name, properties);
            var relationshipProperties = relationshipValues as JObject;

            // serialize the links part (so the data can be fetched)
            var objId = EnsureHasId(properties, resource);
            var relToken = GetMinimumRelationship(
                objId.ToString(),
                resource,
                relationship,
                relationshipProperties != null ? (string)GetId(relationshipProperties, relationship.RelatedResource) : null);
            if (relationshipValues == null)
            {
                return relToken;
            }

            // only include data if it exists, otherwise just assume it should be fetched later
            var data = GetRelationshipData(relationship, relationshipValues);
            if (data != null)
            {
                relToken["data"] = data;
            }

            return relToken;
        }
Example #25
0
 public RiskassessmentsClient(ApiResource parent, IDictionary <string, string> pathContext) :
     base(parent, pathContext)
 {
 }
        /// <summary>
        /// Validates the request.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="api">The API.</param>
        /// <returns></returns>
        public async Task <IntrospectionRequestValidationResult> ValidateAsync(NameValueCollection parameters, ApiResource api)
        {
            _logger.LogDebug("Introspection request validation started.");

            // retrieve required token
            var token = parameters.Get("token");

            if (token == null)
            {
                _logger.LogError("Token is missing");

                return(new IntrospectionRequestValidationResult
                {
                    IsError = true,
                    Api = api,
                    Error = "missing_token"
                });
            }

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

            // invalid or unknown token
            if (tokenValidationResult.IsError)
            {
                _logger.LogDebug("Token is invalid.");

                return(new IntrospectionRequestValidationResult
                {
                    IsActive = false,
                    IsError = false,
                    Token = token,
                    Api = api
                });
            }

            _logger.LogDebug("Introspection request validation successful.");

            // valid token
            return(new IntrospectionRequestValidationResult
            {
                IsActive = true,
                IsError = false,
                Token = token,
                Claims = tokenValidationResult.Claims,
                Api = api
            });
        }
        public async Task <IActionResult> Edit(long id, ApiResource apiResource)
        {
            var src = await _context.ApiResources
                      .Include(x => x.Secrets)
                      .Include(x => x.UserClaims)
                      .Include(x => x.Scopes)
                      .AsNoTracking()
                      .SingleOrDefaultAsync(m => m.Id == id);

            #region Claims
            List <ApiResourceClaim>
            Claims_Add        = null,
                Claims_Update = null,
                Claims_Delete = null;
            var claims        = DeserializeFormData <ApiResourceClaim>("UserClaims");
            if (claims != null && claims.Count > 0)
            {
                Claims_Add    = claims.Where(x => x.Id == 0).ToList();
                Claims_Update = claims.Where(x => x.Id > 0).ToList();
                var Ids = claims.Select(x => x.Id).ToList();
                if (Ids.Count > 0)
                {
                    Claims_Delete = src.UserClaims.Where(x => !Ids.Contains(x.Id)).ToList();
                }
            }
            #endregion

            #region AllowedScopes
            List <ApiScope>
            Scopes_Add        = null,
                Scopes_Update = null,
                Scopes_Delete = null;
            var scopes        = DeserializeFormData <ApiScope>("Scopes");
            if (scopes != null && scopes.Count > 0)
            {
                Scopes_Add    = scopes.Where(x => x.Id == 0).ToList();
                Scopes_Update = scopes.Where(x => x.Id > 0).ToList();
                var Ids = scopes.Select(x => x.Id).ToList();
                if (Ids.Count > 0)
                {
                    Scopes_Delete = src.Scopes.Where(x => !Ids.Contains(x.Id)).ToList();
                }
            }
            #endregion

            #region ClientSecrets
            List <ApiSecret>
            Secrets_Add        = null,
                Secrets_Update = null,
                Secrets_Delete = null;
            var secrets        = DeserializeFormData <ApiSecret>("Secrets");
            if (secrets != null && secrets.Count > 0)
            {
                Secrets_Add    = secrets.Where(x => x.Id == 0).ToList();
                Secrets_Update = secrets.Where(x => x.Id > 0).ToList();
                var Ids = secrets.Select(x => x.Id).ToList();
                if (Ids.Count > 0)
                {
                    Secrets_Delete = src.Secrets.Where(x => !Ids.Contains(x.Id)).ToList();
                }
            }
            #endregion

            #region Submit to database
            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(apiResource);
                    await _context.SaveChangesAsync();

                    #region Claims
                    if (Claims_Add != null && Claims_Add.Count > 0)
                    {
                        Claims_Add.ForEach(x => x.ApiResource = apiResource);
                        _context.AddRange(Claims_Add);
                        await _context.SaveChangesAsync();
                    }
                    if (Claims_Update != null && Claims_Update.Count > 0)
                    {
                        Claims_Update.ForEach(x => x.ApiResource = apiResource);
                        _context.UpdateRange(Claims_Update);
                        await _context.SaveChangesAsync();
                    }
                    if (Claims_Delete != null && Claims_Delete.Count > 0)
                    {
                        Claims_Delete.ForEach(x => x.ApiResource = null);
                        _context.RemoveRange(Claims_Delete);
                        await _context.SaveChangesAsync();
                    }
                    #endregion

                    #region AllowedScopes
                    if (Scopes_Add != null && Scopes_Add.Count > 0)
                    {
                        Scopes_Add.ForEach(x => x.ApiResource = apiResource);
                        _context.AddRange(Scopes_Add);
                        await _context.SaveChangesAsync();
                    }
                    if (Scopes_Update != null && Scopes_Update.Count > 0)
                    {
                        Scopes_Update.ForEach(x => x.ApiResource = apiResource);
                        _context.UpdateRange(Scopes_Update);
                        await _context.SaveChangesAsync();
                    }
                    if (Scopes_Delete != null && Scopes_Delete.Count > 0)
                    {
                        Scopes_Delete.ForEach(x => x.ApiResource = null);
                        _context.RemoveRange(Scopes_Delete);
                        await _context.SaveChangesAsync();
                    }
                    #endregion

                    #region ClientSecrets
                    if (Secrets_Add != null && Secrets_Add.Count > 0)
                    {
                        Secrets_Add.ForEach(x => x.ApiResource = apiResource);
                        _context.AddRange(Secrets_Add);
                        await _context.SaveChangesAsync();
                    }
                    if (Secrets_Update != null && Secrets_Update.Count > 0)
                    {
                        Secrets_Update.ForEach(x => x.ApiResource = apiResource);
                        _context.UpdateRange(Secrets_Update);
                        await _context.SaveChangesAsync();
                    }
                    if (Secrets_Delete != null && Secrets_Delete.Count > 0)
                    {
                        Secrets_Delete.ForEach(x => x.ApiResource = null);
                        _context.RemoveRange(Secrets_Delete);
                        await _context.SaveChangesAsync();
                    }
                    #endregion
                }

                catch (DbUpdateConcurrencyException)
                {
                    if (!AppUserExists(id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("Index"));
            }
            #endregion

            return(View(apiResource));
        }
 public SortingInterpreter(SortingContext context, ApiResource resource)
 {
     _context = context;
     _resource = resource;
 }
        public async Task InsertApiResourceAsync(ApiResource apiResource)
        {
            var doc = new ApiResourceDocument(apiResource);

            await InsertAsync(doc);
        }
Example #30
0
 public static StoredApiResource ToEntity(this ApiResource token)
 {
     return(Mapper.Map <ApiResource, StoredApiResource>(token));
 }
        public async Task OnPostAsync()
        {
            // Arrange
            const string property1OriginalValue = "Original Value";
            const string property1EditedValue   = "Edited Value";
            const string newPropertyValue       = "New Value";
            var          databaseName           = $"{DatabaseNamePrefix}.{nameof(OnPostAsync)}";
            var          options = new DbContextOptionsBuilder <IdentityServerDbContext>()
                                   .UseInMemoryDatabase(databaseName)
                                   .Options;
            PropertiesModel properties;
            IActionResult   post;
            var             property1 = new ApiResourceProperty
            {
                Id    = Random.Next(),
                Value = property1OriginalValue
            };
            var property2 = new ApiResourceProperty {
                Id = Random.Next()
            };
            var apiResourceId = Random.Next();
            var apiResource   = new ApiResource
            {
                Id         = apiResourceId,
                Properties = new List <ApiResourceProperty>
                {
                    property1,
                    property2
                }
            };

            using (var context = new IdentityServerDbContext(options, _configurationStoreOptions.Object, _operationalStoreOptions.Object))
            {
                context.Add(apiResource);
                await context.SaveChangesAsync().ConfigureAwait(false);
            }

            // Act
            using (var context = new IdentityServerDbContext(options, _configurationStoreOptions.Object, _operationalStoreOptions.Object))
            {
                properties = new PropertiesModel(context)
                {
                    ApiResource = new ApiResource
                    {
                        Id         = apiResourceId,
                        Properties = new List <ApiResourceProperty>
                        {
                            new ApiResourceProperty
                            {
                                Id    = property1.Id,
                                Value = property1EditedValue
                            },
                            new ApiResourceProperty {
                                Value = newPropertyValue
                            }
                        }
                    }
                };
                post = await properties.OnPostAsync().ConfigureAwait(false);
            }

            // Assert
            using (var context = new IdentityServerDbContext(options, _configurationStoreOptions.Object, _operationalStoreOptions.Object))
            {
                apiResource = await context.ApiResources
                              .Include(x => x.Properties)
                              .SingleOrDefaultAsync(x => x.Id.Equals(apiResourceId))
                              .ConfigureAwait(false);

                property1 = apiResource.Properties.SingleOrDefault(x => x.Id.Equals(property1.Id));
                property2 = apiResource.Properties.SingleOrDefault(x => x.Id.Equals(property2.Id));
                var newProperty = apiResource.Properties.SingleOrDefault(x => x.Value.Equals(newPropertyValue));

                Assert.NotNull(property1);
                Assert.Equal(property1EditedValue, property1.Value);
                Assert.Null(property2);
                Assert.NotNull(newProperty);
            }

            var result = Assert.IsType <RedirectToPageResult>(post);

            Assert.Equal("../Details/Properties", result.PageName);
            Assert.Collection(result.RouteValues, routeValue =>
            {
                var(key, value) = routeValue;
                Assert.Equal(nameof(ApiResource.Id), key);
                Assert.Equal(properties.ApiResource.Id, value);
            });
        }
Example #32
0
 public static ApiResourceDto ToModel(this ApiResource resource)
 {
     return(resource == null ? null : Mapper.Map <ApiResourceDto>(resource));
 }
Example #33
0
 public ProductgroupsClient(ApiResource parent, IDictionary <string, string> pathContext) :
     base(parent, pathContext)
 {
 }
Example #34
0
 public HostedcheckoutsClient(ApiResource parent, IDictionary <string, string> pathContext) :
     base(parent, pathContext)
 {
 }
        private JToken GetMinimumRelationship(string id, ApiResource resource, ResourceRelationship relationship, string relationshipId)
        {
            var links = new JObject();
            AddUrl(links, "self", _urlBuilder.BuildRelationshipPath(resource, id, relationship));
            AddUrl(links, "related", _urlBuilder.BuildRelationshipPath(resource, id, relationship, relationshipId));

            return new JObject
            {
                ["links"] = links
            };
        }
Example #36
0
 public async Task <int> Update(ApiResource apiResource)
 {
     _idb.ApiResources.Update(apiResource);
     return(await _idb.SaveChangesAsync());
 }
        private static JToken SerializeArrayOrObject(ApiResource resource, JToken token, Func<ApiResource, IDictionary<string, JToken>, JToken> serializeObj)
        {
            var dataArray = token as JArray;

            // single thing, just serialize it
            if (dataArray == null)
            {
                return token is JObject ? serializeObj(resource, (JObject)token) : null;
            }

            // serialize each element separately
            var data = new JArray();
            foreach (var obj in dataArray.OfType<JObject>())
            {
                data.Add(serializeObj(resource, obj));
            }

            return data;
        }
Example #38
0
 public string BuildCanonicalPath(ApiResource resource, string id)
 {
     return(string.Empty);
 }
 public string BuildRelationshipPath(ApiResource resource, string id, ResourceRelationship relationship,
     string relatedResourceId)
 {
     return string.Empty;
 }
Example #40
0
        public static void PopulateDatabase(IApplicationBuilder app)
        {
            using var serviceScope         = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope();
            using var configurationContext = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();

            //Seed clients
            bool frontEndClientExists =
                configurationContext.Clients.Any(x => x.ClientId == "7ceea8f0-9ef6-4a41-b0d7-d4ebe99430bb");

            if (!frontEndClientExists)
            {
                Client frontEndClient = new Client
                {
                    ClientName                       = "Microservices.WebUI",
                    ClientId                         = "7ceea8f0-9ef6-4a41-b0d7-d4ebe99430bb",
                    AllowedGrantTypes                = GrantTypes.Implicit,
                    RequireConsent                   = false,
                    AllowAccessTokensViaBrowser      = true,
                    AlwaysIncludeUserClaimsInIdToken = true,
                    PostLogoutRedirectUris           = new List <string>()
                    {
                        "http://localhost:4200"
                    },
                    RedirectUris = new List <string>()
                    {
                        "http://localhost:4200/authentication/signin-oidc",
                        "http://localhost:4200/authentication/redirect-silent"
                    },
                    AllowedScopes = new List <string>()
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "roles", "portal-gateway", "product-service-api"
                    },
                    ClientSecrets = new List <Secret>()
                    {
                        new Secret("2af62f010fab4e558324b841d8006be1".Sha256())
                    },
                    Claims = new List <ClientClaim>()
                    {
                        new ClientClaim(string.Empty, "openid"),
                        new ClientClaim(string.Empty, "profile"),
                        new ClientClaim(string.Empty, "roles")
                    }
                };

                configurationContext.Clients.Add(frontEndClient.ToEntity());
            }

            //Seed identity resources
            IdentityResources.OpenId openId = new IdentityResources.OpenId();
            if (!configurationContext.IdentityResources.Any(x => x.Name == openId.Name))
            {
                configurationContext.IdentityResources.Add(openId.ToEntity());
            }

            IdentityResources.Profile profile = new IdentityResources.Profile();
            if (!configurationContext.IdentityResources.Any(x => x.Name == profile.Name))
            {
                configurationContext.IdentityResources.Add(profile.ToEntity());
            }

            IdentityResource role = new IdentityResource("roles", "Your role(s)", new[] { "role" });

            if (!configurationContext.IdentityResources.Any(x => x.Name == role.Name))
            {
                configurationContext.IdentityResources.Add(role.ToEntity());
            }

            //Seed api resources
            ApiResource portalGateway = new ApiResource("portal-gateway", "Portal.Gateway", new[] { "role" });

            if (!configurationContext.ApiResources.Any(x => x.Name == portalGateway.Name))
            {
                configurationContext.ApiResources.Add(portalGateway.ToEntity());
            }

            ApiResource productService = new ApiResource("product-service-api", "ProductService.API", new[] { "role" });

            if (!configurationContext.ApiResources.Any(x => x.Name == productService.Name))
            {
                configurationContext.ApiResources.Add(productService.ToEntity());
            }


            ApiResource pricingService = new ApiResource("pricing-service-api", "PricingService.API", new[] { "role" });

            if (!configurationContext.ApiResources.Any(x => x.Name == pricingService.Name))
            {
                configurationContext.ApiResources.Add(pricingService.ToEntity());
            }


            ApiResource policyService = new ApiResource("policy-service-api", "PolicyService.API", new[] { "role" });

            if (!configurationContext.ApiResources.Any(x => x.Name == policyService.Name))
            {
                configurationContext.ApiResources.Add(policyService.ToEntity());
            }


            ApiResource policySearchService = new ApiResource("policy-search-service-api", "PolicySearchService.API", new[] { "role" });

            if (!configurationContext.ApiResources.Any(x => x.Name == policySearchService.Name))
            {
                configurationContext.ApiResources.Add(policySearchService.ToEntity());
            }


            ApiResource paymentService = new ApiResource("payment-service-api", "PaymentService.API", new[] { "role" });

            if (!configurationContext.ApiResources.Any(x => x.Name == paymentService.Name))
            {
                configurationContext.ApiResources.Add(paymentService.ToEntity());
            }

            //.AddInMemoryApiScopes(new IdentityServer4.Models.ApiScope[] { new IdentityServer4.Models.ApiScope("portal-gateway", "Portal.Gateway", new[] { "role" })})
            ApiScope portalGatewayScope = new ApiScope("portal-gateway", "Portal.Gateway", new[] { "role" });

            if (!configurationContext.ApiScopes.Any(x => x.Name == portalGatewayScope.Name))
            {
                configurationContext.ApiScopes.Add(portalGatewayScope.ToEntity());
            }

            configurationContext.SaveChanges();
        }
        private JToken SerializeMinimalData(SerializationContext serializationContext, IDictionary<string, JToken> properties, ApiResource resource)
        {
            var data = new JObject
            {
                ["type"] = resource.ResourceType.ToDashed(),
                ["id"] = EnsureHasId(properties, resource)
            };

            return data;
        }
Example #42
0
 /// <summary>
 /// Initializes a new instance of <see cref="ApiResourceBuilder"/>.
 /// </summary>
 /// <param name="resource">A preconfigured resource.</param>
 public ApiResourceBuilder(ApiResource resource)
 {
     _apiResource = resource;
 }
Example #43
0
        public Task <bool> Save(ApiResource model)
        {
            var command = _mapper.Map <RegisterApiResourceCommand>(model);

            return(Bus.SendCommand(command));
        }
Example #44
0
 public PassService()
 {
     CacheResource = new CacheResource(ConfigurationManager.RemoteResources.Local.Pass);
     ApiResource   = new ApiResource(ConfigurationManager.RemoteResources.Remote.Pass);
 }
        private JToken SerializeRelationships(ApiResource resource, IDictionary<string, JToken> properties)
        {
            var relationships = new JObject();

            foreach (var rel in resource.Relationships)
            {
                relationships[rel.Name] = SerializeRelationship(resource, rel, properties);
            }

            return relationships;
        }
        private static JToken SerializeAttributes(SerializationContext serializationContext, IDictionary<string, JToken> properties, ApiResource resource)
        {
            var attributes = new JObject();
            foreach (var attr in resource.Attributes)
            {
                var value = GetValue(attr.Name, properties);
                if (value != null)
                {
                    attributes.Add(attr.Name, value);
                }
            }

            return attributes;
        }
Example #47
0
        public Task <bool> Update(string id, ApiResource model)
        {
            var command = new UpdateApiResourceCommand(model, id);

            return(Bus.SendCommand(command));
        }
 private static JToken GetId(IDictionary<string, JToken> properties, ApiResource resource)
 {
     return GetValue(resource.IdProperty, properties);
 }
Example #49
0
        public Task <Dictionary <string, object> > ProcessAsync(IntrospectionRequestValidationResult validationResult, ApiResource apiResource)
        {
            _logger.LogTrace("Creating introspection response");

            if (validationResult.IsActive == false)
            {
                _logger.LogDebug("Creating introspection response for inactive token.");

                var response = new Dictionary <string, object>();
                response.Add("active", false);
                return(Task.FromResult(response));
            }
            else
            {
                _logger.LogDebug("Creating introspection response for active token.");

                var response = validationResult.Claims.Where(c => c.Type != JwtClaimTypes.Scope).ToClaimsDictionary();

                var allowedScopes = apiResource.Scopes.Select(x => x.Name);
                var scopes        = validationResult.Claims.Where(c => c.Type == JwtClaimTypes.Scope).Select(x => x.Value);
                scopes = scopes.Where(x => allowedScopes.Contains(x));
                response.Add("scope", scopes.ToSpaceSeparatedString());

                response.Add("active", true);

                return(Task.FromResult(response));
            }
        }
Example #50
0
 /// <summary>
 /// Maps an entity to a model.
 /// </summary>
 /// <param name="entity">The entity.</param>
 /// <returns></returns>
 public static IdentityServer4.Models.ApiResource ToModel(this ApiResource entity)
 {
     return(entity == null ? null : Mapper.Map <IdentityServer4.Models.ApiResource>(entity));
 }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.Configure <IISOptions>(options =>
            {
                options.AutomaticAuthentication   = false;
                options.AuthenticationDisplayName = "Windows";
            });

            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
                          .AddTestUsers(TestUsers.Users);

            // in-memory, code config
            //builder.AddInMemoryIdentityResources(Config.GetIdentityResources());
            //builder.AddInMemoryApiResources(Config.GetApis());
            //builder.AddInMemoryClients(Config.GetClients());

            // in-memory, json config
            builder.AddInMemoryIdentityResources(Configuration.GetSection("IdentityResources"));
            builder.AddInMemoryApiResources(Configuration.GetSection("ApiResources"));

            builder.AddClientStore <UpdatableClientStore>();

            List <Client> c = new List <Client>();

            Configuration.GetSection("Clients").Bind(c);

            builder.Services.AddSingleton(c);

            var existingCors = builder.Services.Where(x => x.ServiceType == typeof(ICorsPolicyService)).LastOrDefault();

            if (existingCors != null &&
                existingCors.ImplementationType == typeof(DefaultCorsPolicyService) &&
                existingCors.Lifetime == ServiceLifetime.Transient)
            {
                // if our default is registered, then overwrite with the InMemoryCorsPolicyService
                // otherwise don't overwrite with the InMemoryCorsPolicyService, which uses the custom one registered by the host
                builder.Services.AddTransient <ICorsPolicyService, InMemoryCorsPolicyService>();
            }


            builder.Services.Configure <List <Client> >(Configuration.GetSection("Clients"));



            builder.AddProfileService <TceProfileService>();


            var apir = new ApiResource()
            {
            };


            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                throw new Exception("need to configure key material");
            }

            services.AddAuthentication()
            .AddGoogle(options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                options.ClientId     = "708996912208-9m4dkjb5hscn7cjrn5u0r4tbgkbj1fko.apps.googleusercontent.com";
                options.ClientSecret = "wdfPY6t8H8cecgjlxud__4Gh";
            });
        }
 public PaginationInterpreter(PaginationContext context, ApiResource resource)
 {
     _context = context;
     _resource = resource;
 }
 public void Add(ApiResource entity, CancellationToken cancelationToken = default(CancellationToken))
 {
     configurationDbContext.ApiResources.Add(entity.ToEntity());
 }
 public string BuildCanonicalPath(ApiResource resource, string id)
 {
     return string.Empty;
 }
 public void Update(ApiResource entity, CancellationToken cancelationToken = default(CancellationToken))
 {
     throw new NotImplementedException();
 }
 public FilteringInterpreter(FilteringContext context, ApiResource resource)
 {
     _context = context;
     _resource = resource;
 }
 void SgmApi_ValueChanged(object sender, EventArgs e)
 {
     selectedApiResource = (ApiResource)(int)SgmApi.SelectedSegment;
     selectedModelIndex  = 0;
     AvailableModelsTable.ReloadSections(NSIndexSet.FromIndex(0), UITableViewRowAnimation.Automatic);
 }