<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Serhat Ayata on Medium]]></title>
        <description><![CDATA[Stories by Serhat Ayata on Medium]]></description>
        <link>https://medium.com/@srhtayata?source=rss-b857298ce5cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*olqKLcrXpRFBRj0xDe3_kQ.png</url>
            <title>Stories by Serhat Ayata on Medium</title>
            <link>https://medium.com/@srhtayata?source=rss-b857298ce5cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:45:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srhtayata/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Elasticsearch Multisearch API]]></title>
            <link>https://medium.com/@srhtayata/elasticsearch-multisearch-api-e26cddd39569?source=rss-b857298ce5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e26cddd39569</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Serhat Ayata]]></dc:creator>
            <pubDate>Wed, 10 Jul 2024 09:47:37 GMT</pubDate>
            <atom:updated>2024-07-10T09:47:37.825Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*kqu7Z-pgKqmbhbEghOf6Bg.png" /></figure><p>Projelerde elasticsearch üzerinde arama işlemleri yaparken bazı senaryolarda birden fazla istek atarak alınan dataları kullanmamız gerekebiliyor. Bazı durumlarda bu istek sayısı fazlalaşıyor ve tek bir arama sonucu için birçok istekte bulunmamız gerekebiliyor.</p><p>İşte bu problemi Multisearch API ile çözüme kavuşturabiliriz. Elbette bu kullanımın da artı ve eksileri bulunmakta. Bunlara göre ihtiyaç halinde kullanım sağlanabilir.</p><p>Bu <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html">link</a> üzerinden Elasticsearch dökümanına da erişebilirsiniz.</p><p><strong><em>Artıları :</em></strong></p><ul><li>Bahsettiğimiz gibi birden fazla isteği tek istek üzerinden çalıştırabiliriz.</li><li>Birçok istek için karmaşık kod yapısı oluşturmak yerine daha basitleştirilmiş şekilde kullanabiliriz.</li></ul><p><strong><em>Eksileri :</em></strong></p><ul><li>Burada hata yakalama ve ayırt etme de bazı sıkıntılar yaşayabiliriz.</li><li>Varsayılan olarak, genel istek boyutu <strong>10MB’dir</strong>. Bu sınır, tüm alt isteklerin toplam boyutunu kapsar. Bu sınırı max_content_length parametresiyle değiştirebilirsiniz. Genel istek boyutu hatası <em>“</em><strong><em>request_size_limit_exceeded</em></strong><em>”</em></li><li>Her alt istek için varsayılan boyut sınırı <strong>1MB’dir</strong>. Bu sınırı max_docsize parametresiyle değiştirebilirsiniz.</li><li>Eğer alt isteklerinizin toplam boyutu genel istek boyutu sınırını aşıyorsa veya bir alt isteğinizin boyutu alt istek boyutu sınırını aşıyorsa, Elasticsearch hata mesajı döndürür. Alt istek boyutu hatası <em>“</em><strong><em>search_size_limit_exceeded</em></strong><em>”</em></li></ul><p><strong>Kullanım Önerileri :</strong></p><ul><li>Büyük alt istekleriniz varsa, bunları birden fazla Multisearch isteğine bölebiliriz.</li><li>Daha küçük belgeler kullanarak veya gereksiz alanları hariç tutarak indeksleri optimize edebiliriz.</li></ul><p>Limitlerle ilgili sorulan bir soruya da <a href="https://discuss.elastic.co/t/is-there-a-limit-for-the-msearch/245361">buradan</a> ulaşabilirsiniz.</p><p>Örnek üzerinden gidersek;</p><p>İlk olarak örnek bir index oluşturalım.</p><pre>PUT /test-multisearch<br>{<br>    &quot;settings&quot; : {<br>        &quot;number_of_shards&quot; : 2,<br>        &quot;number_of_replicas&quot; : 1<br>    },<br>    &quot;mappings&quot; : {<br>        &quot;properties&quot; : {<br>            &quot;name&quot; : { &quot;type&quot; : &quot;text&quot; },<br>            &quot;categoryId&quot;: { &quot;type&quot; : &quot;integer&quot; }<br>        }<br>    }<br>}</pre><p>Örnek veriler ekleyelim.</p><pre>POST /test-multisearch/_doc<br>{<br>  &quot;name&quot;:&quot;Coffee Maker&quot;,<br>  &quot;categoryId&quot; : 1<br>}<br><br>POST /test-multisearch/_doc<br>{<br>  &quot;name&quot;:&quot;Monitor&quot;,<br>  &quot;categoryId&quot; : 2<br>}<br><br>...</pre><p>Tüm bu işlemlerden sonra normal arama işlemi yaparsak;</p><pre>GET test-multisearch/_search<br>{<br>  &quot;query&quot;: {<br>    &quot;bool&quot;: {<br>      &quot;must&quot;: [<br>        {<br>          &quot;match&quot;: {<br>            &quot;name&quot;: &quot;Monitor&quot;<br>          }<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>Aldığımız veri ise şu şekilde;</p><pre>{<br>  &quot;took&quot; : 1,<br>  &quot;timed_out&quot; : false,<br>  &quot;_shards&quot; : {<br>    &quot;total&quot; : 2,<br>    &quot;successful&quot; : 2,<br>    &quot;skipped&quot; : 0,<br>    &quot;failed&quot; : 0<br>  },<br>  &quot;hits&quot; : {<br>    &quot;total&quot; : {<br>      &quot;value&quot; : 1,<br>      &quot;relation&quot; : &quot;eq&quot;<br>    },<br>    &quot;max_score&quot; : 0.9808291,<br>    &quot;hits&quot; : [<br>      {<br>        &quot;_index&quot; : &quot;test-multisearch&quot;,<br>        &quot;_type&quot; : &quot;_doc&quot;,<br>        &quot;_id&quot; : &quot;_Himm5AB8XOTTnS2Mpjl&quot;,<br>        &quot;_score&quot; : 0.9808291,<br>        &quot;_source&quot; : {<br>          &quot;name&quot; : &quot;Monitor&quot;,<br>          &quot;categoryId&quot; : 2<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p>Şimdi ise birden fazla cevap alabileceğimiz Multisearch API kısmına gelelim. Burada “<strong>_msearch</strong>” endpoint kullanılır.</p><pre>GET test-multisearch/_msearch<br>{}<br>{ &quot;query&quot;: { &quot;bool&quot;: { &quot;must&quot;: [ { &quot;match&quot;: { &quot;name&quot;: &quot;Monitor&quot; } } ] } } }<br>{}<br>{ &quot;query&quot;: { &quot;bool&quot;: { &quot;must&quot;: [ { &quot;match&quot;: { &quot;name&quot;: &quot;Laptop&quot; } } ] } } }</pre><p>Aldığımız cevap şu şekilde;</p><pre>{<br>  &quot;took&quot; : 1,<br>  &quot;responses&quot; : [<br>    {<br>      &quot;took&quot; : 1,<br>      &quot;timed_out&quot; : false,<br>      &quot;_shards&quot; : {<br>        &quot;total&quot; : 2,<br>        &quot;successful&quot; : 2,<br>        &quot;skipped&quot; : 0,<br>        &quot;failed&quot; : 0<br>      },<br>      &quot;hits&quot; : {<br>        &quot;total&quot; : {<br>          &quot;value&quot; : 1,<br>          &quot;relation&quot; : &quot;eq&quot;<br>        },<br>        &quot;max_score&quot; : 0.9808291,<br>        &quot;hits&quot; : [<br>          {<br>            &quot;_index&quot; : &quot;test-multisearch&quot;,<br>            &quot;_type&quot; : &quot;_doc&quot;,<br>            &quot;_id&quot; : &quot;_Himm5AB8XOTTnS2Mpjl&quot;,<br>            &quot;_score&quot; : 0.9808291,<br>            &quot;_source&quot; : {<br>              &quot;name&quot; : &quot;Monitor&quot;,<br>              &quot;categoryId&quot; : 2<br>            }<br>          }<br>        ]<br>      },<br>      &quot;status&quot; : 200<br>    },<br>    {<br>      &quot;took&quot; : 1,<br>      &quot;timed_out&quot; : false,<br>      &quot;_shards&quot; : {<br>        &quot;total&quot; : 2,<br>        &quot;successful&quot; : 2,<br>        &quot;skipped&quot; : 0,<br>        &quot;failed&quot; : 0<br>      },<br>      &quot;hits&quot; : {<br>        &quot;total&quot; : {<br>          &quot;value&quot; : 1,<br>          &quot;relation&quot; : &quot;eq&quot;<br>        },<br>        &quot;max_score&quot; : 1.5697745,<br>        &quot;hits&quot; : [<br>          {<br>            &quot;_index&quot; : &quot;test-multisearch&quot;,<br>            &quot;_type&quot; : &quot;_doc&quot;,<br>            &quot;_id&quot; : &quot;AHimm5AB8XOTTnS23Zkw&quot;,<br>            &quot;_score&quot; : 1.5697745,<br>            &quot;_source&quot; : {<br>              &quot;name&quot; : &quot;Laptop&quot;,<br>              &quot;categoryId&quot; : 3<br>            }<br>          }<br>        ]<br>      },<br>      &quot;status&quot; : 200<br>    }<br>  ]<br>}</pre><p>Görüldüğü üzere “<strong>responses</strong>” içerisinde çoklu arama verilerine ulaşabiliriz.</p><p>Bu işlemlerden sonra bunu .NET üzerinde uygulayalım.</p><pre>using ElasticSearchMultisearchAPI;<br>using Nest;<br><br>// Connection<br>ConnectionSettings connSettings = new ConnectionSettings(new Uri(&quot;http://localhost:9200&quot;))<br>                                      .DisableDirectStreaming();<br><br>ElasticClient elasticClient = new ElasticClient(connSettings);<br><br><br>// Quer<br>var firstCategoryQuery = new SearchDescriptor&lt;Product&gt;()<br>    .Index(&quot;test-multisearch&quot;)<br>    .Query(q =&gt; q<br>      .Bool(b =&gt; b<br>        .Must(m =&gt; m<br>          .Term(mm =&gt; mm.Field(mmf =&gt; mmf.CategoryId).Value(1)))));<br><br>var secondCategoryQuery = new SearchDescriptor&lt;Product&gt;()<br>    .Index(&quot;test-multisearch&quot;)<br>    .Query(q =&gt; q<br>      .Bool(b =&gt; b<br>        .Must(m =&gt; m<br>          .Term(mm =&gt; mm.Field(mmf =&gt; mmf.CategoryId).Value(2)))));<br><br>// Multisearch<br>var multiSearchRequest = new MultiSearchRequest()<br>{<br>    Operations = new Dictionary&lt;string, ISearchRequest&gt;<br>    {<br>        {<br>            &quot;first-match&quot;, firstCategoryQuery<br>        },<br>        {<br>            &quot;second-match&quot;, secondCategoryQuery<br>        }<br>    }<br>};<br><br>var multiSearchResponse = elasticClient.MultiSearch(multiSearchRequest);<br><br>// Responses<br>var firstResponse = multiSearchResponse.GetResponse&lt;Product&gt;(&quot;first-match&quot;);<br>var secondResponse = multiSearchResponse.GetResponse&lt;Product&gt;(&quot;second-match&quot;);<br><br>Console.WriteLine(firstResponse);<br>Console.WriteLine(secondResponse);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e26cddd39569" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET Service Dependency Injection Yapılandırması]]></title>
            <link>https://medium.com/@srhtayata/net-service-dependency-injection-yap%C4%B1land%C4%B1rmas%C4%B1-e37aa5ec61b1?source=rss-b857298ce5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e37aa5ec61b1</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Serhat Ayata]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 15:58:03 GMT</pubDate>
            <atom:updated>2024-03-03T15:58:03.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tIl0dCNsIUoudo3d.jpg" /></figure><p>Bu başlık altında sadece servis konfigürasyon başlığı için bu işlemi uygulayacağım. Bunu farklı örnekler içinde genişletebiliriz.</p><p>Öncelikli olarak bu yapılandırmaya neden ihtiyaç duyduğumu belirtmek istiyorum. Bu yapıyı kullanmadan önce birçok farklı yöntem ile servis konfigürasyonunu yapmaya çalışmıştım. Ancak bu yazı ile göreceğimiz yapılandırma daha kullanışlı diyebilirim.</p><p>Örneğin servis konfigürsayonunda bu yapıları <strong>extension </strong>altında toplayarak uygulayabiliriz.</p><pre>public static class ServiceCollectionExtensions<br>{<br>    public static IServiceCollection AddAndConfigureDbContext(this IServiceCollection services)<br>    {<br>        var assembly = typeof(Program).Assembly.GetName().Name;<br><br>        services.AddDbContext&lt;CampaignDbContext&gt;(options =&gt;<br>        {<br>            options.UseSqlServer(connectionString: &quot;connectionString&quot;,<br>                                 sqlServerOptionsAction: sqlOptions =&gt;<br>                                 {<br>                                     sqlOptions.MigrationsAssembly(assembly);<br>                                 });<br>        });<br><br>        return services;<br>    }<br><br>    public static IServiceCollection ConfigureLocalization(this IServiceCollection services)<br>    {<br>        services.AddLocalization(options =&gt; options.ResourcesPath = &quot;Resources&quot;);<br><br>        var supportedCultures = new List&lt;CultureInfo&gt; { new(&quot;en&quot;), new(&quot;tr&quot;) };<br>        services.Configure&lt;RequestLocalizationOptions&gt;(options =&gt;<br>        {<br>            options.DefaultRequestCulture = new RequestCulture(&quot;tr&quot;);<br>            options.SupportedCultures = supportedCultures;<br>            options.SupportedUICultures = supportedCultures;<br>        });<br><br>        return services;<br>    }<br>}</pre><p>Bu yapıyı da gördükten sonra asıl konumuz olan yapı ile devam edebiliriz.</p><p>İlk olarak yapımızın imzası olarak kullandığımız “<strong>IServiceInstaller</strong>” arayüzünü oluştururuz.</p><pre>public interface IServiceInstaller<br>{<br>    void Install(<br>      IServiceCollection services, <br>      IConfiguration configuration, <br>      IWebHostEnvironment hostEnvironment);<br>}</pre><p>Bu arayüzü de oluşturduğumuz <strong>DbContextServiceInstaller </strong>ve <strong>LocalizationServiceInstaller </strong>sınıflarına implemente ederiz.</p><pre>public class DbContextServiceInstaller : IServiceInstaller<br>{<br>    public void Install(<br>      IServiceCollection services, <br>      IConfiguration configuration, <br>      IWebHostEnvironment hostEnvironment)<br>    {<br>        var assembly = typeof(Program).Assembly.GetName().Name;<br>        string connString = configuration.GetConnectionString(&quot;Default&quot;);<br><br>        services.AddDbContext&lt;CampaignDbContext&gt;(options =&gt;<br>        {<br>            options.UseSqlServer(connectionString: connString,<br>                                 sqlServerOptionsAction: sqlOptions =&gt;<br>                                 {<br>                                     sqlOptions.MigrationsAssembly(assembly);<br>                                 });<br>        });<br>    }<br>}</pre><pre>public class LocalizationServiceInstaller : IServiceInstaller<br>{<br>    public void Install(<br>      IServiceCollection services, <br>      IConfiguration configuration, <br>      IWebHostEnvironment hostEnvironment)<br>    {<br>        services.AddLocalization(options =&gt; options.ResourcesPath = &quot;Resources&quot;);<br><br>        var supportedCultures = new List&lt;CultureInfo&gt; { new(&quot;en&quot;), new(&quot;tr&quot;) };<br>        services.Configure&lt;RequestLocalizationOptions&gt;(options =&gt;<br>        {<br>            options.DefaultRequestCulture = new RequestCulture(&quot;tr&quot;);<br>            options.SupportedCultures = supportedCultures;<br>            options.SupportedUICultures = supportedCultures;<br>        });<br>    }<br>}</pre><p>Belirlediğimiz sınıfları da oluşturduktan sonra <strong>extension metotları</strong>nı yazdığımız bir <strong>DependencyInjection </strong>sınıfı oluşturalım.</p><pre>public static class DependencyInjection<br>{<br>      public static IServiceCollection InstallServices(<br>        this IServiceCollection services,<br>        IConfiguration configuration,<br>        IWebHostEnvironment hostEnvironment,<br>        params Assembly[] assemblies)<br>    {<br>        IEnumerable&lt;IServiceInstaller&gt; serviceInstallers = assemblies<br>            .SelectMany(a =&gt; a.DefinedTypes)<br>            .Where(IsAssignableToType&lt;IServiceInstaller&gt;)<br>            .Select(Activator.CreateInstance)<br>            .Cast&lt;IServiceInstaller&gt;();<br><br>        foreach (IServiceInstaller serviceInstaller in serviceInstallers)<br>        {<br>            serviceInstaller.Install(services, configuration, hostEnvironment);<br>        }<br><br>        return services;<br><br>        static bool IsAssignableToType&lt;T&gt;(TypeInfo typeInfo) =&gt;<br>            typeof(T).IsAssignableFrom(typeInfo) &amp;&amp;<br>            !typeInfo.IsInterface &amp;&amp;<br>            !typeInfo.IsAbstract;<br>    }<br>}</pre><p>Yukarıda oluşturduğumuz yapı ile <strong>IServiceInstaller </strong>arayüzünden implemente edilen sınıfları alarak <strong>Install </strong>metotları tetiklenir ve istediğimiz işlem uygulanmış olur.</p><p>Şimdi bu yapıyı Program.cs içerisinde çağıralım.</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services<br>    .InstallServices(<br>        configuration,<br>        environment,<br>        typeof(IServiceInstaller).Assembly);<br><br>...</pre><p>Yukarıda kurguladığımız yapıda <strong>IServiceInstaller </strong>arayüzünden elde ettiğimiz sınıflardaki <strong>Install </strong>metotlarını çalıştırıyoruz. Ancak herhangi bir sıralama ile çalışma söz konusu değildir. Şimdi bunun için bir işlem uygulayalım.</p><p><strong>InstallOrderAttribute </strong>attribute sınıfı oluştururuz.</p><pre>[AttributeUsage(AttributeTargets.Class)]<br>public class InstallerOrderAttribute : Attribute<br>{<br>    public int Order { get; set; }<br>}</pre><p>Bu attribute daha önceden oluşturduğumuz <strong>LocalizationServiceInstaller </strong>ve <strong>DbContextServiceInstaller </strong>için uygulanır.</p><pre>[InstallerOrder(Order = 1)]<br>public class LocalizationServiceInstaller : IServiceInstaller<br>{<br>  ...<br>}<br><br><br>[InstallerOrder(Order = 2)]<br>public class DbContextServiceInstaller : IServiceInstaller<br>{<br>  ...<br>}</pre><p>Son olarak <strong>DependencyInjection </strong>sınıfında bir düzenleme yapalım ve sıralama işlemini gerçekleştirelim.</p><pre>public static class DependencyInjection<br>{<br>      public static IServiceCollection InstallServices(<br>        this IServiceCollection services,<br>        IConfiguration configuration,<br>        IWebHostEnvironment hostEnvironment,<br>        params Assembly[] assemblies)<br>    {<br>        IEnumerable&lt;IServiceInstaller&gt; serviceInstallers = assemblies<br>            .SelectMany(a =&gt; a.DefinedTypes)<br>            .Where(IsAssignableToType&lt;IServiceInstaller&gt;)<br>            .Select(Activator.CreateInstance)<br>            .Cast&lt;IServiceInstaller&gt;()<br>            .OrderBy(ord =&gt;<br>            {<br>                var att = ord.GetType()<br>                             .GetCustomAttributes(typeof(InstallerOrderAttribute), true)<br>                             .FirstOrDefault() as InstallerOrderAttribute;<br><br>                if (att == null)<br>                    return int.MaxValue;<br><br>                return att.Order;<br>            });<br><br>        foreach (IServiceInstaller serviceInstaller in serviceInstallers)<br>        {<br>            serviceInstaller.Install(services, configuration, hostEnvironment);<br>        }<br><br>        return services;<br><br>        static bool IsAssignableToType&lt;T&gt;(TypeInfo typeInfo) =&gt;<br>            typeof(T).IsAssignableFrom(typeInfo) &amp;&amp;<br>            !typeInfo.IsInterface &amp;&amp;<br>            !typeInfo.IsAbstract;<br>    }<br>}</pre><p>Bu şekilde <strong>Order </strong>sıralamasına göre önceliklendirerek <strong>Install </strong>metotları çalıştırılır.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e37aa5ec61b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ngrok Kullanımı]]></title>
            <link>https://medium.com/@srhtayata/ngrok-kullan%C4%B1m%C4%B1-7cf729f09d49?source=rss-b857298ce5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cf729f09d49</guid>
            <category><![CDATA[ngrok]]></category>
            <dc:creator><![CDATA[Serhat Ayata]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 18:52:42 GMT</pubDate>
            <atom:updated>2024-03-21T06:31:49.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/834/0*6Z1WFIUB5SBLfOpK.png" /></figure><p>Localhost üzerinde çalıştırdığımız projelerimizi bazı durumlarda dışarıya açmak isteyebiliriz. Ben bu özelliği localhost üzerinde çalıştırdığım bir projeyi dışarıya açarak test amaçlı kullanımını sağlamak istemiştim. Bu ve bunun gibi durumlar için <strong>Ngrok </strong>kullanarak verilen adresi güvenli şekilde internete açabiliriz.</p><p>Aşağıdaki adresten önce üye olup daha sonra indirme işlemini gerçekleştirebiliriz.</p><p><em>https://ngrok.com/<br>https://ngrok.com/download</em></p><p>Üye olduktan sonra <strong>Getting Started -&gt; Your Authtoken </strong>kısmından bize ait bir token alırız.</p><p>Daha sonra <strong>ngrok.exe</strong> dosyası çalıştırılmalıdır. Burada aşağıdaki komut ile token ekleme işlemi gerçekleştirilir.</p><pre>ngrok config add-authtoken &lt;token&gt;</pre><p>Eğer bir adresi dışarıya açmak istersek;</p><pre>ngrok http [port] --host-header=&quot;localhost:[port]&quot;</pre><p>Bazı durumlarda ise birden fazla adresi dışarıya açmak isteyebiliriz. Bu durumda ise ilk olarak <strong>config </strong>dosyasını değiştirmemiz gerekir.</p><p>Daha sonra aşağıdaki komutu çalıştırarak bu dosyayı açabiliriz.</p><pre>ngrok config edit</pre><p>Bu komut ile birlikte açılan dosya içerisindeki içeriği aşağıdaki formatta değiştirebiliriz. Bu formatı kendi istediğimiz şekile dönüştürebiliriz. <strong>Schemes </strong>kısmından <strong>http </strong>ve <strong>https url </strong>kullanımı için ayrıca şemalar belirtilebilir.</p><pre>version: &quot;2&quot;<br>authtoken: 2XZYW1**********************<br>tunnels:<br>  api:<br>    addr: localhost:AAAA<br>    host_header: localhost:AAAA<br>    proto: http<br>    schemes: <br>      - http<br>  web:<br>    addr: localhost:BBBB<br>    host_header: localhost:BBBB<br>    proto: http<br>    schemes: <br>      - http<br>      - https</pre><p><strong>Daha detaylı bilgi</strong> : <a href="https://ngrok.com/docs/agent/config/"><em>https://ngrok.com/docs/agent/config/</em></a></p><p>Yukarıdaki gibi değişikliklerimizi yaptıktan sonra dosyayı kaydedip kapatabiliriz.</p><p>Son olarak ise çalıştırmak için;</p><pre>ngrok start --all</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cf729f09d49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker ile Redis Keyspace Notifications Kullanımı]]></title>
            <link>https://medium.com/@srhtayata/docker-ile-redis-keyspace-notifications-kullan%C4%B1m%C4%B1-a1c6b21db9ac?source=rss-b857298ce5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1c6b21db9ac</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Serhat Ayata]]></dc:creator>
            <pubDate>Sat, 16 Dec 2023 08:23:25 GMT</pubDate>
            <atom:updated>2023-12-16T08:33:34.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*ISUxKhm8mPLCgg2m.png" /></figure><p><strong>Redis Keyspace Notifications</strong> kısaca Redis içerisinde meydana gelen değişimleri takip edip dinleyebileceğimiz bir pub-sub mekanizmasıdır.<br><strong><br></strong>Bu konuyu farklı kaynaklar içerisinde okurken <strong>windows </strong>üzerinde kurulumu ve kullanımını gördüm ancak <strong>docker </strong>ile kullanımını göremedim. Bu nedenle bu yazı içerisinde bunu yapmak istedim.</p><p>Okuduğum bazı kaynaklar şu şekilde;</p><ul><li><a href="https://redis.io/docs/manual/keyspace-notifications/">Kaynak 1</a></li><li><a href="https://borakasmer.medium.com/redis-keyspace-notifications-on-c-988014f0d62c">Kaynak 2</a></li><li><a href="https://dev.to/sayganov/redis-keyspace-notifications-with-a-c-example-2ahp">Kaynak 3</a></li></ul><p>İlk olarak <strong>Docker </strong>kurulumunu gerçekleştirelim.</p><p>Docker compose dosyasını aşağıdaki şekilde çalıştıralım.</p><pre>version: &#39;3.4&#39;<br><br>services:<br>  redis:<br>    container_name: redis<br>    tty: true<br>    command: sh -cx &quot;redis-server --daemonize yes &amp;&amp; redis-cli config set notify-keyspace-events KEA &amp;&amp; sleep infinity&quot;<br>    image: redis<br>    ports:<br>      - 6379:6379<br>    volumes:<br>      - /opt/app_data/redis/:/data<br>  <br>  redisInsight:<br>    image: &#39;redislabs/redisinsight:latest&#39;<br>    ports:<br>      - 8001:8001</pre><p>Yukarıdaki <strong>YML </strong>dosyasının bizim için önemli noktalarını açıklayacak olursak;</p><p>İki ayrı container çalıştırıyoruz. Bunlardan biri yönetim paneli (<strong>Redis Insight</strong>) diğeri ise redis server (<strong>Redis</strong>)</p><p>Asıl önemli kısım ise “<strong>command</strong>” kısmı olacaktır.</p><p>Komut 3 kısımdan oluşmaktadır.</p><ul><li><strong>redis-server<br></strong>Redis server başlatılır. “<strong>daemonize</strong>” opsiyonu ile redis kendini terminalden koparıp çalışmasına devam edecektir.</li><li><strong>redis-cli config set notify-keyspace-events KEA<br>“redis-cli” </strong>terminal programı<strong> </strong>ile redis server tarafına komut yollayıp dönen cevapları okuyabiliriz. Kalan kısım ile rediste hangi olayları takip edeceğimizi belirleyebiliriz.</li><li><strong>sleep</strong><br>Bu komutu redis terminal kapatılsa dahi container durumunu aktif tutabilmek için kullanırız. “<strong>infinity</strong>” opsiyonu ile ise bu durumu sonsuza kadar devam ettirmek istediğimizi belirtiriz. Bu komutun yerine kullanılabilecek olan “<strong>tail</strong>” komutu ile log dosyalarını görüntüleyebiliriz. “<strong>-f /dev/null</strong>” opsiyonu genellikle real-time içerisinde görüntüleme için kullanılır ve container sürekli ayakta tutulur.</li></ul><p>Yukarıdaki komut içerisindeki “<strong>KEA</strong>” hangi anlama gelmektedir sorusu ile devam edebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QZq7BJRM3MNQOSX6.png" /></figure><p>Yukarıda set ettiğimiz <strong>notify-keyspace-events </strong>default olarak kapalıdır. Bunu aktif hale getirmek için yukarıdaki resimde bulunan karakterleri kullanabiliriz. Bu karakterler ile hangi event için log kayıtları tutulacak buna karar verebiliriz.</p><p>Yukarıda kullandığımız “<strong>KEA</strong>” ise tümünü aktif hale getirir.</p><p>Şimdi ise<strong> .NET Console App</strong> içerisinde aşağıdaki gibi uygulayabiliriz.</p><p>Uygulamamızı oluşturduktan sonra <strong>StackExchange.Redis</strong> paketini yükleyebiliriz.</p><p>Daha sonra aşağıdaki kod bloğu ile kullanımı gerçekleştirebiliriz.</p><pre>using StackExchange.Redis;<br><br>var configurationOptions = new ConfigurationOptions<br>{<br>    EndPoints =<br>    {<br>        &quot;localhost:6379&quot;<br>    }<br>};<br><br>var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);<br>var subscriber = connectionMultiplexer.GetSubscriber();<br><br>await subscriber.SubscribeAsync(&quot;__keyspace@0__:*&quot;, (channel, type) =&gt;<br>{<br>    var key = GetKey(channel);<br><br>    switch (type)<br>    {<br>        case &quot;set&quot;:<br>            Console.WriteLine($&quot;Set: {key}&quot;);<br>            break;<br>        case &quot;expire&quot;:<br>            Console.WriteLine($&quot;Expire: {key}&quot;);<br>            break;<br>        case &quot;expired&quot;:<br>            Console.WriteLine($&quot;Expired: {key}&quot;);<br>            break;<br>    }<br>});<br><br>static string GetKey(string channel)<br>{<br>    var index = channel.IndexOf(&#39;:&#39;);<br><br>    if (index &gt;= 0 &amp;&amp; index &lt; channel.Length - 1)<br>    {<br>        return channel[(index + 1)..];<br>    }<br><br>    return channel;<br>}<br><br>Console.ReadLine();</pre><p>Yukarıdaki kod bloğu izleme işlemini sürekli devam ettirecektir. Bu takip işlemini bitirip redis ile bağlantıyı koparmak için aşağıdaki kod bloğunu kullanabiliriz.</p><pre>await subscriber.UnsubscribeAllAsync();<br>await connectionMultiplexer.DisposeAsync();</pre><p>Şimdi bu kod bloğunu çalıştırırsak;</p><p>İlk olarak “<strong>set</strong>” komutunu uygulayalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*g6ii0Dd5NY8fz4RzXxVZhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*WemVAtKNUaa8LCH8o3kMSw.png" /></figure><p>Yukarıda görüldüğü üzere <strong>set </strong>işlemi uygulanan <strong>key </strong>bilgisini elde ettik.</p><p>“<strong>expire</strong>” komutunu uygularsak;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*Oa9HEgX_uYKc0XkVXzU1-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*lFw7CsebZV2FvbcdqwySWw.png" /></figure><p>Yukarıda görüldüğü üzere <strong>expire </strong>işlemi ile uygulanan <strong>key </strong>bilgisini elde ettik.</p><p>Bu şekilde “<strong>KEA</strong>” karakterleri ile tüm eventler için takip mekanizmasını kurduk. Ancak burada elbette senaryolar değişebilir.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1c6b21db9ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AES Encryption ve .NET ile Kullanımı]]></title>
            <link>https://medium.com/@srhtayata/aes-encryption-ve-net-ile-kullan%C4%B1m%C4%B1-41b3a5fb73dd?source=rss-b857298ce5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/41b3a5fb73dd</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[encryption]]></category>
            <dc:creator><![CDATA[Serhat Ayata]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 14:08:48 GMT</pubDate>
            <atom:updated>2023-11-29T14:10:33.792Z</atom:updated>
            <content:encoded><![CDATA[<h3>AES Encryption ve .NET ile Kullanımı</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*OJyTcb28P8a9mLUo" /></figure><p>İlk olarak AES konusuyla başlayabiliriz. AES açılımı “<strong>Advanced Encryption Standard</strong>” olarak bilinen ve verinin şifrelenmesi için kullanılan bir standarttır. Bu standart ilk olarak 2001&#39;de duyurulmuştur. Bunun öncesinde ise DES (Data Encryption Standard) kullanılıyordu.</p><p>Bu standart Vincent Rijmen ve Joan Daemen tarafından geliştirilen <strong>Rijndael </strong>algoritmasında değişiklikler yapılarak oluşturulmuştur. Burada gördüğümüz <strong>Rijndael (<em>RIJ</em>me<em>N</em>-<em>DAE</em>men) </strong>ismini .NET taraflı da göreceğiz.</p><p>AES birçok alanda kullanılmaktadır;</p><ul><li>Veritabanlarında veya uygulamalarımızda hassas verileri gizlemek için kullanılabilir</li><li>Sadece veritabanı değil aynı zamanda harddisk, usb bellek gibi birçok yerde de şifreleme yaparak verilerimizi saklayabiliriz</li><li>Haberleşme güvenliği (e-mail, video arama vs)</li></ul><p>AES “<strong>Substitution-Permutation</strong>” tasarımı kullanmaktadır.</p><ul><li>Verileri 128-bit bloklar halinde şifreler</li><li>Key uzunluğu 128/192/256 bit olmaktadır. DES için ise bu değer 56&#39;dır</li></ul><p>Yani bu demek oluyor ki 128-bit girdi olarak aldığı veriyi şifreledikten sonra 128-bit çıktı olarak verir.</p><p>AES durum (state) denilen 4x4 matris üzerinde çalışır. Bu algoritma verilen girdiyi şifreli çıktıya dönüştüren çevrimlerden (Round) oluşmaktadır.</p><p>Adımlar şu şekildedir;</p><ul><li><strong>Anahtar Oluşturma</strong> (<strong>KeyExpansion</strong>) : Temel anahtar kullanılarak çevrim anahtarını oluşturmayı sağlar.</li><li><strong>İlk Çevrim</strong> (<strong>AddRoundKey</strong>) : Yukarıda da durum olarak belirttiğimiz matris bu ilk çevrim anahtarı ile <strong>XOR </strong>işlemine girer.</li><li><strong>Çevrimler</strong> : <br>- SubBytes<br>- ShiftRows<br>- MixColumn<br>- AddKey</li><li><strong>Son Çevrim<br>- </strong>SubBytes<br>- ShiftRows<br>- AddKey</li></ul><p>Buradaki çalışma mantığını <a href="https://www.youtube.com/watch?v=O4xNJsjtN6E&amp;ab_channel=Computerphile">bu linkteki</a> video ile daha net anlayabiliriz.</p><p>Şimdi ise kendi .NET uygulamamız üzerinde AES Encryption mekanizmasını kullanalım.</p><p>İlk olarak bir <strong>.NET Core Web Api</strong> uygulaması oluşturalım. Buradaki kod blokları için <a href="http://www.developerslearnit.com/2022/07/how-to-encrypt-decrypt-connection-strings-in-asp-net-core-6-0.html">buradan </a>yardım aldım.</p><p>Daha sonra ise <strong>appsettings.json</strong> içerisine bir connectionString bilgisi ekleyelim.</p><pre>{<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>    }<br>  },<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;Default&quot;: &quot;Server=localhost,1433;Database=TESTDB;User Id=sa;Password=BlaBla;MultipleActiveResultSets=true;Encrypt=false;&quot;<br>  },<br>  &quot;AllowedHosts&quot;: &quot;*&quot;<br>}</pre><p>Şifreleme ve şifrelenen veriyi çözme işlemini yapalım. Bunun için ilk olarak <strong>AESService.cs</strong> dosyasını oluşturuyoruz.</p><pre>public static class AESService<br>{<br>    private static readonly byte[] key = Encoding.UTF8.GetBytes(&quot;0001028304051996&quot;);<br>    private static readonly byte[] iv = Encoding.UTF8.GetBytes(&quot;1011121394152507&quot;);<br><br>    public static string Encrypt(string plainText) =&gt; Convert.ToBase64String(EncryptStringToBytes(plainText));<br><br>    public static string Decrypt(string cipherText) =&gt; DecryptStringFromBytes(Convert.FromBase64String(cipherText));<br><br>    private static string DecryptStringFromBytes(byte[] cipherText)<br>    {<br>        if (cipherText == null || cipherText.Length &lt;= 0)<br>            throw new ArgumentNullException(&quot;cipherText&quot;);<br><br>        if (key == null || key.Length &lt;= 0)<br>            throw new ArgumentNullException(&quot;key&quot;);<br><br>        if (iv == null || iv.Length &lt;= 0)<br>            throw new ArgumentNullException(&quot;key&quot;);<br><br>        string plaintext = null;<br><br>        using (var rijAlg = new RijndaelManaged())<br>        {<br><br>            rijAlg.Mode = CipherMode.CBC;<br>            rijAlg.Padding = PaddingMode.PKCS7;<br>            rijAlg.FeedbackSize = 128;<br><br>            rijAlg.Key = key;<br>            rijAlg.IV = iv;<br><br>            var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);<br>            try<br>            {<br>                using (var msDecrypt = new MemoryStream(cipherText))<br>                {<br>                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))<br>                    {<br>                        using (var srDecrypt = new StreamReader(csDecrypt))<br>                        {<br>                            plaintext = srDecrypt.ReadToEnd();<br><br>                        }<br><br>                    }<br>                }<br>            }<br>            catch<br>            {<br>                plaintext = &quot;keyError&quot;;<br>            }<br>        }<br><br>        return plaintext;<br>    }<br><br>    private static byte[] EncryptStringToBytes(string plainText)<br>    {<br>        if (plainText == null || plainText.Length &lt;= 0)<br>            throw new ArgumentNullException(&quot;plainText&quot;);<br><br>        if (key == null || key.Length &lt;= 0)<br>            throw new ArgumentNullException(&quot;key&quot;);<br><br>        if (iv == null || iv.Length &lt;= 0)<br>            throw new ArgumentNullException(&quot;key&quot;);<br><br>        byte[] encrypted;<br><br>        using var rijAlg = new RijndaelManaged();<br>        rijAlg.Mode = CipherMode.CBC;<br>        rijAlg.Padding = PaddingMode.PKCS7;<br>        rijAlg.FeedbackSize = 128;<br><br>        rijAlg.Key = key;<br>        rijAlg.IV = iv;<br><br>        var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);<br><br>        using (var msEncrypt = new MemoryStream())<br>        {<br>            using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))<br>            {<br>                using (var swEncrypt = new StreamWriter(csEncrypt))<br>                {<br>                    swEncrypt.Write(plainText);<br>                }<br>                encrypted = msEncrypt.ToArray();<br>            }<br>        }<br><br>        return encrypted;<br>    }<br>}</pre><p>Yukarıda ilk olarak verdiğimiz “<strong>key</strong>”, “<strong>mode</strong>”, “<strong>padding</strong>”, “<strong>feedbackSize</strong>” ve “<strong>iv</strong>” başlıklarından bahsedelim.</p><p><strong>Key (Secret Key)</strong> : Bu anahtar ile şifreleme ve şifrelenen veriyi çözme işlemi yaparız. Eğer çift taraflı bir iletişim söz konusu ise bu key sadece gönderen ve alıcı tarafı tarafından bilinmelidir.</p><p><strong>IV (Initialization Vector) </strong>: Şifreleme sürecinde güvenliği arttırmak için kullanılan ek bir girdidir. Aynı anahtarla şifrelenen aynı düz metnin her seferinde farklı şifreli metinler üretmesini sağlayarak belirli saldırı türlerini hafifletir.</p><p><strong>Mode </strong>: İşlem modu, blok şifresinin (bu durumda Rijndael) bir şifreli metin bloğu üretmek için bir düz metin bloğunu nasıl işlediğini tanımlar.</p><p><strong>Padding</strong>: Rijndael gibi blok şifrelerde veriler sabit boyutlu bloklar halinde işlenir (AES için 128 bit). Son düz metin bloğu tam bir blok değilse, blok boyutuna uyacak şekilde doldurulması gerekir. <br>Yaygın Padding şemaları arasında, dolgunun her baytının değerinin eklenen bayt sayısı olduğu PKCS#7 (veya PKCS#5) ve bloğu tamamlamak için sıfırların eklendiği sıfır doldurma şemaları bulunur.</p><p>Son olarak ise<strong> AppSettings.cs</strong> dosyasını oluştururuz.</p><pre>public static class AppSettings<br>{<br>    private static IConfiguration _config;<br>    public static void ConfigureSetting(IConfiguration config)<br>    {<br>        _config = config;<br>    }<br><br>    private static string Setting(string Key) =&gt; AESService.Decrypt(_config.GetSection(Key).Value);<br><br>    static Type GetSettingAsType&lt;Type&gt;(object obj, Func&lt;object, Type&gt; callerConverter)<br>    {<br><br>        if (obj != null)<br>        {<br>            Type value = default(Type);<br>            try<br>            {<br>                value = callerConverter(obj);<br>            }<br>            catch<br>            {<br>                value = default(Type);<br>            }<br>            return value;<br>        }<br>        else<br>            return default(Type);<br>    }<br><br>    public static int GetSettingAsInteger(string key) =&gt; GetSettingAsType&lt;int&gt;(Setting(key), obj =&gt; Convert.ToInt32(obj));<br><br>    public static string GetSettingAsString(string key) =&gt; GetSettingAsType&lt;string&gt;(Setting(key), obj =&gt; Convert.ToString(obj));<br>    public static bool? GetSettingAsBool(string key) =&gt; GetSettingAsType&lt;bool?&gt;(Setting(key), obj =&gt; Convert.ToBoolean(obj));<br>}</pre><p>Static olan bu sınıfı kullanarak <strong>Encryption </strong>ve <strong>Decryption </strong>işlemlerini gerçekleştirebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQ7Y9-nkzQtvrEKIjl1YJg.png" /></figure><p>Yukarıda görüldüğü üzere connectionString bilgisini şifreleyebiliriz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41b3a5fb73dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debezium ile MSSQL Veritabanı Değişiklerini Elde Etme (CDC)]]></title>
            <link>https://medium.com/@srhtayata/debezium-ile-mssql-veritaban%C4%B1-de%C4%9Fi%C5%9Fiklerini-elde-etme-cdc-ef4272c0dbbb?source=rss-b857298ce5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef4272c0dbbb</guid>
            <category><![CDATA[debezium]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[mssql]]></category>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Serhat Ayata]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 20:14:02 GMT</pubDate>
            <atom:updated>2023-09-30T20:27:42.963Z</atom:updated>
            <content:encoded><![CDATA[<p>Veritabanındaki <strong>INSERT</strong>, <strong>UPDATE</strong>, <strong>DELETE </strong>işlemlerinde değişen ve mevcut değerlerin elde edilmesi işlemidir. Veritabanı tarafında CDC (Change Data Capture) ile bu değişikler kayıt altına alınır.</p><p>Burada MSSQL tarafında CDC için şunları belirtmekte fayda var.</p><ul><li><strong>SQL Server 2016 SP1 </strong>öncesinde <strong>Developer Edition</strong> ve <strong>Enterprise Edition </strong>tarafında desteklenmektedir.</li><li><strong>SQL Server 2016 SP1 </strong>sonrasında bunların yanı sıra <strong>Standart Edition</strong> tarafında da desteklenmektedir.</li></ul><p>Ayrıca trigger kullanarak bu verileri takip edebilir ve kaydedebiliriz ancak burada ekstra bir maliyet oluşacaktır. <strong>CDC </strong>ise aktif edildiğinde veritabanı loglarından istenen bilgileri okuyarak hizmet verebilir.</p><p>Aşağıda da belirteceğimiz üzere belirlenen şema altındaki tabloda yapılan değişiklikleri takip edeceğiz. Ancak istersek özel olarak bu tablo altındaki belirli bir kolonu da takip edebiliriz.</p><p>Şimdi ise docker ile örnek bir projeyi ayağa kaldıralım.</p><p><strong><em>docker-compose.yml</em></strong></p><pre>version: &#39;3.1&#39;<br>services:<br>  zookeeper:<br>    image: wurstmeister/zookeeper:latest<br>    environment:<br>      ZOOKEEPER_CLIENT_PORT: 2181<br>      ZOOKEEPER_TICK_TIME: 2000<br>    ports:<br>      - 2181:2181<br>      - 2888:2888<br>      - 3888:3888<br><br>  kafka1:<br>    image: wurstmeister/kafka:latest<br>    restart: &quot;no&quot;<br>    ports:<br>      - 9092:9092<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_LISTENERS: INTERNAL://:29092,EXTERNAL://:9092<br>      KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka1:29092,EXTERNAL://localhost:9092<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT<br>      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br><br>  kafka2:<br>    image: wurstmeister/kafka:latest<br>    restart: &quot;no&quot;<br>    depends_on:<br>      - kafka1<br>    ports:<br>      - 9093:9093<br>    environment:<br>      KAFKA_BROKER_ID: 2<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_LISTENERS: INTERNAL://:29093,EXTERNAL://:9093<br>      KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka2:29093,EXTERNAL://localhost:9093<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT<br>      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br><br>  kafdrop:<br>    image: obsidiandynamics/kafdrop<br>    restart: &quot;no&quot;<br>    environment:<br>      KAFKA_BROKERCONNECT: &quot;kafka1:29092,kafka2:29093&quot;<br>      JVM_OPTS: &quot;-Xms16M -Xmx512M -Xss180K -XX:-TieredCompilation -XX:+UseStringDeduplication -noverify&quot;<br>    ports:<br>      - 9000:9000<br>    depends_on:<br>      - kafka1<br>      - kafka2<br><br>  sqlserver:<br>    image: mcr.microsoft.com/mssql/server<br>    ports:<br>      - 1433:1433<br>    environment:<br>      - ACCEPT_EULA=Y<br>      - MSSQL_PID=Standard<br>      - SA_PASSWORD=sa.++112233<br>      - MSSQL_AGENT_ENABLED=true<br><br>  connect:<br>    image: debezium/connect<br>    ports:<br>      - 8083:8083<br>    environment:<br>      CONFIG_STORAGE_TOPIC: my_connect_configs<br>      OFFSET_STORAGE_TOPIC: my_connect_offsets<br>      STATUS_STORAGE_TOPIC: my_connect_statuses<br>      BOOTSTRAP_SERVERS: kafka1:29092,kafka2:29093<br>    depends_on:<br>      - kafka1<br>      - kafka2<br>      - zookeeper<br>      - sqlserver</pre><p>Yukarıdaki YML dosyası içerisinde;</p><ul><li>Kafka1</li><li>Kafka2</li><li>Zookeeper</li><li>Kafdrop (UI Tool)</li><li>SQLServer</li><li>Debezium</li></ul><p>servisleri için konfigüre ediyoruz.</p><p>Daha sonra ise aşağıdaki komut ile compose dosyası ayağa kaldırılır.</p><blockquote>docker-compose up -d</blockquote><p>Bu işlemlerden sonra veritabanı tarafı işlemlerini gerçekleştirebiliriz.</p><pre>// Veritabanını oluştururuz<br>CREATE DATABASE DebeziumTestDB<br><br>// Şema oluşturulur<br>CREATE SCHEMA debezium<br><br>// Oluşturulan şema altında tabloyu oluşturuyoruz<br>CREATE TABLE debezium.products<br>(<br>  id int primary key identity(1,1),<br>  name nvarchar(200),<br>  category nvarchar(max)<br>)<br><br>// Veritabanı özelinde CDC aktifleştirme<br>EXEC sys.sp_cdc_enable_db<br><br>// Tablo özelinde CDC aktifleştirme<br>USE DebeziumTestDB<br>EXEC sys.sp_cdc_enable_table <br>@source_schema = N&#39;debezium&#39;, <br>@source_name = N&#39;products&#39;, <br>@role_name = NULL, <br>@filegroup_name = N&#39;&#39;, <br>@supports_net_changes = 0 </pre><p>Bu işlemlerden sonra debezium ile veritabanı arasında bağlantı kurmamız gerekiyor. Bunun için debezium tarafında bulunan bir Rest API uç noktasına POST isteğinde bulunarak connector oluştururuz.</p><p><strong>Endpoint </strong>: <a href="http://localhost:8083/connectors">http://localhost:8083/connectors</a></p><p><strong>Body </strong>:</p><pre>{<br>  &quot;name&quot;: &quot;debezium-connector&quot;,<br>  &quot;config&quot;: {<br>    &quot;connector.class&quot;: &quot;io.debezium.connector.sqlserver.SqlServerConnector&quot;,<br>    &quot;topic.creation.enable&quot;: true,<br>    &quot;topic.creation.default.replication.factor&quot;: 1,<br>    &quot;topic.creation.default.partitions&quot;: 10,<br>    &quot;topic.creation.default.cleanup.policy&quot;: &quot;compact&quot;,<br>    &quot;topic.creation.default.compression.type&quot;: &quot;lz4&quot;,<br>    &quot;auto.create.topics.enable&quot;: true,<br>    &quot;database.server.name&quot;: &quot;dbserver1&quot;,<br>    &quot;database.hostname&quot;: &quot;sqlserver&quot;,<br>    &quot;database.port&quot;: &quot;1433&quot;,<br>    &quot;database.user&quot;: &quot;sa&quot;,<br>    &quot;database.password&quot;: &quot;sa.++112233&quot;,<br>    &quot;database.names&quot;: &quot;DebeziumTestDB&quot;,<br>    &quot;database.whitelist&quot;: &quot;debezium.products&quot;,<br>    &quot;database.history.kafka.topic&quot;: &quot;dbhistory&quot;,<br>    &quot;database.encrypt&quot;: &quot;false&quot;,<br>    &quot;database.history.kafka.bootstrap.servers&quot;: &quot;kafka1:29092,kafka2:29093&quot;,<br>    &quot;table.whitelist&quot;: &quot;products&quot;,<br>    &quot;schema.include.list&quot;: &quot;debezium&quot;,<br>    &quot;schema.history.internal.kafka.topic&quot;: &quot;schemahistory&quot;,<br>    &quot;schema.history.internal.kafka.bootstrap.servers&quot;: &quot;kafka1:29092,kafka2:29093&quot;,<br>    &quot;table.include.list&quot;: &quot;debezium.products&quot;,<br>    &quot;topic.prefix&quot;: &quot;topicprefix&quot;<br>  }<br>}</pre><p>Tüm bu işlemlerden sonra Console uygulaması oluşturalım ve Kafka üzerinden CDC verilerine ulaşalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*HyFboFZyiK2WmZWapjXGnA.png" /><figcaption>CDC Akışı</figcaption></figure><pre>using Confluent.Kafka;<br><br>try<br>{<br>    var configuration = new ConsumerConfig() <br>    { <br>        GroupId = &quot;topicprefix.DebeziumTestDB.debezium.products&quot;,<br>        BootstrapServers = &quot;localhost:9092&quot;<br>    };<br><br>    using var consumer = new ConsumerBuilder&lt;string, string&gt;(configuration).Build();<br>    consumer.Subscribe(&quot;topicprefix.DebeziumTestDB.debezium.products&quot;);<br><br>    while (true)<br>    {<br>        ConsumeResult&lt;string, string&gt; value = consumer.Consume();<br>        Console.WriteLine($&quot;Value : {value.Value}&quot;);<br>    }<br>}<br>catch (System.Exception ex)<br>{<br>    Console.WriteLine(ex.Message);<br>}</pre><p>Uygulamayı çalıştırırsak ve aşağıdaki query veritabanı tarafında çalıştırılırsa, şu şekilde bir cevap alırız.</p><pre>INSERT INTO debezium.products<br>VALUES(&#39;product 6&#39;,&#39;test category 6&#39;)</pre><pre>{<br>  &quot;schema&quot;: {<br>    &quot;type&quot;: &quot;struct&quot;,<br>    &quot;fields&quot;: [<br>      {<br>        &quot;type&quot;: &quot;struct&quot;,<br>        &quot;fields&quot;: [<br>          {<br>            &quot;type&quot;: &quot;int32&quot;,<br>            &quot;optional&quot;: false,<br>            &quot;field&quot;: &quot;id&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: true,<br>            &quot;field&quot;: &quot;name&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: true,<br>            &quot;field&quot;: &quot;category&quot;<br>          }<br>        ],<br>        &quot;optional&quot;: true,<br>        &quot;name&quot;: &quot;topicprefix.DebeziumTestDB.debezium.products.Value&quot;,<br>        &quot;field&quot;: &quot;before&quot;<br>      },<br>      {<br>        &quot;type&quot;: &quot;struct&quot;,<br>        &quot;fields&quot;: [<br>          {<br>            &quot;type&quot;: &quot;int32&quot;,<br>            &quot;optional&quot;: false,<br>            &quot;field&quot;: &quot;id&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: true,<br>            &quot;field&quot;: &quot;name&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: true,<br>            &quot;field&quot;: &quot;category&quot;<br>          }<br>        ],<br>        &quot;optional&quot;: true,<br>        &quot;name&quot;: &quot;topicprefix.DebeziumTestDB.debezium.products.Value&quot;,<br>        &quot;field&quot;: &quot;after&quot;<br>      },<br>      {<br>        &quot;type&quot;: &quot;struct&quot;,<br>        &quot;fields&quot;: [<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: false,<br>            &quot;field&quot;: &quot;version&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: false,<br>            &quot;field&quot;: &quot;connector&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: false,<br>            &quot;field&quot;: &quot;name&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;int64&quot;,<br>            &quot;optional&quot;: false,<br>            &quot;field&quot;: &quot;ts_ms&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: true,<br>            &quot;name&quot;: &quot;io.debezium.data.Enum&quot;,<br>            &quot;version&quot;: 1,<br>            &quot;parameters&quot;: {<br>              &quot;allowed&quot;: &quot;true,last,false,incremental&quot;<br>            },<br>            &quot;default&quot;: &quot;false&quot;,<br>            &quot;field&quot;: &quot;snapshot&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: false,<br>            &quot;field&quot;: &quot;db&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: true,<br>            &quot;field&quot;: &quot;sequence&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: false,<br>            &quot;field&quot;: &quot;schema&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: false,<br>            &quot;field&quot;: &quot;table&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: true,<br>            &quot;field&quot;: &quot;change_lsn&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: true,<br>            &quot;field&quot;: &quot;commit_lsn&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;int64&quot;,<br>            &quot;optional&quot;: true,<br>            &quot;field&quot;: &quot;event_serial_no&quot;<br>          }<br>        ],<br>        &quot;optional&quot;: false,<br>        &quot;name&quot;: &quot;io.debezium.connector.sqlserver.Source&quot;,<br>        &quot;field&quot;: &quot;source&quot;<br>      },<br>      {<br>        &quot;type&quot;: &quot;string&quot;,<br>        &quot;optional&quot;: false,<br>        &quot;field&quot;: &quot;op&quot;<br>      },<br>      {<br>        &quot;type&quot;: &quot;int64&quot;,<br>        &quot;optional&quot;: true,<br>        &quot;field&quot;: &quot;ts_ms&quot;<br>      },<br>      {<br>        &quot;type&quot;: &quot;struct&quot;,<br>        &quot;fields&quot;: [<br>          {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;optional&quot;: false,<br>            &quot;field&quot;: &quot;id&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;int64&quot;,<br>            &quot;optional&quot;: false,<br>            &quot;field&quot;: &quot;total_order&quot;<br>          },<br>          {<br>            &quot;type&quot;: &quot;int64&quot;,<br>            &quot;optional&quot;: false,<br>            &quot;field&quot;: &quot;data_collection_order&quot;<br>          }<br>        ],<br>        &quot;optional&quot;: true,<br>        &quot;name&quot;: &quot;event.block&quot;,<br>        &quot;version&quot;: 1,<br>        &quot;field&quot;: &quot;transaction&quot;<br>      }<br>    ],<br>    &quot;optional&quot;: false,<br>    &quot;name&quot;: &quot;topicprefix.DebeziumTestDB.debezium.products.Envelope&quot;,<br>    &quot;version&quot;: 1<br>  },<br>  &quot;payload&quot;: {<br>    &quot;before&quot;: null,<br>    &quot;after&quot;: {<br>      &quot;id&quot;: 4,<br>      &quot;name&quot;: &quot;product 6&quot;,<br>      &quot;category&quot;: &quot;test category 6&quot;<br>    },<br>    &quot;source&quot;: {<br>      &quot;version&quot;: &quot;2.2.0.Alpha3&quot;,<br>      &quot;connector&quot;: &quot;sqlserver&quot;,<br>      &quot;name&quot;: &quot;topicprefix&quot;,<br>      &quot;ts_ms&quot;: 1696104363803,<br>      &quot;snapshot&quot;: &quot;false&quot;,<br>      &quot;db&quot;: &quot;DebeziumTestDB&quot;,<br>      &quot;sequence&quot;: null,<br>      &quot;schema&quot;: &quot;debezium&quot;,<br>      &quot;table&quot;: &quot;products&quot;,<br>      &quot;change_lsn&quot;: &quot;0000002a:000003a8:0002&quot;,<br>      &quot;commit_lsn&quot;: &quot;0000002a:000003a8:0003&quot;,<br>      &quot;event_serial_no&quot;: 1<br>    },<br>    &quot;op&quot;: &quot;c&quot;,<br>    &quot;ts_ms&quot;: 1696104366879,<br>    &quot;transaction&quot;: null<br>  }<br>}</pre><p><strong>Daha farklı bilgi ve kullanımlar da olabilir. Bu konudaki farklı bilgi ve düşünceni bizimle de paylaşırsan mutlu olurum :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef4272c0dbbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entity Framework Core Hi/Lo Kullanımı]]></title>
            <link>https://medium.com/@srhtayata/entity-framework-core-hi-lo-kullan%C4%B1m%C4%B1-64bc0106228e?source=rss-b857298ce5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/64bc0106228e</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <dc:creator><![CDATA[Serhat Ayata]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 17:03:27 GMT</pubDate>
            <atom:updated>2023-09-15T17:09:22.395Z</atom:updated>
            <content:encoded><![CDATA[<p>Veritabanında 2 adet ilişkili tablo oluşturduğumuzu düşünelim.</p><pre>CREATE TABLE Customers (<br>    Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,<br>    Name VARCHAR(255),<br>    Email VARCHAR(255)<br>);<br><br>CREATE TABLE Orders (<br>    Id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,<br>    CustomerId INT,<br>    OrderDate DATE,<br>    TotalAmount DECIMAL(10, 2),<br>    CONSTRAINT FK_Order_Customer_Id <br>    FOREIGN KEY (CustomerId) REFERENCES Customers(Id)<br>);</pre><p>Burada görüldüğü üzere tablolardaki <strong>Id </strong>bilgisi birer birer artan olarak ayarlanıyor. Bunu aynı şekilde kod tarafında Annotation ile düzenlersek şu şekilde ilerleyebiliriz.</p><pre>public class Customer<br>{<br>    [Key]<br>    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public string Email { get; set; }<br><br>    public ICollection&lt;Order&gt; Orders { get; set; }<br>}<br><br>public class Order<br>{<br>    [Key]<br>    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]<br>    public int Id { get; set; }<br>    public DateTime OrderDate { get; set; }<br>    public decimal TotalAmount { get; set; }<br><br>    public int CustomerId { get; set; }<br>    public Customer Customer { get; set; }<br>}</pre><p>Şimdi bu kullanımlardan sonra<strong> EF Core </strong>kullanımına geçelim.</p><p>Burada oluşturduğumuz <strong>ProjectDbContext </strong>şu şekilde olsun.</p><pre>public class ProjectDbContext : DbContext<br>{<br>    public DbSet&lt;Customer&gt; Customers{ get; set; }<br> <br>    public DbSet&lt;Order&gt; Orders { get; set; }<br> <br>    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)<br>    {<br>        optionsBuilder<br>            .UseSqlServer(&quot;ConnectionString&quot;);<br>    }<br> <br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        modelBuilder.Entity&lt;Customer&gt;(builder =&gt;<br>        {<br>            builder<br>                .HasMany(x =&gt; x.Orders)<br>                .WithOne()<br>                .HasForeignKey(x =&gt; x.CustomerId);<br>        });<br>    }<br>}</pre><p>Bu işlemden de sonra örnek bir ekleme işlemi yapalım.</p><pre>using var context = new ProjectDbContext();<br> <br>var customer = new Customer() { <br>    Name = &quot;Serhat&quot;,<br>    Email = &quot;serhat@...&quot;<br>};<br><br>context.Customers.Add(customer);<br> <br>var order = new Order { <br>    OrderDate = DateTime.Now,<br>    TotalAmount = 225.50M,<br>    CustomerId = customer.Id<br>};<br><br>context.Orders.Add(order);<br> <br>await context.SaveChangesAsync()</pre><p>Burada <strong>SaveChangesAync </strong>metodu hata verecektir. <br>(Hata mesajı : <strong><em>“The INSERT statement conflicted with the FOREIGN KEY constraint “</em>FK_Order_Customer_Id<em>”</em></strong>)</p><p>Bunun nedeni eklediğimiz customer için henüz veritabanına bir kayıt atılmadığı için <strong>Id </strong>değeri <strong>0 </strong>gelmektedir.</p><p>İşte bu tarz senaryolarda <strong>HiLo </strong>algoritmasını kullanmak işimize yarayabilir. Burada <strong>ProjectDbContext </strong>içerisinde <strong>OnModelCreating </strong>metodunda aşağıdaki şekilde bir değişiklik yapalım.</p><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        modelBuilder.Entity&lt;Customer&gt;(builder =&gt;<br>        {<br>            builder<br>                .HasMany(x =&gt; x.Orders)<br>                .WithOne()<br>                .HasForeignKey(x =&gt; x.CustomerId);<br><br>            builder<br>                .Property(x =&gt; x.Id)<br>                .UseHiLo(&quot;customerseq&quot;);<br>        });<br>    }</pre><p>Database migration eklersek şu şekilde bir Sequence oluşturulduğunu görürüz.</p><pre>migrationBuilder<br>  .CreateSequence(name: &quot;customerseq&quot;, incrementBy: 10); // default 10</pre><p>Yukarıdaki şekilde düzenlersek ekleme işleminde customer <strong>Id </strong>değeri 0 olmayacaktır.</p><p>Peki burada neler olduğuna gelirsek, <strong>Hi/Lo</strong> algoritması şu şekilde çalışıyor.</p><p>Örneğin yukarıdaki ekleme işlemi gerçekleşirken <strong>Hi/Lo</strong> ile birlikte;</p><pre>using var context = new ProjectDbContext();<br> <br>var customer = new Customer() { <br>    Name = &quot;Serhat&quot;,<br>    Email = &quot;serhat@...&quot;<br>};<br><br>context.Customers.Add(customer);<br> <br>var order = new Order { <br>    OrderDate = DateTime.Now,<br>    TotalAmount = 225.50M,<br>    CustomerId = customer.Id<br>};<br><br>context.Orders.Add(order);<br> <br>await context.SaveChangesAsync()</pre><ol><li>Customers tablosunda herhangi bir kayıt olmadığını varsayalım. <br>İlk olarak <strong>EF </strong>tarafından <strong>Add</strong> metodu ile<strong> </strong>veritabanında<strong> <br><em>“SELECT NEXT VALUE FOR [customerseq]”</em></strong> çalıştırılır. <br>Buradan <strong>1 </strong>değeri döner çünkü herhangi bir kayıt eklenmedi henüz.</li><li>Migration oluşturulurken <strong>CreateSequence </strong>metodundaki <strong>incrementBy </strong>değeri ile <strong>Id </strong>değeri <strong>1–10</strong> arası bu rezerve edilir ve farklı bağlantılarla bu <strong>Id </strong>değerlerine aynı anda ekleme yapılamaz.</li></ol><p>Yukarıdaki kod bloğunu ayrı ayrı 2 süreç olarak çalıştırdığımızı düşünelim. Burada <strong>SaveChangesAsync() </strong>noktasına breakpoint ekleyelim.</p><p>Yukarıda 1. maddede <strong>Id </strong>değeri <strong>1 </strong>olanı eklediğimizi varsayalım. <br>Bunun üstüne 2 defa daha bu kod bloğunu çalıştırırsak eğer <br>ilkinde <strong>Id </strong>rezerve işlemi <strong>2–11</strong> arasında gerçekleşir. <br>Diğerinde ise <strong>Id </strong>rezerve işlemi <strong>12–21 </strong>arasında gerçekleşir. <br>İlk customerId <strong>2</strong>, ikinci çalışmada ise <strong>12 </strong>olarak alınır.</p><p>Burada dikkat edilmesi gereken nokta iki kodda da <strong>SaveChangesAsync </strong>metoduna breakpoint ekledik ve daha kayıt işlemi yapılmadan <strong>Add </strong>metodunu iki farklı yerde çalıştırdık bu nedenle sırayla <strong>2–11</strong> ve <strong>12–21</strong> şeklinde rezervasyonlar gerçekleştirildi.</p><p>Burada görüldüğü üzere verilen <strong>incrementBy </strong>değeri kadar bir aralık rezerve edilir. İşlem tamamlanınca ise bu rezerve sonlanır.</p><p><a href="https://en.wikipedia.org/wiki/Hi/Lo_algorithm">Hi/Lo algoritma örneği </a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*qlagrKT64-lYuMB3IRPuBw.png" /></figure><p><strong>Daha farklı bilgi ve kullanımlar da olabilir. Bu konudaki farklı bilgi ve düşünceni bizimle de paylaşırsan mutlu olurum :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64bc0106228e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IdentityServer4 — Part3 / ASP.NET Core JS Client]]></title>
            <link>https://medium.com/@srhtayata/identityserver4-part3-asp-net-core-js-client-dd87064b0362?source=rss-b857298ce5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd87064b0362</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[identityserver4]]></category>
            <dc:creator><![CDATA[Serhat Ayata]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 19:04:08 GMT</pubDate>
            <atom:updated>2023-04-21T19:04:08.366Z</atom:updated>
            <content:encoded><![CDATA[<h3>IdentityServer4 — Part3 / ASP.NET Core JS Client</h3><p>IdentityServer4 ile kimlik doğrulama işlemini bu sefer browser tabanlı bir Javascript uygulaması (SPA) üzerinden ilerleteceğiz.</p><p>Süreç şu şekilde ilerleyecek;</p><ul><li>Kullanıcı Login işlemini yaparak bir Token elde edecek.</li><li>Bu token ile API uygulamasına istekte bulunabilecek.</li><li>Daha sonra ise Logout işlemi yapılacak.</li></ul><p>İlk olarak <strong>ASP.NET Web App</strong> uygulamasını oluşturuyoruz. applicationUrl olarak ise <a href="https://localhost:5003/"><strong>https://localhost:5003</strong></a><strong> </strong>ayarlanacaktır<strong>.</strong></p><p>Bu uygulama kullanıcı taraflı çalışacağı için HTML ve Javascript dosyalarını da kullanacak şekilde <strong>Program.cs</strong> düzenlemesi yapılacak. Yani statik dosyaları kullanmak üzere middleware eklenmelidir. Bunlar sayesinde hem statik dosyalara ulaşabileceğiz hem de bu dosyaların varsayılan dizini olarak ise “<strong>~/wwroot</strong>” belirtmiş olacağız.</p><pre>...<br>app.UseDefaultFiles();<br>app.UseStaticFiles();<br><br>...</pre><p>IdentityServer — Part2&#39;de OpenId Connect protokolü için bir kütüphane yüklemiştik. Bu projede de aynı şekilde bir kütüphaneye ihtiyaç duyuyoruz. Bu kütüphaneye örnek olarak <strong>oidc-client</strong> kütüphanesi örnek verilebilir. Bunu NPM ile veya manuel olarak yükleyebiliriz.</p><p>Proje konumunda aşağıdaki komutları çalıştırıyoruz.</p><pre>npm i oidc-client<br>copy node_modules\oidc-client\dist\* wwwroot</pre><p>Şimdi ise HTML ve JS dosyalarını wwwroot içerisine ekliyoruz. Burada ekleyeceğimiz 2 HTML ve 1 adet JS dosyası bulunacak.</p><ul><li>index.html</li><li>callback.html</li><li>app.js</li></ul><p>İlk olarak <strong>index.html</strong> ile başlayalım. Buraya hem kendi oluşturduğumuz <strong>app.js</strong> kütüphanesini hem de <strong>oidc-client.js</strong> kütüphanesini ekleyeceğiz.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;title&gt;Client JS IdentityServer4&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;button id=&quot;login&quot;&gt;Login&lt;/button&gt;<br>    &lt;button id=&quot;api&quot;&gt;Call API&lt;/button&gt;<br>    &lt;button id=&quot;logout&quot;&gt;Logout&lt;/button&gt;<br><br>    &lt;div id=&quot;results&quot;&gt;&lt;/div&gt;<br><br>    &lt;script src=&quot;oidc-client.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>app.js</strong></p><pre>// Log messages<br>function log() {<br>    document.getElementById(&#39;results&#39;).innerText = &#39;&#39;;<br><br>    Array.prototype.forEach.call(arguments, function (msg) {<br>        if (msg instanceof Error) {<br>            msg = &quot;Error: &quot; + msg.message;<br>        }<br>        else if (typeof msg !== &#39;string&#39;) {<br>            msg = JSON.stringify(msg, null, 2);<br>        }<br>        document.getElementById(&#39;results&#39;).innerHTML += msg + &#39;\r\n&#39;;<br>    });<br>}<br><br>// Click events<br>document.getElementById(&quot;login&quot;).addEventListener(&quot;click&quot;, login, false);<br>document.getElementById(&quot;api&quot;).addEventListener(&quot;click&quot;, api, false);<br>document.getElementById(&quot;logout&quot;).addEventListener(&quot;click&quot;, logout, false);<br><br>// Daha sonra ise OpenID Connect protokolünü kullanmak üzere <br>// oidc-client kütüphanesi ile gelen UserManager sınıfı kullanılır<br>// Belirli konfigürasyon ayarları yapılır ve bunu UserManager&#39;a yollarız<br><br>var config = {<br>    authority: &quot;https://localhost:5001&quot;, // identity server url<br>    client_id: &quot;js&quot;, // identity server tarafındaki client&#39;ın client id&#39;si<br>    client_secret: &quot;secret&quot;, // identity server tarafındaki client&#39;ın client secret bilgisi<br>    redirect_uri: &quot;https://localhost:5003/callback.html&quot;, // loginden sonra yönlendirilecek url<br>    response_type: &quot;code&quot;, // Grant type : Authorization code<br>    scope: &quot;openid profile catalog_fullpermission&quot;, // istenen scope bilgileri<br>    post_logout_redirect_uri : &quot;https://localhost:5003/index.html&quot;, // logout işleminden sonraki yönlendirilecek url<br>};<br>var mgr = new Oidc.UserManager(config);<br><br>mgr.getUser().then(function (user) {<br>    if (user) {<br>        log(&quot;User logged in&quot;, user.profile);<br>    }<br>    else {<br>        log(&quot;User not logged in&quot;);<br>    }<br>});<br><br>// Click eventlerinde belirtilen login,api ve logout metotları tanımlanır<br>// signinRedirect ve signoutRedirect metotları ise login ve logout için kullanılır<br><br>function login() {<br>    mgr.signinRedirect();<br>}<br><br>function api() {<br>    mgr.getUser().then(function (user) {<br>        var url = &quot;https://localhost:5002/api/catalog&quot;; // API Url<br><br>        var xhr = new XMLHttpRequest();<br>        xhr.open(&quot;GET&quot;, url);<br>        xhr.onload = function () {<br>            log(xhr.status, JSON.parse(xhr.responseText));<br>        }<br>        xhr.setRequestHeader(&quot;Authorization&quot;, &quot;Bearer &quot; + user.access_token);<br>        xhr.send();<br>    });<br>}<br><br>function logout() {<br>    mgr.signoutRedirect();<br>}</pre><p><strong>callback.html</strong></p><p>Kullanıcı girişinden sonra buraya yönlendirme sağlanır. Eğer başarılı bir kullanıcı girişi yapıldıysa tekrar <strong>index.html</strong> sayfasına yönlendirilir.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;title&gt;&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;script src=&quot;oidc-client.js&quot;&gt;&lt;/script&gt;<br>    &lt;script&gt;<br>        new Oidc.UserManager({response_mode:&quot;query&quot;}).signinRedirectCallback().then(function() {<br>            window.location = &quot;index.html&quot;;<br>        }).catch(function(e) {<br>            console.error(e);<br>        });<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Daha sonra IdentityServer tarafına Client bilgisini ekleyelim.</p><pre>public static class Config<br>{<br>    public static IEnumerable&lt;Client&gt; Clients =&gt;<br>    new Client[]<br>    {<br>        new Client<br>        {<br>            ClientId = &quot;jsClient&quot;,<br>            ClientName = &quot;Javascript Client&quot;,<br>            ClientSecrets = { new Secret(&quot;secret&quot;.Sha256()) },<br>            AllowedGrantTypes = GrantTypes.Code,<br>            // where to redirect to after login<br>            RedirectUris = { &quot;https://localhost:5003/callback.html&quot; },<br>            // where to redirect to after logout<br>            PostLogoutRedirectUris = { &quot;https://localhost:5003/index.html&quot;  },<br>            AllowedCorsOrigins =     { &quot;https://localhost:5003&quot; },<br>            AllowOfflineAccess = true,<br>            AllowedScopes = new List&lt;string&gt;<br>            {<br>              IdentityServerConstants.StandardScopes.OpenId,<br>              IdentityServerConstants.StandardScopes.Profile<br>             }<br>        }<br>    };<br><br>    public static IEnumerable&lt;IdentityResource&gt; IdentityResources =&gt;<br>        new List&lt;IdentityResource&gt;<br>        {<br>            new IdentityResources.OpenId(),<br>            new IdentityResources.Profile()<br>        };<br>    }</pre><p>API tarafında ise CORS Policy ayarını oluşturup daha sonra yetkilendirme konfigürasyonunu sağlıyoruz.</p><pre>...<br>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddPolicy(&quot;default&quot;, policy =&gt;<br>    {<br>        policy.WithOrigins(&quot;https://localhost:5003&quot;)<br>            .AllowAnyHeader()<br>            .AllowAnyMethod();<br>    });<br>});<br><br>builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)<br>    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =&gt;<br>    {<br>        options.Authority = &quot;https://localhost:5001&quot;; // IdentityServer<br>        options.TokenValidationParameters = new TokenValidationParameters<br>        {<br>            ValidateAudience = false,<br>            ClockSkew = TimeSpan.Zero<br>        };<br>    });<br>...<br><br>app.UseRouting();<br>app.UseCors(&quot;default&quot;);<br><br>app.UseAuthentication();<br>app.UseAuthorization();<br>...</pre><p>Aynı şekilde API tarafında Controller şu şekilde olacak. Burada CORS Policy kontrol izni de ekleriz.</p><pre>[EnableCors(&quot;default&quot;)]<br>[HttpGet]<br>public IActionResult Get()<br>{<br>    return new JsonResult(from c in User.Claims select new { c.Type, c.Value });<br>}</pre><p>Bu işlemleri yaptıktan sonra ise Login, CallAPI ve Logout fonksiyonlarını kullanabiliriz.</p><p><a href="https://github.com/serhatayata/IdentityServer4-Projects/tree/master/IdentityServer_3">Proje Github Linki</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd87064b0362" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IdentityServer4 — Part2]]></title>
            <link>https://medium.com/@srhtayata/identityserver4-part2-e438e0d1420c?source=rss-b857298ce5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e438e0d1420c</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[oidc]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[identity-server]]></category>
            <dc:creator><![CDATA[Serhat Ayata]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 16:18:54 GMT</pubDate>
            <atom:updated>2023-04-21T11:33:57.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>IdentityServer4 — Part2 / ASP.NET Core MVC</h3><p>Bu yazıda OpenId Connect protokolü ile kullanıcı kimlik doğrulama işlemi gerçekleştireceğim. IdentityServer olarak tekrardan bir önceki yazıda yaptığım proje üzerinden devam ediyorum.</p><p>Bunun için ilk olarak <strong>ASP.NET Core MVC</strong> uygulaması oluşturuyoruz.</p><p>Aşağıdaki kütüphaneleri ekliyoruz.</p><ul><li><strong>Microsoft.AspNetCore.Authentication.OpenIdConnect</strong></li><li><strong>IdentityServer4.Template</strong></li></ul><p>Bu projede .NET 7 üzerinde geliştirme yapıyorum ve Template kütüphanesini desteklememektedir. Bu nedenle açık kaynak kodunu bu <a href="https://github.com/IdentityServer/IdentityServer4.Quickstart.UI">link</a> üzerinden indirip ekliyorum.</p><p>Daha sonra<strong> Program.cs</strong> içerisinde konfigürasyon işlemlerini gerçekleştiriyoruz.</p><pre>...<br>JwtSecurityTokenHandler.DefaultMapInboundClaims = false;<br><br>builder.Services.AddAuthentication(options =&gt;<br>{<br>    options.DefaultScheme = &quot;Cookies&quot;;<br>    options.DefaultChallengeScheme = &quot;oidc&quot;;<br>})<br>    .AddCookie(&quot;Cookies&quot;)<br>    .AddOpenIdConnect(&quot;oidc&quot;, options =&gt;<br>    {<br>        options.Authority = &quot;https://localhost:5001&quot;;<br><br>        options.ClientId = &quot;mvcClient&quot;;<br>        options.ClientSecret = &quot;secret&quot;;<br>        options.ResponseType = &quot;code&quot;;<br><br>        options.SaveTokens = true;<br>    });</pre><p>MVC projemizde kullanıcı login işlemi için cookie kullanacağız. “<strong>DefaultChallengeScheme</strong>” olarak “<strong>oidc</strong>” kullanıyoruz çünkü kullanıcı giriş yaparken OIDC protokolü kullanacağız.</p><p>Bunlarla birlikte <strong>AddAuthentication </strong>kısmında “<strong>Cookies</strong>” kullanıyoruz. Bu kısımda son olarak <strong>AddOpenIdConnect </strong>kullanıyoruz. Bunun içerisinde;</p><ul><li><strong>Authority </strong>: Identity server location</li><li><strong>ClientId </strong>: Identity server tarafında belirlenen client id bilgisi</li><li><strong>ClientSecret </strong>: ClientId ile gelen client için secret bilgisi</li><li><strong>ResponseType </strong>: Grant type</li><li><strong>SaveTokens </strong>: Token bilgisini daha sonra kullanılmak üzere cookie içerisinde tutma bilgisi</li></ul><p>Grant type konusuna daha sonra gelecek olsam da “code” kullanılmasının sebebi “Authorization Code” flow kullanılmasından dolayıdır. Genelde Web uygulamaları, SPA veya mobil uygulamalarda bu Grant Type sıklıkla kullanılır.</p><p>Daha sonra ise <strong>Program.cs</strong> içinde middleware eklemesi gerçekleştirilir.</p><pre>...<br>builder.Services.AddSession(options =&gt; {<br>    options.IdleTimeout = TimeSpan.FromMinutes(1);<br>});<br><br>...<br>app.UseSession();<br>app.UseHttpsRedirection();<br>app.UseStaticFiles();<br>app.UseRouting();<br>app.UseAuthentication();<br>app.UseAuthorization();</pre><p><strong>IdentityServer </strong>tarafında konfigürasyon işlemleri yapılır. Program.cs içerisinde IdentityServer register işlemi gerçekleştirilir. Burada aynı zamanda QuickStart ile gelen test kullanıcıları da eklenir.</p><pre>public static class Config<br>{<br>    public static IEnumerable&lt;Client&gt; Clients =&gt;<br>        new Client[]<br>        {<br>            new Client<br>            {<br>                ClientId = &quot;mvcClient&quot;,<br>                ClientSecrets = { new Secret(&quot;secret&quot;.Sha256()) },<br>                AllowedGrantTypes = GrantTypes.Code,<br>                // where to redirect to after login<br>                RedirectUris = { &quot;https://localhost:5002/signin-oidc&quot; },<br>                // where to redirect to after logout<br>                PostLogoutRedirectUris = { &quot;https://localhost:5002/signout-callback-oidc&quot; },<br>                AllowedScopes = new List&lt;string&gt;<br>                {<br>                   IdentityServerConstants.StandardScopes.OpenId,<br>                   IdentityServerConstants.StandardScopes.Profile<br>                }<br>            }<br>        };<br><br>    public static IEnumerable&lt;IdentityResource&gt; IdentityResources =&gt;<br>        new List&lt;IdentityResource&gt;<br>        {<br>            new IdentityResources.OpenId(),<br>            new IdentityResources.Profile(),<br>        };<br>}</pre><pre>...<br>builder.Services.AddIdentityServer()<br>                .AddDeveloperSigningCredential()<br>                .AddInMemoryIdentityResources(Config.IdentityResources)<br>                .AddInMemoryClients(Config.Clients)<br>                .AddTestUsers(TestUsers.Users);<br><br>...</pre><p>Bu işlemlerden sonra web uygulaması tarafında</p><pre>public class HomeController : Controller<br>{<br>    [Authorize]<br>    public IActionResult Index()<br>    {<br>       return View();<br>    }<br>}</pre><p>Index.cshtml ise şu şekildedir.</p><pre>@using Microsoft.AspNetCore.Authentication;<br><br>@{<br>    ViewData[&quot;Title&quot;] = &quot;Home Page&quot;;<br>}<br><br>&lt;div class=&quot;text-center&quot;&gt;<br>    &lt;h2&gt;Claims&lt;/h2&gt;<br><br>    &lt;div&gt;<br>        @foreach (var claim in User.Claims)<br>        {<br>            &lt;p&gt;@claim.Type&lt;/p&gt;<br>            &lt;p&gt;@claim.Value&lt;/p&gt;<br>            &lt;br /&gt;&lt;hr /&gt;&lt;br /&gt;<br>        }<br>    &lt;/div&gt;<br>    <br>    &lt;h2&gt;Properties&lt;/h2&gt;<br><br>    &lt;div&gt;<br>        @foreach (var property in (await Context?.AuthenticateAsync())?.Properties?.Items ?? new Dictionary&lt;string,string?&gt;())<br>        {<br>            &lt;p&gt;@property.Key&lt;/p&gt;<br>            &lt;p&gt;@property.Value&lt;/p&gt;<br>            &lt;br /&gt;&lt;hr /&gt;&lt;br /&gt;<br>        }<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Bu işlemden sonra programları ayağa kaldırdığımızda bizi IdentityServer tarafındaki Login sayfasına yönlendirecektir. Daha sonra ise buradan test kullanıcılarından biri ile giriş yaparız ve tekrar MVC projemize yönlendirme sağlanır.</p><p>Aynı şekilde sign out işlemi için hem kullanıcı tarafında cookie silme işlemi yapılır hem de IdentityServer tarafında merkezi oturum açma session bilgisi silinir. Controller içerisine aşağıdaki kod bloğu eklenir.</p><pre> [Authorize]<br> public IActionResult Logout()<br> {<br>    return SignOut(&quot;Cookies&quot;,&quot;oidc&quot;);<br> }</pre><p>Bu kod yapısı ile kullanıcı bazlı cookie temizlenir. Daha sonra Client belirtirken yazdığımız <strong>PostLogoutRedirectUris </strong>tarafına yönlendirme yapılarak IdentityServer tarafında session bilgisi silinir ve ardından MVC uygulamasına dönüş sağlanır.</p><p>Client ekleme işlemi yapılırken <strong>IdentityServerConstants.StandardScopes.OpenId</strong> ve <strong>IdentityServerConstants.StandardScopes.Profile</strong> scope olarak eklenmişti ancak dönen token içerisinde bu bilgiler yer almıyordu. Bunun için <strong>AddAuthentication </strong>kısmı değiştirilmelidir.</p><p>Eğer istersek test kullanıcılarına ekstra claim bilgisi de eklenerek bunlar token içerisine eklenebilir. Bu ekleme işleminden sonra tekrar <strong>AddOpenIdConnect </strong>içerisinde bunlar belirtilmelidir.<br>İlk olarak kullanıcı claim bilgileri içerisine ekleme yapılır. Biz “<strong>role</strong>” için bunu yapalım.</p><pre>new Claim(&quot;role&quot;, &quot;admin&quot;)</pre><pre> public static IEnumerable&lt;Client&gt; Clients =&gt;<br>    new Client[]<br>    {<br>        new Client<br>        {<br>            ClientId = &quot;mvcClient&quot;,<br>            ClientSecrets = { new Secret(&quot;secret&quot;.Sha256()) },<br>            AllowedGrantTypes = GrantTypes.Code,<br><br>            // where to redirect to after login<br>            RedirectUris = { &quot;https://localhost:5002/signin-oidc&quot; },<br><br>            // where to redirect to after logout<br>            PostLogoutRedirectUris = { &quot;https://localhost:5002/signout-callback-oidc&quot; },<br><br>            AllowedScopes = new List&lt;string&gt;<br>            {<br>                IdentityServerConstants.StandardScopes.OpenId,<br>                IdentityServerConstants.StandardScopes.Profile,<br>                &quot;Roles&quot;<br>            }<br>        }<br>    };<br><br>    public static IEnumerable&lt;IdentityResource&gt; IdentityResources =&gt;<br>     new List&lt;IdentityResource&gt;<br>     {<br>        new IdentityResources.OpenId(),<br>        new IdentityResources.Profile(),<br>        new IdentityResource {<br>            Name = &quot;Roles&quot;,<br>            DisplayName = &quot;Roles&quot;,<br>            Description = &quot;Kullanıcı rolleri&quot;,<br>            UserClaims = { &quot;role&quot; }<br>        }<br>     };</pre><pre>builder.Services.AddAuthentication(options =&gt;<br>{<br>    options.DefaultScheme = &quot;Cookies&quot;;<br>    options.DefaultChallengeScheme = &quot;oidc&quot;;<br>})<br>    .AddCookie(&quot;Cookies&quot;)<br>    .AddOpenIdConnect(&quot;oidc&quot;, options =&gt;<br>    {<br>        options.Authority = &quot;https://localhost:5001&quot;;<br><br>        options.ClientId = &quot;mvcClient&quot;;<br>        options.ClientSecret = &quot;secret&quot;;<br>        options.ResponseType = &quot;code&quot;;<br>        options.Scope.Add(&quot;profile&quot;);<br>        options.Scope.Add(&quot;Roles&quot;);<br>        options.GetClaimsFromUserInfoEndpoint = true;<br>        options.SaveTokens = true;<br>    });</pre><p>bu işlemlerden sonra programlar çalıştırılıp giriş yapıldığında “<strong>role</strong>” bilgisinin de ekrana geldiğini göreceğiz.</p><p>Eğer Client içerisine RefreshToken bilgisi de eklenmek istenirse Client içerisine <strong>AllowOfflineAccess = true</strong> bilgisi eklenir.</p><p>Client son hali şu şekilde olacaktır.</p><pre>new Client<br>{<br>    ClientId = &quot;mvcClient&quot;,<br>    ClientSecrets = { new Secret(&quot;secret&quot;.Sha256()) },<br>    AllowedGrantTypes = GrantTypes.Code,<br><br>    // where to redirect to after login<br>    RedirectUris = { &quot;https://localhost:5002/signin-oidc&quot; },<br><br>    // where to redirect to after logout<br>    PostLogoutRedirectUris = { &quot;https://localhost:5002/signout-callback-oidc&quot; },<br>    AllowOfflineAccess = true,<br>    AllowedScopes = new List&lt;string&gt;<br>    {<br>       IdentityServerConstants.StandardScopes.OpenId,<br>       IdentityServerConstants.StandardScopes.Profile,<br>       &quot;Roles&quot;<br>    }<br>}</pre><p>refresh token bilgisini ayrıca kullanıcı tarafındaki scope bilgileri içerisine eklemek istersek bunu AddOpenIdConnect içerisinde de belirtmeliyiz. Daha önceden de bahsedilen <strong>SaveToken </strong>bilgisi de burada <strong>True</strong> yapılarak gelen access ve refresh token bilgileri session içerisinde saklanır.</p><pre>.AddOpenIdConnect(&quot;oidc&quot;, options =&gt;<br>{<br>    options.Authority = &quot;https://localhost:5001&quot;;<br><br>    options.ClientId = &quot;mvcClient&quot;;<br>    options.ClientSecret = &quot;secret&quot;;<br>    options.ResponseType = &quot;code&quot;;<br><br>    options.GetClaimsFromUserInfoEndpoint = true;<br>    options.SaveTokens = true;<br>    options.Scope.Add(&quot;profile&quot;);<br>    options.Scope.Add(&quot;Roles&quot;);<br>    options.Scope.Add(&quot;offline_access&quot;);<br>    options.ClaimActions.MapUniqueJsonKey(&quot;role&quot;, &quot;role&quot;);<br>    options.TokenValidationParameters = new TokenValidationParameters<br>    {<br>        RoleClaimType = &quot;role&quot;<br>    };<br>});</pre><p>Eğer elde ettiğimiz access token bilgisini kullanmak istersek;</p><pre>[Authorize]<br>public async Task&lt;IActionResult&gt; Index()<br>{<br>    var accessToken = await HttpContext.GetTokenAsync(&quot;access_token&quot;);<br>    ViewBag.AccessToken = accessToken;<br>    return View();<br>}</pre><p><a href="https://github.com/serhatayata/IdentityServer4-Projects/tree/master/IdentityServer_2">Mevcut projenin GitHub linki</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e438e0d1420c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IdentityServer4 — Part1 / ASP.NET Core API]]></title>
            <link>https://medium.com/@srhtayata/identityserver4-part1-fd0e3e33b361?source=rss-b857298ce5cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd0e3e33b361</guid>
            <category><![CDATA[openid-connect]]></category>
            <category><![CDATA[identity-server]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[identityserver4]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Serhat Ayata]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 10:30:49 GMT</pubDate>
            <atom:updated>2023-04-21T11:36:52.234Z</atom:updated>
            <content:encoded><![CDATA[<p>IdentityServer4 OpenID Connect (OIDC) ve OAuth2.0 standartlarını uygulayan bir kimlik doğrulama (Authentication) sunucusudur. Gelen isteklerin kimlik doğrulama işlemlerini yapmak üzere tasarlanmıştır. Bu istekler mobil, web, api vs. gibi birçok uygulama üzerinden gerçekleşebilir.</p><p>OAuth2.0 kullanarak hesabın belirli bir kısmına erişim için yetki alınabilir veya bunu hesabın tümü içinde yapabiliriz. Bunlara örnek olarak Facebook, Twitter, Yahoo ve birçok örnek verilebilir.</p><p>Bu seride IdentityServer4 üzerine bir proje gerçekleştireceğim.</p><p>İlk olarak <strong>ASP.NET Core Web API</strong> projesi oluşturuyoruz. Oluşturulan projede applicationUrl olarak <strong>https://localhost:5001</strong> tanımladım.</p><p>Daha sonra<strong> </strong>aşağıdaki kütüphaneleri ekliyoruz. Ben .NET 7 üzerinde geliştirme yapıyorum ve Template kütüphanesini desteklememektedir. Bu nedenle açık kaynak kodunu bu <a href="https://github.com/IdentityServer/IdentityServer4.Quickstart.UI">link</a> üzerinden indirip ekliyorum.</p><ul><li><strong>IdentityServer4.AspNetIdentity</strong></li><li><strong>IdentityServer4.Template</strong></li></ul><h4><strong>API SCOPE</strong></h4><p>ApiScopes kavramı, Identity Server tarafından korunacak olan API noktaları için tanımladığımız kapsamlardır. Bunu kullanıcı bazlı rollendirmeye benzetebiliriz. Proje içerisinde bir Config.cs sınıfı oluşturduktan sonra içerisinde bunları belirtiriz.</p><pre>public static class Config<br>{<br>   public static IEnumerable&lt;ApiScope&gt; ApiScopes =&gt;<br>      new ApiScope[]<br>      {<br>          new ApiScope(&quot;catalog_readpermission&quot;,&quot;Read access to Catalog API&quot;),<br>          new ApiScope(&quot;catalog_writepermission&quot;,&quot;Write access to Catalog API&quot;),<br>          new ApiScope(&quot;order_readpermission&quot;,&quot;Read Access to Order API&quot;),<br>          new ApiScope(&quot;order_writepermission&quot;,&quot;Write Access to Order API&quot;)<br>      };<br>}</pre><h4>CLIENT</h4><p>Identity Server tarafından korunan API noktalarına erişim sağlamak için kullandığımız uygulamalardır. Aşağıda da tanımlanacak olan client secret ile Identity Server üzerinde kimlik doğrulaması sağlanır.</p><pre> public static IEnumerable&lt;Client&gt; Clients =&gt;<br>    new Client[]<br>    {<br>      new Client<br>      {<br>        ClientName=&quot;ClientFirst&quot;,<br>        ClientId=&quot;clientFirst&quot;,<br>        ClientSecrets= {new Secret(&quot;clientfirstsecret&quot;.Sha256())},<br>        AllowedGrantTypes= GrantTypes.ClientCredentials,<br>        AllowedScopes={ &quot;catalog_readpermission&quot;, &quot;catalog_writepermission&quot; }<br>      },<br>      new Client<br>      {<br>        ClientName=&quot;ClientSecond&quot;,<br>        ClientId=&quot;clientFirst&quot;,<br>        ClientSecrets= { new Secret(&quot;clientsecondsecret&quot;.Sha256()) },<br>        AllowedGrantTypes= GrantTypes.ClientCredentials,<br>        AllowedScopes={ &quot;order_readpermission&quot;, &quot;order_writepermission&quot; }<br>      }<br>    };</pre><ul><li>ClientId ve ClientSecret kısmını kullanıcı adı ve şifre gibi düşünebiliriz.</li><li>ClientName identity server üzerinde kendi tanımladığımız bir isimdir.</li><li><strong>AllowGrantTypes</strong> kısmı ise hangi türde bir kimlik doğrulama işlemi yapacağımızı belirlediğimiz kısımdır. Burayı daha detaylı ileride uygulayacak olsamda kısaca <strong>ClientCredentials </strong>için <strong>M2M </strong>(machine to machine) kimlik doğrulama diyebiliriz. Yani bir kullanıcıya yetki vermekten ziyade uygulamaya yetki tanımlıyoruz denebilir.</li><li><strong>AllowedScopes</strong> ise <strong>ApiScopes </strong>içerisinden hangilerini bu Client için kullanacağımızı belirttiğimiz kısımdır. Mesela “<strong>catalog_readpermission</strong>” kapsamına sahip olan bir Client “<strong>order_readpermission</strong>” kapsamına sahip olunması gereken bir API noktasına erişim sağlayamaz çünkü IdentityServer onu bu kapsamda tutmamaktadır.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOHE7abI1JpxcGUCiDtuLw.png" /></figure><p>Daha sonra ise IdentityServer konfigürasyonu sağlanır. Geçici olarak InMemory kullanacağız ancak daha sonra bunu düzenleyeceğim.</p><p>Program.cs içerisine aşağıdaki yapılar eklenir.</p><pre>...<br>builder.Services.AddIdentityServer()<br>                .AddDeveloperSigningCredential()   //This is for dev only scenarios when you don’t have a certificate to use.<br>                .AddInMemoryApiScopes(Config.ApiScopes)<br>                .AddInMemoryClients(Config.Clients);<br><br>...<br>app.UseIdentityServer();</pre><p>Yukarıda da görüldüğü üzere “AddDeveloperSigningCredential” kullandığımız için projeyi kontrol ettiğimizde “tempkey.jwk” isminde bir dosyanın oluşturulduğu görülecektir.</p><p>Yukarıda IdentityServer ve konfigürasyon ayarlarını gerçekleştirdik. Şimdi ise belirtilen API yapılarından birini oluşturarak devam edelim.</p><p>Catalog.API adında bir <strong>ASP.NET Core Web API </strong>projesi oluşturarak başlayabiliriz. Oluşturulan projede applicationUrl olarak <strong>https://localhost:5002</strong> tanımladım.</p><p>Daha sonra <strong>Microsoft.AspNetCore.Authentication.JwtBearer</strong> paketini yüklüyoruz.</p><p>CatalogController oluşturup içerisine bir metot ekliyoruz.</p><pre>[Route(&quot;api/[controller]&quot;)]<br>[ApiController]<br>[Authorize]<br>public class CatalogController : ControllerBase<br>{<br>    [HttpGet]<br>    public IActionResult Get()<br>    {<br>        return new JsonResult(from c in User.Claims select new { c.Type, c.Value });<br>    }<br>}</pre><p>API için son olarak konfigürasyon ayarlarını yapacağız ve sonrasında ise Client tarafına geçeceğiz.</p><pre>...<br>// adds the authentication services to DI - as default &quot;Bearer&quot;<br>builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)<br>    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =&gt;<br>    {<br>        options.Authority = &quot;https://localhost:5001&quot;; // IdentityServer<br>        options.TokenValidationParameters = new TokenValidationParameters<br>        {<br>            ValidateAudience = false<br>        };<br>    });<br><br>...<br>app.UseRouting();<br>app.UseAuthentication();<br>app.UseAuthorization();</pre><p>Bu işlemlerden sonra ise Client tarafına geçebiliriz.</p><p>Client uygulamasını bir Console uygulaması üzerinden ilerletebiliriz.</p><p>Uygulama oluşturulduktan sonra <strong>IdentityModel </strong>kütüphanesini ekliyoruz.</p><p>IdentityServer tarafında OAuth 2.0 protokolü uygulanmakta ve buna ulaşmak için HTTP istekleri de kullanılabilir. Ancak protokol etkileşimini daha kolay şekilde sağlamamız için geliştirilen <strong>IdentityModel</strong>’i kullanacağız.</p><p>Aşağıdaki şekilde Console uygulamasını oluşturup tüm projeleri çalıştırırsak;</p><pre>var client = new HttpClient();<br>var disco = await client.GetDiscoveryDocumentAsync(&quot;https://localhost:5001&quot;);<br>var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest<br>{<br>    Address = disco.TokenEndpoint,<br>    ClientId = &quot;clientFirst&quot;,<br>    ClientSecret = &quot;clientfirstsecret&quot;,<br>    Scope = &quot;catalog_writepermission catalog_readpermission&quot;<br>});<br><br>Console.WriteLine(tokenResponse.Json);<br>Console.ReadKey();</pre><p>yukarıda görüldüğü üzere IdentityServer tarafında eklediğimiz ClientFirst ismindeki client tarafından yapılan istek sonucunda kimlik doğrulama işlemi tamamlannış olup identity server tarafından bir token etmiş oluruz.</p><p>Scope içerisinde “<strong>catalog_writepermission catalog_readpermission</strong>” şeklinde belirttik ancak eğer daha fazla kapsam varsa burada bu Client kendisine ait olabilecek tüm kapsamları da aralarına boşluk bırakarak talep edebilir. İstemediği kapsamları ise buraya dahil etmeyebilir.</p><p>Token çıktısı şu şekilde olacaktır.</p><pre>{<br>  &quot;nbf&quot;: 1681984733,<br>  &quot;exp&quot;: 1681988333,<br>  &quot;iss&quot;: &quot;https://localhost:5001&quot;,<br>  &quot;client_id&quot;: &quot;clientFirst&quot;,<br>  &quot;jti&quot;: &quot;3A4A902972CBCB9148184D49331BEEFB&quot;,<br>  &quot;iat&quot;: 1681984733,<br>  &quot;scope&quot;: [<br>    &quot;catalog_readpermission&quot;,<br>    &quot;catalog_writepermission&quot;<br>  ]<br>}</pre><p>Görüldüğü üzere scope içerisinde belirttiğimiz kapsamlar token içerisinde gelmiştir.</p><p>Şimdi bu elde ettiğimiz Token ile CatalogAPI tarafına istekte bulunalım ve sonucu görelim.</p><pre>var client = new HttpClient();<br>var disco = await client.GetDiscoveryDocumentAsync(&quot;https://localhost:5001&quot;);<br><br>var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest<br>{<br>    Address = disco.TokenEndpoint,<br><br>    ClientId = &quot;clientSecond&quot;,<br>    ClientSecret = &quot;clientsecondsecret&quot;,<br>    Scope = &quot;order_writepermission&quot;<br>});<br><br>client.SetBearerToken(tokenResponse.AccessToken);<br><br>var response = await client.GetAsync(&quot;https://localhost:5002/api/catalog/get&quot;);<br>if (!response.IsSuccessStatusCode)<br>{<br>    Console.WriteLine(response.StatusCode);<br>}<br>else<br>{<br>    var content = await response.Content.ReadAsStringAsync();<br>    Console.WriteLine(JArray.Parse(content));<br>}<br><br>Console.WriteLine(tokenResponse.Json);<br>Console.ReadKey();</pre><p>Yukarıda da görüldüğü üzere Scope olarak sadece “<strong>catalog_writepermission</strong>” kullanıldı. Bununla birlikte CatalogAPI tarafından dönen response ise şu şekilde olacaktır.</p><pre>[<br>  {<br>    &quot;type&quot;: &quot;nbf&quot;,<br>    &quot;value&quot;: &quot;1681985417&quot;<br>  },<br>  {<br>    &quot;type&quot;: &quot;exp&quot;,<br>    &quot;value&quot;: &quot;1681989017&quot;<br>  },<br>  {<br>    &quot;type&quot;: &quot;iss&quot;,<br>    &quot;value&quot;: &quot;https://localhost:5001&quot;<br>  },<br>  {<br>    &quot;type&quot;: &quot;client_id&quot;,<br>    &quot;value&quot;: &quot;clientSecond&quot;<br>  },<br>  {<br>    &quot;type&quot;: &quot;jti&quot;,<br>    &quot;value&quot;: &quot;E6AF1D863ABFD0589C186F9785BA41B4&quot;<br>  },<br>  {<br>    &quot;type&quot;: &quot;iat&quot;,<br>    &quot;value&quot;: &quot;1681985416&quot;<br>  },<br>  {<br>    &quot;type&quot;: &quot;scope&quot;,<br>    &quot;value&quot;: &quot;order_writepermission&quot;<br>  }<br>]</pre><blockquote>Default olarak access token içerisinde Scope, Lifetime, ClientId ve IssuerName bilgisi yer alacaktır.</blockquote><p>Yukarıdaki şekilde eğer token olmadan bir istekte bulunursak 401 Not Authenticated hatası alacağız. Aslında API uygulamamız burada bir yetkilendirme kontrolü yapmadı, sadece kimlik kontrolü sağladı. Bunun için API uygulamamıza bazı yapılar ekleyeceğiz.</p><p>Eğer Controller veya Action bazlı bir yetkilendirme işlemi uygulayacaksak;</p><pre>builder.Services.AddAuthorization(options =&gt;<br>{<br>    options.AddPolicy(&quot;CatalogRead&quot;, policy =&gt;<br>    {<br>        policy.RequireAuthenticatedUser();<br>        policy.RequireClaim(&quot;catalog_readpermission&quot;);<br>    });<br><br>    options.AddPolicy(&quot;CatalogWrite&quot;, policy =&gt;<br>    {<br>        policy.RequireAuthenticatedUser();<br>        policy.RequireClaim(&quot;catalog_writepermission&quot;);<br>    });<br><br>    options.AddPolicy(&quot;CatalogFull&quot;, policy =&gt;<br>    {<br>        policy.RequireAuthenticatedUser();<br>        policy.RequireClaim(&quot;catalog_writepermission&quot;, &quot;catalog_readpermission&quot;);<br>    });<br>});</pre><p>Yukarıdaki yapıda 3 tip yetkilendirme yaptık. Eğer;</p><ul><li>catalog_readpermission kapsamına sahipse okuma yetkisi</li><li>catalog_writepermission kapsamına sahipse yazma yetkisi</li><li>Her ikisine de sahipse tam yetkili</li></ul><p>olarak ayırdık.</p><p>Bununla birlikte tüm uygulamada bulunan Controller sınıfları için yetkilendirmesi yapmak istersek yukarıda oluşturduğumuz gibi Policy oluşturup aşağıdaki gibi belirtiyoruz.</p><pre>app.UseEndpoints(endpoints =&gt;<br>{<br>    endpoints.MapControllers()<br>        .RequireAuthorization(&quot;CatalogRead&quot;);<br>});</pre><p>Daha sonraki aşamada bunu Controller veya Action üzerinde göstermek istersek aşağıdaki şekilde ilerleyebiliriz.</p><pre>[Route(&quot;api/[controller]&quot;)]<br>[ApiController]<br>public class CatalogController : ControllerBase<br>{<br>    [HttpGet]<br>    [Authorize(JwtBearerDefaults.AuthenticationScheme, Policy = &quot;CatalogRead&quot;)]<br>    public IActionResult Get()<br>    {<br>        return new JsonResult(from c in User.Claims select new { c.Type, c.Value });<br>    }<br>}</pre><pre>var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest<br>{<br>    Address = disco.TokenEndpoint,<br><br>    ClientId = &quot;clientFirst&quot;,<br>    ClientSecret = &quot;clientfirstsecret&quot;,<br>    Scope = &quot;catalog_writepermission&quot;<br>});</pre><p>token response bu şekilde olursa ve yukarıda yaptığımız gibi CatalogAPI tarafına bir istekte bulunursak <strong>403 Unauthorized</strong> hatası alırız. Bunun sebebi ise yukarıda <strong>CatalogRead </strong>policy yetkisi gerektiği ancak bizim CatalogWrite yetkisi ile buraya ulaşmaya çalışmamız. Yukarıdaki Scope içerisinde Scope içerisini <strong>catalog_readpermissin</strong> ile değişirsek ulaşım gerçekleştirmiş oluruz.</p><p>Aynı zamanda burada iki scope birlikte yazılsa da aynı şekilde ulaşım sağlamış oluruz.</p><p><a href="https://github.com/serhatayata/IdentityServer4-Projects/tree/master/IdentityServer_1">Mevcut projenin GitHub linki</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd0e3e33b361" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>