<?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 Erdem Kaya on Medium]]></title>
        <description><![CDATA[Stories by Erdem Kaya on Medium]]></description>
        <link>https://medium.com/@erdemkayatr?source=rss-375f2d327254------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lq63JhOMEgOBIEDvEsKkeQ.jpeg</url>
            <title>Stories by Erdem Kaya on Medium</title>
            <link>https://medium.com/@erdemkayatr?source=rss-375f2d327254------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 08:46:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erdemkayatr/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[CIBA Authentication with Duende IdentityServer]]></title>
            <link>https://medium.com/@erdemkayatr/ciba-authentication-with-duende-identity-server-5ea61ad79aef?source=rss-375f2d327254------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ea61ad79aef</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[openid-connect]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[identity-server]]></category>
            <dc:creator><![CDATA[Erdem Kaya]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 13:08:22 GMT</pubDate>
            <atom:updated>2024-11-01T09:33:46.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*gCQ-w4DUCtSVhKk2.jpeg" /></figure><p>CIBA (Client Initiated Backchannel Authentication) is an authentication method used within OAuth 2.0 and OpenID Connect (OIDC) frameworks. This method provides a more secure and convenient way to perform authentication in scenarios requiring user interaction.</p><p>CIBA is commonly used in high-security sectors such as banking, financial services, and healthcare. It aims to improve the user experience while enhancing security.</p><h3>Key Features and Use Cases of CIBA</h3><ol><li><strong>Non-User Initiated Requests:</strong> CIBA is effective when a user has not actively initiated a login, but an authentication request is necessary. For example, it can verify a user’s identity to approve a financial transaction.</li><li><strong>Limited User Interaction:</strong> It is used in scenarios where user interaction for authentication is minimal or non-existent. For example, it may be used in IoT devices or smart home systems requiring authentication.</li><li><strong>Security Requirements:</strong> It is used in applications requiring high security. CIBA is based on directly sending authentication requests to the user, who authenticates using a secure device. This minimizes security vulnerabilities.</li></ol><h3>How CIBA Works:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*U4i30V3-nbHLLByyQG_HMw.png" /></figure><p>Image from Duende’s page.</p><p><strong><em>Step 1.</em></strong></p><p>IdentityServer provides an endpoint for clients to initiate the CIBA workflow through a backchannel authentication request.</p><p><strong><em>Step 2.</em></strong></p><p>After client authentication and basic request parameter validation, the user who the request is for must be identified. This is done using the IBackchannelAuthenticationUserValidator service within Dependency Injection (DI). You need to implement this service and register it with the DI system. The ValidateRequestAsync method validates request parameters and returns a result containing the sub (subject identifier) claim for the user.</p><p><strong><em>Step 3.</em></strong></p><p>Once a user is successfully identified, a record representing the pending login request is created in the Backchannel Authentication Request Store.</p><p><strong><em>Step 4.</em></strong></p><p>Then, the login request should be communicated to the user. This is done using the IBackchannelAuthenticationUserNotificationService service within DI. Implement this service and register it with DI. The SendLoginRequestAsync method should communicate with the user via any suitable mechanism (e.g., email, SMS, push notification, etc.) and possibly provide instructions for the user to initiate the login and consent process (maybe through a link, but other approaches can also be considered). This method is provided with a BackchannelUserLoginRequest containing all contextual information to send to the user for this login request (including the InternalId necessary for completing the request).</p><p><strong><em>Step 5.</em></strong></p><p>The login request information should then be presented to the user (e.g., via a web page on IdentityServer or any other appropriate method). A BackchannelUserLoginRequest can be accessed via InternalId using the IBackchannelAuthenticationInteractionService. After the user consents and allows the login, the result (including which scopes the user agreed to) should be recorded using the CompleteLoginRequestAsync method.</p><p><strong><em>Step 6.</em></strong></p><p>Finally, after polling to receive the result, the client will be issued the requested tokens (or an appropriate error if the user has denied the request or it has timed out).</p><p>Now, let’s create a simple CIBA example project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*rMQ87MTdL94Mc3DOfKiV1g.png" /></figure><p>As shown in the image, we created our .Net 8 project. Let’s add the following packages to our project:</p><pre>&lt;PackageReference Include=&quot;Duende.IdentityServer&quot; Version=&quot;7.0.6&quot; /&gt;  <br>&lt;PackageReference Include=&quot;Swashbuckle.AspNetCore.SwaggerGen&quot; Version=&quot;6.7.2&quot; /&gt;  <br>&lt;PackageReference Include=&quot;Microsoft.AspNetCore.OpenApi&quot; Version=&quot;8.0.8&quot; /&gt;  <br>&lt;PackageReference Include=&quot;Swashbuckle.AspNetCore.SwaggerUI&quot; Version=&quot;6.7.2&quot; /&gt;</pre><p>Let’s now create an interface named “ICibaRequestStore.cs” and a class named “CibaRequestStore.cs” inheriting from this interface under a folder named “Stores” to complete our pending CIBA requests. (I tried to explain the code lines with comments.)</p><pre>namespace CibaExample.Api.Stores;  <br>  <br>public interface ICibaRequestStore  <br>{  <br>    Task CompleteCibaRequestAsync(string id); // Completes the pending Ciba request  <br>}</pre><p>We’ll need to dive a bit more into the CibaRequestStore.cs class:</p><pre>using Duende.IdentityServer.Models;  <br>using Duende.IdentityServer.Services;  <br>using Duende.IdentityServer.Stores;  <br>using Duende.IdentityServer.Stores.Serialization;  <br>using System.Security.Claims;  <br>  <br>namespace CibaExample.Api.Stores;  <br>  <br>public class CibaRequestStore : DefaultGrantStore&lt;BackChannelAuthenticationRequest&gt;, ICibaRequestStore  <br>{  <br>  <br>    private IBackchannelAuthenticationInteractionService _cibaInteractionService;  <br>    public CibaRequestStore(string grantType, IPersistedGrantStore store, IPersistentGrantSerializer serializer, IHandleGenerationService handleGenerationService, ILogger logger, IBackchannelAuthenticationInteractionService cibaInteractionService) : base(grantType, store, serializer, handleGenerationService, logger)  <br>    {  <br>        _cibaInteractionService = cibaInteractionService;  <br>    }  <br>  <br>    public async Task CompleteCibaRequestAsync(string id)  <br>    {  <br>       var persisted = await Store.GetAsync(id);  <br>       if (persisted == null)  <br>       {  <br>           throw new NullReferenceException(&quot;Grant not found&quot;);  <br>       }  <br>       var backChannelAuthenticationRequestData = Serializer.Deserialize&lt;BackChannelAuthenticationRequest&gt;(persisted.Data);  <br>        var completeRequest = new CompleteBackchannelLoginRequest(id)  <br>       {  <br>           InternalId = id,  <br>           Subject = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]  <br>           {  <br>               new Claim(&quot;sub&quot;, persisted.SubjectId) // The subject identifying the user (e.g., user_id)  <br>           })),  <br>           ScopesValuesConsented = backChannelAuthenticationRequestData.RequestedScopes  <br>        };  <br>  <br>       await _cibaInteractionService.CompleteLoginRequestAsync(completeRequest);  <br>          <br>         <br>    }  <br>    <br>}</pre><ul><li><strong>Constructor Parameters:</strong></li></ul><p><strong>grantType:</strong> Specifies the type of grant to be issued.</p><p><strong>store (<em>IPersistedGrantStore</em>):</strong> The interface used to manage persisted grants used in authentication processes. These persisted grants include long-term permissions, access tokens, refresh tokens, and other grant types used in OAuth 2.0 or OpenID Connect protocols. Main functions include:</p><ol><li>Token Storage</li><li>Token Update</li><li>Token Deletion</li><li>Token Retrieval</li></ol><p><strong>serializer:</strong> Used for data serialization and deserialization.</p><p><strong>handleGenerationService:</strong> Service used to create a unique identifier (handle).</p><p><strong>logger:</strong> Used for logging operations (ILogger interface).</p><p><strong>cibaInteractionService (<em>IBackchannelAuthenticationInteractionService</em>):</strong> Service used to manage CIBA interactions.</p><ul><li><strong>CompleteCibaRequestAsync Method:</strong></li></ul><p>Our custom method is written to complete the pending CIBA request.</p><p>Now, let’s implement the “<em>BackchannelAuthenticationUserValidator</em>” class implementing the “<em>IBackchannelAuthenticationUserValidator</em>” interface for our user validation processes and a “<em>TestUser</em>” class containing the users we’ll use as examples in these processes.</p><pre>using Duende.IdentityServer.Test;  <br>using Duende.IdentityServer;  <br>using IdentityModel;  <br>using System.Security.Claims;  <br>using System.Text.Json;  <br>  <br>namespace CibaExample.Api;  <br>  <br>public static class TestUsers  <br>{  <br>    public static List&lt;TestUser&gt; Users  <br>    {  <br>        get  <br>        {  <br>            var address = new  <br>            {  <br>                street_address = &quot;One Hacker Way&quot;,  <br>                locality = &quot;Heidelberg&quot;,  <br>                postal_code = &quot;69118&quot;,  <br>                country = &quot;Germany&quot;  <br>            };  <br>  <br>            return new List&lt;TestUser&gt;  <br>            {  <br>                new TestUser  <br>                {  <br>                    SubjectId = &quot;1&quot;,  <br>                    Username = &quot;alice&quot;,  <br>                    Password = &quot;alice&quot;,  <br>                    Claims =  <br>                    {  <br>                        new Claim(JwtClaimTypes.Name, &quot;Alice Smith&quot;),  <br>                        new Claim(JwtClaimTypes.GivenName, &quot;Alice&quot;),  <br>                        new Claim(JwtClaimTypes.FamilyName, &quot;Smith&quot;),  <br>                        new Claim(JwtClaimTypes.Email, &quot;AliceSmith@email.com&quot;),  <br>                        new Claim(JwtClaimTypes.EmailVerified, &quot;true&quot;, ClaimValueTypes.Boolean),  <br>                        new Claim(JwtClaimTypes.WebSite, &quot;http://alice.com&quot;),  <br>                        new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)  <br>                    }  <br>                },  <br>                new TestUser  <br>                {  <br>                    SubjectId = &quot;2&quot;,  <br>                    Username = &quot;bob&quot;,  <br>                    Password = &quot;bob&quot;,  <br>                    Claims =  <br>                    {  <br>                        new Claim(JwtClaimTypes.Name, &quot;Bob Smith&quot;),  <br>                        new Claim(JwtClaimTypes.GivenName, &quot;Bob&quot;),  <br>                        new Claim(JwtClaimTypes.FamilyName, &quot;Smith&quot;),  <br>                        new Claim(JwtClaimTypes.Email, &quot;BobSmith@email.com&quot;),  <br>                        new Claim(JwtClaimTypes.EmailVerified, &quot;true&quot;, ClaimValueTypes.Boolean),  <br>                        new Claim(JwtClaimTypes.WebSite, &quot;http</pre><pre>://bob.com&quot;),  <br>                        new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)  <br>                    }  <br>                }  <br>            };  <br>        }  <br>    }  <br>}</pre><pre>using System.Security.Claims;  <br>using Duende.IdentityServer.Validation;  <br>using IdentityModel;  </pre><pre>namespace CibaExample.Api.Validators;  </pre><pre>public class   <br>using System.Security.Claims;  <br>using Duende.IdentityServer.Validation;  <br>using IdentityModel;  </pre><pre>namespace CibaExample.Api.Validators;  </pre><pre>public class BackchannelAuthenticationUserValidator : IBackchannelAuthenticationUserValidator  <br>{  </pre><pre>  public Task&lt;BackchannelAuthenticationUserValidationResult&gt; ValidateRequestAsync(BackchannelAuthenticationUserValidatorContext userValidatorContext)  <br>  {  </pre><pre>      var user = TestUsers.Users.FirstOrDefault(u =&gt; u.Username == userValidatorContext?.LoginHint);  </pre><pre>      return Task.FromResult(new BackchannelAuthenticationUserValidationResult  <br>      {  <br>          Subject = new ClaimsPrincipal(new ClaimsIdentity(new List&lt;Claim&gt;  <br>          {  <br>              new Claim(&quot;sub&quot;, user?.SubjectId),  <br>              new Claim(JwtClaimTypes.AuthenticationTime, DateTime.UtcNow.ToEpochTime().ToString()), // auth_time claim  <br>              new Claim(JwtClaimTypes.IdentityProvider, &quot;local&quot;),  <br>          })),  <br>      });  <br>  }  <br>} : IBackchannelAuthenticationUserValidator  <br>{  </pre><pre>  public Task&lt;BackchannelAuthenticationUserValidationResult&gt; ValidateRequestAsync(BackchannelAuthenticationUserValidatorContext userValidatorContext)  <br>  {  </pre><pre>      var user = TestUsers.Users.FirstOrDefault(u =&gt; u.Username == userValidatorContext?.LoginHint);  </pre><pre>      return Task.FromResult(new BackchannelAuthenticationUserValidationResult  <br>      {  <br>          Subject = new ClaimsPrincipal(new ClaimsIdentity(new List&lt;Claim&gt;  <br>          {  <br>              new Claim(&quot;sub&quot;, user?.SubjectId),  <br>              new Claim(JwtClaimTypes.AuthenticationTime, DateTime.UtcNow.ToEpochTime().ToString()), // auth_time claim  <br>              new Claim(JwtClaimTypes.IdentityProvider, &quot;local&quot;),  <br>          })),  <br>      });  <br>  }  <br>}</pre><p>Now let’s add the class to send a verification request via PushNotification, SMS, or Email when we create a CIBA request. Here, we’ll print the “ID” value to the console for verification.</p><pre>using Duende.IdentityServer.Models;  <br>using Duende.IdentityServer.Services;  <br>  <br>namespace CibaExample.Api.Services;  <br>  <br>public class BackchannelAuthenticationUserNotificationService : IBackchannelAuthenticationUserNotificationService  <br>{  <br>    public Task SendLoginRequestAsync(BackchannelUserLoginRequest request)  <br>    {  <br>        Console.WriteLine($&quot;**Sending login request to user with request ID {request.InternalId}&quot;);  <br>        return Task.CompletedTask;  <br>    }  <br>}</pre><p>Let’s add the endpoint to verify our pending CIBA request using the “ID” value printed to the console.</p><pre>using CibaExample.Api.Stores;  <br>using Microsoft.AspNetCore.Mvc;  <br>namespace CibaExample.Api.Apis;  <br>  <br>public static class AuthMinimalApi  <br>{  <br>  <br>    public static void UseCibaEndPoints(this IEndpointRouteBuilder routes)  <br>    {  <br>        var group = routes.MapGroup(&quot;ciba&quot;);  <br>  <br>        group.MapPost(&quot;verify-notification&quot;,VerifyAsync).WithName(&quot;verify&quot;).WithOpenApi();  <br>    }  <br>  <br>    private static async Task&lt;IResult&gt; VerifyAsync([FromServices] ICibaRequestStore store,string id)  <br>    {  <br>  <br>       await store.CompleteCibaRequestAsync(id);  <br>  <br>       return Results.Ok(true);  <br>    }  <br>}</pre><p>Finally, let’s configure IdentityServer and define our “<em>Ciba Client</em>” in the “<em>Program.cs</em>” class.</p><pre>using CibaExample.Api;  <br>using CibaExample.Api.Apis;  <br>using CibaExample.Api.Services;  <br>using CibaExample.Api.Stores;  <br>using CibaExample.Api.Validators;  <br>using Duende.IdentityServer.Models;  <br>using Duende.IdentityServer.Services;  <br>using Duende.IdentityServer.Stores;  <br>using Duende.IdentityServer.Stores.Serialization;  <br>using IdentityModel;  <br>  <br>var builder = WebApplication.CreateBuilder(args);  <br>  <br>  <br>  <br>builder.Services.AddIdentityServer(opt =&gt;  <br>    {  <br>        opt.Events.RaiseErrorEvents = true;  <br>        opt.Events.RaiseSuccessEvents = true;  <br>        opt.Events.RaiseFailureEvents = true;  <br>        opt.Ciba.DefaultLifetime = 600;  <br>    })  <br>    .AddInMemoryClients(new List&lt;Client&gt;  <br>    {  <br>        new Client  <br>        {  <br>            ClientId = &quot;ciba_client&quot;,  <br>            AllowedGrantTypes = { OidcConstants.GrantTypes.Ciba, OidcConstants.GrantTypes.RefreshToken},  <br>            RefreshTokenExpiration = TokenExpiration.Sliding,  <br>            AllowOfflineAccess = true,  <br>            AllowAccessTokensViaBrowser = false,  <br>            CoordinateLifetimeWithUserSession = true,  <br>            UpdateAccessTokenClaimsOnRefresh = true,  <br>            CibaLifetime = 180,  <br>            RefreshTokenUsage = TokenUsage.ReUse,  <br>            Enabled = true,  <br>            ClientSecrets = { new Secret(&quot;secret&quot;.Sha256()) },  <br>            AllowedScopes = {&quot;openid&quot;, &quot;profile&quot;, &quot;api&quot; },  <br>            AccessTokenLifetime = 180,  <br>            IdentityTokenLifetime = 180  <br>              <br>        }  <br>    })  <br>    .AddInMemoryIdentityResources(new List&lt;IdentityResource&gt;  <br>    {  <br>        new IdentityResources.OpenId(),  <br>        new IdentityResources.Profile()  <br>    })  <br>    .AddInMemoryApiScopes(new List&lt;ApiScope&gt;  <br>    {  <br>        new ApiScope(&quot;api&quot;, &quot;Ciba Api&quot;)  <br>    }).AddTestUsers(TestUsers.Users)  <br>    .AddBackchannelAuthenticationUserValidator&lt;BackchannelAuthenticationUserValidator&gt;()  <br>    .AddBackchannelAuthenticationUserNotificationService&lt;BackchannelAuthenticationUserNotificationService&gt;()  <br>    .AddDeveloperSigningCredential();  <br>  <br>builder.Services.AddEndpointsApiExplorer();  <br>builder.Services.AddSwaggerGen();  <br>builder.Services.AddTransient&lt;ICibaRequestStore, CibaRequestStore&gt;(serviceProvider =&gt;  <br>{  <br>    var store = serviceProvider.GetRequiredService&lt;IPersistedGrantStore&gt;();  <br>    var serializer = serviceProvider.GetRequiredService&lt;IPersistentGrantSerializer&gt;();  <br>    var handleGenerationService = serviceProvider.GetRequiredService&lt;IHandleGenerationService&gt;();  <br>    var logger = serviceProvider.GetRequiredService&lt;ILogger&lt;CibaRequestStore&gt;&gt;();  <br>    var cibaInteractionService = serviceProvider.GetRequiredService&lt;IBackchannelAuthenticationInteractionService&gt;();  <br>  <br>    return new CibaRequestStore(OidcConstants.GrantTypes.Ciba, store, serializer, handleGenerationService, logger, cibaInteractionService);  <br>});  <br>  <br>var app = builder.Build();  <br>  <br>// Configure the HTTP request pipeline.  <br>  <br>app.UseSwagger();  <br>app.UseSwaggerUI();  <br>app.UseIdentityServer();  <br>app.UseCibaEndPoints();  <br>app.Run();</pre><p>To explain these configurations:</p><pre>builder.Services.AddIdentityServer(opt =&gt;  <br>{  <br>    opt.Events.RaiseErrorEvents = true;  <br>    opt.Events.RaiseSuccessEvents = true;  <br>    opt.Events.RaiseFailureEvents = true;  <br>    opt.Ciba.DefaultLifetime = 600;  <br>})</pre><p>We added IdentityServer to the application and defined the settings allowing us to track error, warning, and success events with “<em>opt.Events.Raise*</em>”. With “<em>opt.Ciba.DefaultLifetime</em>”, we defined the lifespan of our CIBA processes (in seconds).</p><pre>.AddInMemoryClients(new List&lt;Client&gt;  <br> {  <br>     new Client  <br>     {  <br>         ClientId = &quot;ciba_client&quot;,//The unique identifier of the client.  <br>         AllowedGrantTypes = { OidcConstants.GrantTypes.Ciba, OidcConstants.GrantTypes.RefreshToken},//The types of grants the client can use (CIBA and Refresh Token).  <br>         RefreshTokenExpiration = TokenExpiration.Sliding,//Refresh token duration is continuously renewed.  <br>         AllowOfflineAccess = true,//The client can receive a refresh token for offline access.  <br>         AllowAccessTokensViaBrowser = false,//Access tokens cannot be obtained through the browser.  <br>         CoordinateLifetimeWithUserSession = true,//Token lifespan is coordinated with the user session.  <br>         UpdateAccessTokenClaimsOnRefresh = true, //An access token is requested when the refresh token is used.  <br>         CibaLifetime = 180,//CIBA token duration  <br>         RefreshTokenUsage = TokenUsage.ReUse,//Refresh token usage is reusable.  <br>         Enabled = true,//Is the client active?  <br>         ClientSecrets = { new Secret(&quot;secret&quot;.Sha256()) },//The shared secret for the client.  <br>         AllowedScopes = {&quot;openid&quot;, &quot;profile&quot;, &quot;api&quot; },//The scopes the client can access.  <br>         AccessTokenLifetime = 180,//Access token duration  <br>         IdentityTokenLifetime = 180//Identity token duration  <br>           <br>     }  <br> })</pre><p>Above, we defined our “<em>Client</em>” configurations.</p><pre>.AddInMemoryIdentityResources(new List&lt;IdentityResource&gt;  <br>  {  <br>      new IdentityResources.OpenId(), //openid scope  <br>      new IdentityResources.Profile() //profile scope  <br>  })  <br>  .AddInMemoryApiScopes(new List&lt;ApiScope&gt;  <br>  {  <br>      new ApiScope(&quot;api&quot;, &quot;Ciba Api&quot;) //Api scope  <br>  }).AddTestUsers(TestUsers.Users)  <br>  .AddBackchannelAuthenticationUserValidator&lt;BackchannelAuthenticationUserValidator&gt;() //Adds the BackchannelAuthenticationUserValidator class.  <br>  .AddBackchannelAuthenticationUserNotificationService&lt;BackchannelAuthenticationUserNotificationService&gt;() //Adds the BackchannelAuthenticationUserNotificationService class.  <br>  .AddDeveloperSigningCredential(); //Generates a signing key for the developer.</pre><p>Now, let’s test our application via “Post</p><p>man” and “Console.” After the application is up and running, we should see the following configuration information:</p><blockquote><a href="http://localhost:5086/.well-known/openid-configuration"><em>http://localhost:5086/.well-known/openid-configuration</em></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*-g7MEz8XwHsdZ1HwvQ1wAg.png" /></figure><p>Uncompressed version:</p><pre>{  <br>  &quot;issuer&quot;: &quot;http://localhost:5086&quot;,  <br>  &quot;jwks_uri&quot;: &quot;http://localhost:5086/.well-known/openid-configuration/jwks&quot;,  <br>  &quot;authorization_endpoint&quot;: &quot;http://localhost:5086/connect/authorize&quot;,  <br>  &quot;token_endpoint&quot;: &quot;http://localhost:5086/connect/token&quot;,  <br>  &quot;userinfo_endpoint&quot;: &quot;http://localhost:5086/connect/userinfo&quot;,  <br>  &quot;end_session_endpoint&quot;: &quot;http://localhost:5086/connect/endsession&quot;,  <br>  &quot;check_session_iframe&quot;: &quot;http://localhost:5086/connect/checksession&quot;,  <br>  &quot;revocation_endpoint&quot;: &quot;http://localhost:5086/connect/revocation&quot;,  <br>  &quot;introspection_endpoint&quot;: &quot;http://localhost:5086/connect/introspect&quot;,  <br>  &quot;device_authorization_endpoint&quot;: &quot;http://localhost:5086/connect/deviceauthorization&quot;,  <br>  &quot;backchannel_authentication_endpoint&quot;: &quot;http://localhost:5086/connect/ciba&quot;,  <br>  &quot;pushed_authorization_request_endpoint&quot;: &quot;http://localhost:5086/connect/par&quot;,  <br>  &quot;require_pushed_authorization_requests&quot;: false,  <br>  &quot;frontchannel_logout_supported&quot;: true,  <br>  &quot;frontchannel_logout_session_supported&quot;: true,  <br>  &quot;backchannel_logout_supported&quot;: true,  <br>  &quot;backchannel_logout_session_supported&quot;: true,  <br>  &quot;scopes_supported&quot;: [  <br>    &quot;openid&quot;,  <br>    &quot;profile&quot;,  <br>    &quot;api&quot;,  <br>    &quot;offline_access&quot;  <br>  ],  <br>  &quot;claims_supported&quot;: [  <br>    &quot;sub&quot;,  <br>    &quot;name&quot;,  <br>    &quot;family_name&quot;,  <br>    &quot;given_name&quot;,  <br>    &quot;middle_name&quot;,  <br>    &quot;nickname&quot;,  <br>    &quot;preferred_username&quot;,  <br>    &quot;profile&quot;,  <br>    &quot;picture&quot;,  <br>    &quot;website&quot;,  <br>    &quot;gender&quot;,  <br>    &quot;birthdate&quot;,  <br>    &quot;zoneinfo&quot;,  <br>    &quot;locale&quot;,  <br>    &quot;updated_at&quot;  <br>  ],  <br>  &quot;grant_types_supported&quot;: [  <br>    &quot;authorization_code&quot;,  <br>    &quot;client_credentials&quot;,  <br>    &quot;refresh_token&quot;,  <br>    &quot;implicit&quot;,  <br>    &quot;password&quot;,  <br>    &quot;urn:ietf:params:oauth:grant-type:device_code&quot;,  <br>    &quot;urn:openid:params:grant-type:ciba&quot;  <br>  ],  <br>  &quot;response_types_supported&quot;: [  <br>    &quot;code&quot;,  <br>    &quot;token&quot;,  <br>    &quot;id_token&quot;,  <br>    &quot;id_token token&quot;,  <br>    &quot;code id_token&quot;,  <br>    &quot;code token&quot;,  <br>    &quot;code id_token token&quot;  <br>  ],  <br>  &quot;response_modes_supported&quot;: [  <br>    &quot;form_post&quot;,  <br>    &quot;query&quot;,  <br>    &quot;fragment&quot;  <br>  ],  <br>  &quot;token_endpoint_auth_methods_supported&quot;: [  <br>    &quot;client_secret_basic&quot;,  <br>    &quot;client_secret_post&quot;  <br>  ],  <br>  &quot;id_token_signing_alg_values_supported&quot;: [  <br>    &quot;RS256&quot;  <br>  ],  <br>  &quot;subject_types_supported&quot;: [  <br>    &quot;public&quot;  <br>  ],  <br>  &quot;code_challenge_methods_supported&quot;: [  <br>    &quot;plain&quot;,  <br>    &quot;S256&quot;  <br>  ],  <br>  &quot;request_parameter_supported&quot;: true,  <br>  &quot;request_object_signing_alg_values_supported&quot;: [  <br>    &quot;RS256&quot;,  <br>    &quot;RS384&quot;,  <br>    &quot;RS512&quot;,  <br>    &quot;PS256&quot;,  <br>    &quot;PS384&quot;,  <br>    &quot;PS512&quot;,  <br>    &quot;ES256&quot;,  <br>    &quot;ES384&quot;,  <br>    &quot;ES512&quot;,  <br>    &quot;HS256&quot;,  <br>    &quot;HS384&quot;,  <br>    &quot;HS512&quot;  <br>  ],  <br>  &quot;prompt_values_supported&quot;: [  <br>    &quot;none&quot;,  <br>    &quot;login&quot;,  <br>    &quot;consent&quot;,  <br>    &quot;select_account&quot;  <br>  ],  <br>  &quot;authorization_response_iss_parameter_supported&quot;: true,  <br>  &quot;backchannel_token_delivery_modes_supported&quot;: [  <br>    &quot;poll&quot;  <br>  ],  <br>  &quot;backchannel_user_code_parameter_supported&quot;: true,  <br>  &quot;dpop_signing_alg_values_supported&quot;: [  <br>    &quot;RS256&quot;,  <br>    &quot;RS384&quot;,  <br>    &quot;RS512&quot;,  <br>    &quot;PS256&quot;,  <br>    &quot;PS384&quot;,  <br>    &quot;PS512&quot;,  <br>    &quot;ES256&quot;,  <br>    &quot;ES384&quot;,  <br>    &quot;ES512&quot;  <br>  ]  <br>}</pre><p>Now let’s initiate our CIBA request with Postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*id6ugibxwBjzqMJPjUUKvg.png" /></figure><blockquote><a href="http://localhost:5086/connect/token"><em>http://localhost:5086/connect/token</em></a></blockquote><p>We made a request to this address with the “client_id,” “client_secret,” “grant_type,” “login_hint” (we used the username), and scope information. We configured all these definitions in the Program.cs class.</p><p>IdentityServer handled many things for us, but for the parts we customized, let’s look at the process steps:</p><ol><li>We validated the user “alice” with the BackchannelAuthenticationUserValidator class.</li><li>We printed the “<em>InternalId</em>” value to the console for verification with the BackchannelAuthenticationUserNotificationService class.</li></ol><blockquote><strong>At this point, you can imagine that we are sending a verification to the user via SMS, PushNotification, or Email.</strong></blockquote><p>Response value:</p><pre>{  <br>    &quot;auth_req_id&quot;: &quot;3653C1E38A355A8978FCFEA87C48450AEA93A1A9044B20A1FEB37965DB5799AA-1&quot;,  <br>    &quot;expires_in&quot;: 180,  <br>    &quot;interval&quot;: 5  <br>}</pre><p>The value printed to the console:</p><p>**Sending login request to the user with request ID 72A5AB4E8ABBE757AF2EDB094BEC9EF29E3557C000CCD37AFA5B72688F27166F</p><p>Now, let’s verify this “<strong><em>request ID</em></strong>” value (<strong>which is the Id of the CIBA request stored in the PersistedStore</strong>) using the “<strong><em>ciba/verify-notification</em></strong>” endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*2cfXAKuFjxul0muCOPqa6g.png" /></figure><p>Once the verification request is complete, we can now retrieve our “<strong>id_token</strong>,” “access_token,” and “refresh_token” parameters using the “<strong>auth_req_id</strong>” value returned from our initial CIBA request.</p><blockquote><a href="http://localhost:5086/connect/token"><em>http://localhost:5086/connect/token</em></a></blockquote><p>Let’s make our request through Postman as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*nNsUMxkjN8-Zj8-mIId5Kg.png" /></figure><p>And we successfully received our tokens:</p><pre>{  <br>    &quot;id_token&quot;: &quot;eyJhbGciOiJSUzI1NiIsImtpZCI6IjE1NjFDMEMxQUMzRTYzRjc1NUJGMDA0NTE5Rjg2NTBBIiwidHlwIjoiSldUIn0.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjUwODYiLCJuYmYiOjE3MjU3OTA5NzgsImlhdCI6MTcyNTc5MDk3OCwiZXhwIjoxNzI1NzkxMTU4LCJhdWQiOiJjaWJhX2NsaWVudCIsImF0X2hhc2giOiI3LU9LT25BRkQyX2NISzRzbFlLRFN3Iiwic3ViIjoiMSIsImF1dGhfdGltZSI6MTcyNTc5MDk2NiwiaWRwIjoibG9jYWwifQ.CzOzPbEqa8jN84tL13VH396Qt3IxDOUmPDtbldEC72n_cv_BuqFs1l6S_AGc3FGWA_eW5_lNPEAn-MOT83d0T1WH2CcrmyOICAkEechypZEJIfSPsSpZga911tcz5CRc7sQjEMdCiX7_1byl2ubpXS87HZt8mZkhRfUk0f2e2MfvX_aurBQtWNhXhBuL4VLTocAbPvRr09bDCEbuHuvy39jPcn36r86OjLrnVelATkjswjFnGVaDZkmsPNciDgo-Ivqst0RpvoTZvgwoDiKSQp9vVJ3qWxKfH4AJhLc9Ds8SYX9Rv66raFTosyvKodde8ZWh9DndE-oaigO-cqvmzQ&quot;,  <br>    &quot;access_token&quot;: &quot;eyJhbGciOiJSUzI1NiIsImtpZCI6IjE1NjFDMEMxQUMzRTYzRjc1NUJGMDA0NTE5Rjg2NTBBIiwidHlwIjoiYXQrand0In0.eyJpc3MiOiJodHR</pre><pre>wOi8vbG9jYWxob3N0OjUwODYiLCJuYmYiOjE3MjU3OTA5NzgsImlhdCI6MTcyNTc5MDk3OCwiZXhwIjoxNzI1NzkxMTU4LCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwiYXBpIiwib2ZmbGluZV9hY2Nlc3MiXSwiY2xpZW50X2lkIjoiY2liYV9jbGllbnQiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNzI1NzkwOTY2LCJpZHAiOiJsb2NhbCIsImp0aSI6IkMwRkIzOTlCRTc3NTEwNjBDOUIxQUJBNTU3MzFCMTI5In0.LLHS72AWpI5L4943dLD9UdYs4f08BM9TgWA_5LGIAOvloenER83U2ENmG_BHxFeU3mZOZPugvtfzyEQ8iruOMN80bwOZL7wb_bSE1FoBMepAvaHxc8BWNk_O6GBSJyO-0GPjkmFGu-mCENBmRGvwPVI2ydzubQnGrvXxHQs9OWfM9OOVeM44aRpVlcFX86ZDYCjd9uhtzMkNTJ4gMPRVDAPMOqqePPFbV8ON9RdleivjQmmrFJUrDfTOdSXjQW64VOEicJwZgg0Doi-XGtjmHDVD_Cfi-8zEeH2tNqIVuTpD9EszcnPGMWo5cJT3_fQ-EoQXwRAGNa_IC2Y6Y0y-hw&quot;,  <br>    &quot;expires_in&quot;: 180,  <br>    &quot;token_type&quot;: &quot;Bearer&quot;,  <br>    &quot;refresh_token&quot;: &quot;0CA49D2668E29984C4622D1F12786D55E657793F1FF255876EAB6005B2BFE712-1&quot;,  <br>    &quot;scope&quot;: &quot;openid profile api offline_access&quot;  <br>}</pre><p>This brings us to the end of our article. In my next article, I will attempt to cover “Kafka Integration with .Net 8”.</p><h3>For project code:</h3><blockquote><a href="https://erdemkaya.com.tr/en/posts/ciba-authentication-with-duende-identity-server"><strong>https://erdemkaya.com.tr</strong></a></blockquote><h3>SOURCE:</h3><p><a href="https://docs.duendesoftware.com/identityserver/v7">https://docs.duendesoftware.com/identityserver/v7</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ea61ad79aef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET gRPC: Developing High-Performance and Scalable Services (Sample Project)]]></title>
            <link>https://medium.com/@erdemkayatr/net-grpc-developing-high-performance-and-scalable-services-sample-project-566f1ede70a5?source=rss-375f2d327254------2</link>
            <guid isPermaLink="false">https://medium.com/p/566f1ede70a5</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[protocol-buffers]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Erdem Kaya]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 11:52:21 GMT</pubDate>
            <atom:updated>2024-10-23T11:52:21.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*slNUcOwCcftLdtsR.jpeg" /></figure><h3>What is gRPC?</h3><p>gRPC (gRPC Remote Procedure Call) is an open-source remote procedure call (RPC) framework developed by Google. It is designed to enable fast, low-latency, and high-performance communication between client and server applications.</p><p>gRPC is a framework built on the HTTP/2 protocol that facilitates easy communication between various programming languages. It uses a highly efficient and portable format called Protocol Buffers (Protobuf) for defining and serializing messages.</p><p>gRPC offers four different communication models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*z60GTg_QATHKhLRW.png" /></figure><p>gRPC Communication Models</p><p><strong>Unary:</strong> The client sends a message, and the server receives a response.</p><p><strong>Server Streaming:</strong> The client sends a message, and the server sends multiple responses over time.</p><p><strong>Client Streaming:</strong> The client sends multiple messages to the server over time, and the server responds with a single reply after receiving all the messages.</p><p><strong>Bidirectional Streaming:</strong> Both the client and the server continuously send and receive messages to and from each other.</p><p><strong>gRPC</strong>, today, microservice architectures, cloud-based applications, and systems requiring high performance continue to be a popular choice. gRPC, in particular, benefits from the advantages offered by HTTP/2, providing faster, more secure, and efficient communication. Major companies like <strong>Netflix</strong>, <strong>Square,</strong> and <strong>Dropbox</strong> have chosen gRPC to build their high-performance microservice architectures.</p><p>After this brief introduction to <strong>gRPC</strong>, we can now start developing a sample application using the .NET 8 framework.</p><p>First, let’s create a solution named <strong><em>GrpcExample</em></strong> and two Web API projects under that solution named <strong><em>Server</em></strong> and <strong><em>Client</em></strong>, as shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/0*QbCF7sp00_YsC6s2.png" /></figure><p>In this project, we will configure the <strong><em>Server</em></strong> application as the <strong>“Server”</strong> for our gRPC service, and the <strong><em>Client</em></strong> application as the <strong>“Client”</strong> for our gRPC project.</p><p>Let’s start with the Server application;</p><p>First, let’s add the following NuGet packages to our project.</p><ol><li><strong>Grpc.AspNetCore</strong>: This package contains the necessary components to host a gRPC service in ASP.NET Core applications.</li><li><strong>Google.Protobuf</strong>: This is the package required to define and process Protocol Buffers (Protobuf) messages.</li><li><strong>Grpc.Tools</strong>: It provides the tools required to compile Protocol Buffers (.proto) files. This package is only used during development and is not required at runtime.</li></ol><p>Here is the content of our <strong>Server.csproj</strong> file:</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;  <br>      <br>      &lt;PropertyGroup&gt;  <br>        &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;  <br>        &lt;Nullable&gt;enable&lt;/Nullable&gt;  <br>        &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;  <br>      &lt;/PropertyGroup&gt;  <br>      <br>      &lt;ItemGroup&gt;  <br>        &lt;PackageReference Include=&quot;Google.Protobuf&quot; Version=&quot;3.27.1&quot; /&gt;  <br>        &lt;PackageReference Include=&quot;Grpc.AspNetCore&quot; Version=&quot;2.63.0&quot; /&gt;  <br>        &lt;PackageReference Include=&quot;Grpc.Tools&quot; Version=&quot;2.64.0&quot;&gt;  <br>          &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;  <br>          &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;  <br>        &lt;/PackageReference&gt;  <br>      &lt;/ItemGroup&gt;  <br>      <br>    &lt;/Project&gt;</pre><p>In our Server project, let’s create a folder named “Protos.” Under this folder, we will create a file named greet.proto. The content of the greet.proto file will be as follows:</p><pre>syntax = &quot;proto3&quot;; /*We specified that we will be using Protobuf version 3.*/  <br>    option csharp_namespace = &quot;Server&quot;; /*We specified that the generated C# classes will reside in the namespace named **Server**.*/  <br>    package server; /* This line specifies that the protobuf file is within a package named **server**.  <br>It helps organize the code and prevent name collisions. */  <br>    import &quot;google/protobuf/wrappers.proto&quot;; /* We imported this file to use the google.protobuf.StringValue type. */  <br>      <br>    service Greeter { /* We created a gRPC service named Greeter.*/  <br>     rpc SayHelloUnary(HelloRequest) returns (HelloReply); /* Unary RPC method */  <br>     rpc SayHelloServerStream(HelloRequest) returns (stream HelloReply); /* Server Stream RPC method */  <br>     rpc SayHelloClientStream(stream HelloRequest) returns (HelloReply); /* Client Stream RPC method */  <br>     rpc SayHelloBidirectionalStream(stream HelloRequest) returns (stream HelloReply); /* Bi-directional Stream RPC method */  <br>    }  <br>      <br>    message HelloRequest {  <br>     string first_name = 1;  <br>     string last_name = 2;  <br>     google.protobuf.StringValue mother_name = 3; /*nullable string*/  <br>    }  <br>      <br>    message HelloReply {  <br>     string message = 1;  <br>    }</pre><p>I tried to explain each line within our Protobuf file. As you may have noticed, in each message, we assigned a field number to each parameter (property). <strong>Field numbers in Protobuf messages must be sequential and unique.</strong></p><p>However, we are not strictly bound to a specific order. We could have defined the field numbers as shown below.</p><pre>message HelloRequest {  <br>     string first_name = 1;  <br>     string last_name = 3;  <br>     google.protobuf.StringValue mother_name = 4; /*nullable string*/  <br>    }</pre><p>This does not affect how Protobuf works, because each field number is unique and will be correctly used during the data serialization and deserialization processes.</p><p>Let’s discuss the advantages and disadvantages of leaving gaps between field numbers, as shown in the example above.</p><h3>Advantages:</h3><ul><li><strong>Flexibility</strong>: Defining field numbers with gaps, like in the 1, 3, and 4 examples, allows for future additions. For instance, you can later add a field with the number 2.</li><li><strong>Compatibility</strong>: Having unique and consistent field numbers helps maintain both backward and forward compatibility.</li></ul><h3>Disadvantages:</h3><ul><li><strong>Disorder</strong>: Non-sequential field numbers can make the message harder to read and manage.</li><li><strong>Unused Fields:</strong> Skipping field numbers can leave unnecessary gaps in the message structure, though this usually doesn’t cause any issues.</li></ul><p>We have briefly covered the field numbers in Protobuf messages. <strong>While it is ultimately up to you to evaluate based on the advantages and disadvantages, it is generally better to follow best practices.</strong></p><p>Now, let’s continue writing our code…</p><p>After creating the “greet.proto” Protobuf file, let’s update our .csproj file as follows to ensure that the file is compiled into C# classes and remains in the directory when our project is deployed.</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;  <br>      <br>      &lt;PropertyGroup&gt;  <br>        &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;  <br>        &lt;Nullable&gt;enable&lt;/Nullable&gt;  <br>        &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;  <br>      &lt;/PropertyGroup&gt;  <br>      <br>      &lt;ItemGroup&gt;  <br>        &lt;PackageReference Include=&quot;Google.Protobuf&quot; Version=&quot;3.27.1&quot; /&gt;  <br>        &lt;PackageReference Include=&quot;Grpc.AspNetCore&quot; Version=&quot;2.63.0&quot; /&gt;  <br>        &lt;PackageReference Include=&quot;Grpc.Tools&quot; Version=&quot;2.64.0&quot;&gt;  <br>          &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;  <br>          &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;  <br>        &lt;/PackageReference&gt;  <br>      &lt;/ItemGroup&gt;  <br>      <br>      &lt;ItemGroup&gt;  <br>        &lt;Protobuf Include=&quot;Protos\greet.proto&quot; ProtoRoot=&quot;Protos\&quot; GrpcServices=&quot;Server&quot; /&gt;  <br>      &lt;/ItemGroup&gt;  <br>      <br>      &lt;ItemGroup&gt;  <br>        &lt;None Update=&quot;Protos\**\*.*&quot;&gt;  <br>          &lt;CopyToOutputDirectory&gt;Always&lt;/CopyToOutputDirectory&gt;  <br>        &lt;/None&gt;  <br>      &lt;/ItemGroup&gt;  <br>      <br>    &lt;/Project&gt;</pre><p>From this point on, when we compile our Server project, the “Grpc.Tools” package will generate the C# classes on our behalf.</p><p>Let’s create a class named <strong>“GreetGrpcService.cs”</strong> and inherit from the <strong>“Greeter.GreeterBase”</strong> base class, which was generated by the “Grpc.Tools” package.</p><p>Now, by overriding the <strong>“rpc”</strong> methods we created in the Protobuf file, we can configure their content as shown below:</p><pre>using Grpc.Core;  <br>      <br>    namespace Server.Services;  <br>      <br>    public class GreetGrpcService : Greeter.GreeterBase // The GreetGrpcService class, which is derived from the Greeter.GreeterBase class.<br>    {  <br>        // The method that performs the Unary gRPC call.<br>        public override Task&lt;HelloReply&gt; SayHelloUnary(HelloRequest request, ServerCallContext context)  <br>        {  <br>            // It creates and returns a HelloReply message. It concatenates the first and last name from the client request and returns it as the message.<br>            return Task.FromResult(new HelloReply  <br>            {  <br>                Message = request.FirstName + &quot; &quot; + request.LastName + &quot; from Unary&quot;  <br>            });  <br>        }  <br>      <br>        // The method that performs the Server Streaming gRPC call.<br>        public override async Task SayHelloServerStream(HelloRequest request, IServerStreamWriter&lt;HelloReply&gt; responseStream, ServerCallContext context)  <br>        {  <br>            int i = 0; // It starts the forecast counter.<br>            while (!context.CancellationToken.IsCancellationRequested &amp;&amp; i &lt; 10) // The loop continues as long as it is not canceled and the counter is less than 10.<br>            {  <br>                // In each loop iteration, it sends a response message to the server.<br>                await responseStream.WriteAsync(new HelloReply  <br>                {  <br>                    Message = request.FirstName + &quot; &quot; + request.LastName + &quot; from Server Streaming&quot;  <br>                });  <br>                i++; // The counter is incremented.<br>            }  <br>        }  <br>      <br>        // The method that performs the Client Streaming gRPC call.<br>        public override async Task&lt;HelloReply&gt; SayHelloClientStream(IAsyncStreamReader&lt;HelloRequest&gt; requestStream, ServerCallContext context)  <br>        {  <br>            var names = new List&lt;string&gt;(); // It creates a list to store the first and last names received from the client.<br>            await foreach (var message in requestStream.ReadAllAsync()) //It reads all the messages received from the client.<br>            {  <br>                // It takes the first and last name from each message and adds them to the list.<br>                names.Add(message.FirstName + &quot; &quot; + message.LastName);  <br>            }  <br>            // It concatenates all the names and returns them as the response.<br>            return new HelloReply  <br>            {  <br>                Message = string.Join(&quot;, &quot;, names) + &quot; from Client Streaming&quot;  <br>            };  <br>        }  <br>      <br>        // The method that performs the Bidirectional Streaming gRPC call.<br>        public override async Task SayHelloBidirectionalStream(IAsyncStreamReader&lt;HelloRequest&gt; requestStream, IServerStreamWriter&lt;HelloReply&gt; responseStream,  <br>            ServerCallContext context)  <br>        {  <br>            await foreach (var message in requestStream.ReadAllAsync()) // It reads all the messages received from the client.<br>            {  <br>                // For each message, it sends a response message to the client.<br>                await responseStream.WriteAsync(new HelloReply  <br>                {  <br>                    Message = message.FirstName + &quot; &quot; + message.LastName + &quot; from Bidirectional Streaming&quot;  <br>                });  <br>            }  <br>        }  <br>    }</pre><p>We have completed our example rpc methods. Now, let’s configure the necessary settings in the “Program.cs” file.</p><p>The final version of our “Program.cs” file will be as follows: Here is the English translation of the provided C# comments:</p><pre>using System.Net;  <br>    using Microsoft.AspNetCore.Server.Kestrel.Core;  <br>    using Server.Services;  <br>      <br>    var builder = WebApplication.CreateBuilder(args);  <br>      <br>    //Configuration for Kestrel  <br>    builder.WebHost.ConfigureKestrel((context, options) =&gt;  <br>    {  <br>        options.Listen(IPAddress.Any, 5858); //For HTTP traffic<br>          <br>        options.Listen(IPAddress.Any, 5859, listenOptions =&gt; //It will listen for gRPC traffic.<br>        {  <br>            listenOptions.Protocols = HttpProtocols.Http2; //We will use the HTTP/2 protocol for gRPC.<br>           // listenOptions.UseHttps(&quot;certificate.pfx&quot;, &quot;password&quot;); //If HTTPS configuration is needed.  <br>        });  <br>    });  <br>    // Add services to the container.  <br>    builder.Services.AddGrpc(); //Adds gRPC services to the DI (Dependency Injection) container.  <br>      <br>    var app = builder.Build();  <br>      <br>    // Configure the HTTP request pipeline.  <br>    app.MapGrpcService&lt;GreetGrpcService&gt;(); //Adds the gRPC service named GreetGrpcService to the HTTP request pipeline. This service will handle gRPC requests.  <br>      <br>    app.MapGet(&quot;/protos/greet-protobuf&quot;, async httpContext =&gt; ///Using the /greet-protobuf endpoint, we will serve our Protobuf file to clients.  <br>    { //We can make this part more generic to serve all proto files under a specific folder. I&#39;ll leave that part to your imagination. :)  <br>        httpContext.Response.ContentType = &quot;text/plain;charset=utf-8&quot;;  <br>        using var fs = File.OpenRead(&quot;Protos/greet.proto&quot;);  <br>        using var sr = new StreamReader(fs, System.Text.Encoding.UTF8);  <br>        while (!sr.EndOfStream)  <br>        {  <br>           var  protoLine = await sr.ReadLineAsync();  <br>           if(protoLine != &quot;/*&gt;&gt;&quot; || protoLine != &quot;&lt;&lt;*/&quot;)  <br>           {  <br>               await httpContext.Response.WriteAsync(protoLine);  <br>           }  <br>             <br>        }  <br>    });  <br>    app.Run();</pre><p>We have thus completed our sample gRPC Server application.</p><p>Now, let’s continue with coding our Client application.</p><p>To simply explain the topology we will establish here, we will code a RestAPI for each of our gRPC methods. From these REST APIs, we will send requests to our gRPC server. If we draw a simple diagram, this example will work as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*rc2PEPROC7TrFTnp.png" /></figure><p>Now we can start coding our “client” application.</p><p>First, let’s add the necessary NuGet packages for our “client” application.</p><ol><li><strong>Grpc.Net.Client</strong>: This package is used to create and manage gRPC clients.</li><li><strong>Grpc.Net.ClientFactory</strong>: This factory is used to create and configure gRPC clients in ASP.NET Core applications. It allows you to register and configure gRPC clients with Dependency Injection (DI). It works similarly to <strong><em>HttpClientFactory</em></strong> and enables you to manage client configurations from a central location.</li><li><strong>Google.Protobuf</strong>: This package is necessary for defining and handling Protocol Buffers (Protobuf) messages.</li><li><strong>Grpc.Tools</strong>: Provides tools necessary to compile Protocol Buffers files (.proto). This package is only used during development and is not required at runtime.</li></ol><p>After loading our packages, our “Client.csproj” file will look like this:</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;  <br>      <br>      &lt;PropertyGroup&gt;  <br>        &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;  <br>        &lt;Nullable&gt;enable&lt;/Nullable&gt;  <br>        &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;  <br>      &lt;/PropertyGroup&gt;  <br>      <br>      &lt;ItemGroup&gt;  <br>        &lt;PackageReference Include=&quot;Google.Protobuf&quot; Version=&quot;3.27.2&quot; /&gt;  <br>        &lt;PackageReference Include=&quot;Grpc.Net.Client&quot; Version=&quot;2.63.0&quot; /&gt;  <br>        &lt;PackageReference Include=&quot;Grpc.Net.ClientFactory&quot; Version=&quot;2.63.0&quot; /&gt;  <br>        &lt;PackageReference Include=&quot;Grpc.Tools&quot; Version=&quot;2.64.0&quot;&gt;  <br>          &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;  <br>          &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;  <br>        &lt;/PackageReference&gt;  <br>      &lt;/ItemGroup&gt;  <br>      <br>    &lt;/Project&gt;</pre><p>Now, let’s import our previously published protobuf file from the following address:</p><blockquote><a href="http://localhost:5858/protos/greet-protobuf"><em>http://localhost:5858/protos/greet-protobuf</em></a></blockquote><p>Steps for this process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/0*KYwNW_DpdCPtzYSu.png" /></figure><blockquote><em>Right-click on Connected Services ⇒ Manage Connected Services</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Cv-JDLju5py8xcvU.png" /></figure><p>Click on the arrow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*99YAxbm6e1TwMh5_.png" /></figure><p>Select gRPC and click Next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*qWV9fuAcfyXNoxG4.png" /></figure><p>Select the URL from the screen and enter the Protobuf address for the server in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*2DgWPFsIMYLSlaJ8.png" /></figure><p>And we got success!</p><p>With the help of our gRPC NuGet packages, Visual Studio has generated our GrpcClient class.</p><p>Now we can prepare the endpoints where we will call our RPC methods. Let’s create a static class called “GreetMinimalApi.cs” under the Apis folder for these endpoints using .Net Minimal APIs and use the “Greeter.GreeterClient” class generated by the “Grpc.Tools” package as follows:</p><pre>using Grpc.Core;  <br>    using Microsoft.AspNetCore.Mvc;  <br>    using Server;  <br>      <br>    namespace Client.Apis;  <br>      <br>    public static class GreetMinimalApi  <br>    {  <br>        // Extension method to add Minimal API endpoints.  <br>        public static void UseGreetEndPoints(this IEndpointRouteBuilder routes)  <br>        {  <br>            // Organizes all greet endpoints by grouping them.  <br>            var group = routes.MapGroup(&quot;greet&quot;);  <br>      <br>            // GET endpoint that performs a Unary gRPC call.  <br>            group.MapGet(&quot;unary&quot;, UnaryExample).WithName(&quot;unary&quot;).WithOpenApi();  <br>      <br>            // GET endpoint that performs a Server Streaming gRPC call.  <br>            group.MapGet(&quot;serverstream&quot;, ServerStreamExample).WithName(&quot;serverstream&quot;).WithOpenApi();  <br>      <br>            // GET endpoint that performs a Client Streaming gRPC call.  <br>            group.MapGet(&quot;clientstream&quot;, ClientStreamExample).WithName(&quot;clientstream&quot;).WithOpenApi();  <br>      <br>            // GET endpoint that performs a Bidirectional Streaming gRPC call.  <br>            group.MapGet(&quot;bidirectionalstream&quot;, BidirectionalStreamExample).WithName(&quot;bidirectionalstream&quot;).WithOpenApi();  <br>        }  <br>      <br>        // Example of a Unary gRPC call. It takes the client&#39;s first and last name, sends it to the server, and returns the response.  <br>        private static async Task&lt;string&gt; UnaryExample([FromServices] Greeter.GreeterClient grpClient, [FromQuery] string name, [FromQuery] string surname)  <br>        {  <br>            // Sends a HelloRequest message to the server and receives a response.  <br>            var grpcResponse = await grpClient.SayHelloUnaryAsync(new HelloRequest { FirstName = name, LastName = surname });  <br>            // Returns the response message.  <br>            return grpcResponse.Message;  <br>        }  <br>      <br>        // Example of a Server Streaming gRPC call. It takes the client&#39;s first and last name, sends it to the server, and receives multiple responses.  <br>        private static async Task&lt;string&gt; ServerStreamExample([FromServices] Greeter.GreeterClient grpClient, [FromQuery] string name, [FromQuery] string surname)  <br>        {  <br>            // Sends a HelloRequest message to the server and receives a response stream.  <br>            var grpcResponse = grpClient.SayHelloServerStream(new HelloRequest { FirstName = name, LastName = surname });  <br>            var response = &quot;&quot;;  <br>            // Reads and combines all messages from the response stream.  <br>            await foreach (var message in grpcResponse.ResponseStream.ReadAllAsync())  <br>            {  <br>                response += message.Message + &quot;\n&quot;;  <br>            }  <br>            // Returns all messages.  <br>            return response;  <br>        }  <br>      <br>        // Example of a Client Streaming gRPC call. It takes the client&#39;s first and last name, sends multiple messages to the server, and receives a response.  <br>        private static async Task&lt;string&gt; ClientStreamExample([FromServices] Greeter.GreeterClient grpClient, [FromQuery] string name, [FromQuery] string surname)  <br>        {  <br>            // Initiates a message stream to the server.  <br>            var grpcResponse = grpClient.SayHelloClientStream();  <br>            // Sends messages from the client to the server.  <br>            await grpcResponse.RequestStream.WriteAsync(new HelloRequest { FirstName = name, LastName = surname });  <br>            await grpcResponse.RequestStream.CompleteAsync();  <br>            // Returns the response from the server.  <br>            return (await grpcResponse).Message;  <br>        }  <br>      <br>        // Example of a Bidirectional Streaming gRPC call. It takes the client&#39;s first and last name, continuously sends and receives messages from both client and server.  <br>        private static async Task&lt;string&gt; BidirectionalStreamExample([FromServices] Greeter.GreeterClient grpClient, [FromQuery] string name, [FromQuery] string surname)  <br>        {  <br>            // Initiates a bidirectional message stream with the server.  <br>            var grpcResponse = grpClient.SayHelloBidirectionalStream();  <br>            // Sends messages from the client to the server.  <br>            await grpcResponse.RequestStream.WriteAsync(new HelloRequest { FirstName = name, LastName = surname });  <br>            await grpcResponse.RequestStream.CompleteAsync();  <br>            var response = &quot;&quot;;  <br>            // Reads and combines all messages from the server.  <br>            await foreach (var message in grpcResponse.ResponseStream.ReadAllAsync())  <br>            {  <br>                response += message.Message + &quot;\n&quot;;  <br>            }  <br>            // Returns all messages.  <br>            return response;  <br>        }  <br>    }</pre><p>Now let’s reorganize the “Program.cs” class of our “client” project for the functionality of the endpoints, Swagger, and ClientFactory:</p><pre>var builder = WebApplication.CreateBuilder(args); // Creates the web application builder object.  <br>      <br>    builder.Services.AddEndpointsApiExplorer(); // Adds services to explore and document API endpoints.  <br>    builder.Services.AddSwaggerGen(c =&gt;  <br>    {  <br>        // Configures Swagger/OpenAPI documentation.  <br>        c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;My API&quot;, Version = &quot;v1&quot; });  <br>    });  <br>      <br>    builder.Services.AddGrpcClient&lt;Greeter.GreeterClient&gt;(o =&gt; o.Address = new Uri(&quot;http://localhost:5859&quot;));   <br>    // Adds the gRPC client as a service and configures the server address for this client.  <br>      <br>    var app = builder.Build(); // Builds the application object.  <br>      <br>    app.UseSwagger(); // Enables Swagger middleware.  <br>    app.UseSwaggerUI</pre><pre>(); // Enables the Swagger user interface.  <br>    app.UseGreetEndPoints(); // Configures the gRPC endpoints from the GreetMinimalApi class.  <br>    app.Run(); // Runs the application.</pre><p>And thus, we have also completed our client project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*IsyigB5BFG0CP7lS.png" /></figure><p>I leave it to you to run the projects and test them on the SwaggerUI screen above 😃</p><p>You can download the code from the following address:</p><blockquote><a href="https://erdemkaya.com.tr/en/posts/net-grpc-developing-high-performance-and-scalable-services-sample-project"><strong><em>https:</em>//erdemkaya.com.tr</strong></a></blockquote><p>In my next post, I will try to explain <strong>Duende Identity Server — CIBA (Client Initiated Backchannel Authentication)</strong> with a sample project.</p><p>See you in the next article…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=566f1ede70a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Duende IdentityServer ile CIBA Authentication]]></title>
            <link>https://medium.com/akbank-teknoloji/duende-identity-server-ile-ciba-authentication-c01a93e421dc?source=rss-375f2d327254------2</link>
            <guid isPermaLink="false">https://medium.com/p/c01a93e421dc</guid>
            <category><![CDATA[identity-server]]></category>
            <category><![CDATA[net-core-8]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[ciba]]></category>
            <dc:creator><![CDATA[Erdem Kaya]]></dc:creator>
            <pubDate>Tue, 22 Oct 2024 13:20:53 GMT</pubDate>
            <atom:updated>2024-11-01T11:11:41.379Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rM-NNfaScuWiFQSkybGvug.jpeg" /></figure><p>CIBA (Client Initiated Backchannel Authentication) Authentication, OAuth 2.0 ve OpenID Connect (OIDC) çerçevelerinde kullanılan bir kimlik doğrulama yöntemidir. Bu yöntem, kullanıcı etkileşiminin gerektirdiği senaryolarda kimlik doğrulama işlemlerinin daha güvenli ve kullanışlı bir şekilde gerçekleştirilmesini sağlar.</p><p>CIBA, özellikle bankacılık, finansal hizmetler ve sağlık hizmetleri gibi yüksek güvenlik gerektiren sektörlerde yaygın olarak kullanılır. Bu yöntem, kullanıcı deneyimini iyileştirirken aynı zamanda güvenliği artırmayı hedefler.</p><h3><strong>CIBA’nın Temel Özellikleri ve Kullanım Durumları</strong></h3><ol><li><strong>Kullanıcı Tarafından Başlatılmayan İstekler: </strong>CIBA, kullanıcının aktif bir şekilde oturum açma işlemini başlatmadığı, ancak bir kimlik doğrulama talebinin gerektiği durumlarda etkilidir. Örneğin, bir finansal işlemi onaylamak için kullanıcının kimlik doğrulaması yapması gerektiğinde kullanılabilir.</li><li><strong>Kullanıcı Etkileşiminin Sınırlı Olduğu Durumlar: </strong>Kullanıcıların sınırlı etkileşimle veya hiç etkileşimi olmadan kimlik doğrulama yapmalarını gerektiren senaryolarda kullanılır. Örneğin, IoT cihazlarında veya akıllı ev sistemlerinde kimlik doğrulama gerektiren durumlarda.</li><li><strong>Güvenlik Gereksinimleri: </strong>Yüksek güvenlik gerektiren uygulamalarda kullanılır. CIBA, kullanıcıya doğrudan kimlik doğrulama taleplerinin gönderilmesi ve kullanıcının doğrulama işlemini bir güvenli cihaz üzerinden yapması esasına dayanır. Bu sayede güvenlik açıkları minimize edilir.</li></ol><h3><strong>CIBA’nın Çalışma Prensibi:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4i30V3-nbHLLByyQG_HMw.png" /><figcaption>Görsel Duende Sayfasından Alınmıştır.</figcaption></figure><p><strong><em>Adım 1.</em></strong></p><p>IdentityServer, istemcinin CIBA iş akışını başlatmak için kullandığı bir backchannel kimlik doğrulama isteği endpoint’i sağlar.</p><p><strong><em>Adım 2.</em></strong></p><p>İstemci kimlik doğrulaması ve temel istek parametresi doğrulaması gerçekleştirildikten sonra, istek yapılan kullanıcının kimliği belirlenmelidir. Bu, DI (Dependency Injection) içindeki IBackchannelAuthenticationUserValidator servisi kullanılarak yapılır. Bu servisi uygulamanız ve DI sistemine kaydetmeniz gerekmektedir. ValidateRequestAsyncyöntemi istek parametrelerini doğrulayacak ve kullanıcının sub (konu tanımlayıcısı) iddiasını içeren bir sonuç döndürecektir.</p><p><strong><em>Adım 3.</em></strong></p><p>Bir kullanıcı başarıyla tanımlandıktan sonra, Backchannel Authentication Request Store’a bekleyen oturum açma isteğini temsil eden bir kayıt oluşturulur.</p><p><strong><em>Adım 4.</em></strong></p><p>Daha sonra, kullanıcıya oturum açma isteği bildirilmelidir. Bu, DI içindeki IBackchannelAuthenticationUserNotificationService servisi kullanılarak yapılır. Bu servisi uygulamanız ve DI sistemine kaydetmeniz gerekmektedir. SendLoginRequestAsync yöntemi, uygun olan herhangi bir mekanizma ile (örneğin; e-posta, kısa mesaj, push bildirimi vb.) kullanıcıyla iletişime geçmeli ve muhtemelen kullanıcının oturum açma ve izin sürecini başlatması için talimatlar sağlamalıdır (belki bir bağlantı aracılığıyla, ancak diğer yaklaşımlar da düşünülebilir). Bu yöntem, kullanıcıya gönderilmesi gereken tüm bağlamsal bilgileri içeren bir BackchannelUserLoginRequest iletilir (isteğin tamamlanmasında gerekli olan bu oturum açma isteği için InternalId kimliği dahil).</p><p><strong><em>Adım 5.</em></strong></p><p>Daha sonra, kullanıcıya oturum açma isteği için bilgiler sunulmalıdır (örneğin, IdentityServer’da bir web sayfası aracılığıyla veya uygun olan diğer herhangi bir yolla). IBackchannelAuthenticationInteractionService kullanılarak bir BackchannelUserLoginRequest&#39;e InternalId ile erişilebilir. Kullanıcı izni ve oturum açma izininden sonra, CompleteLoginRequestAsync yöntemiyle sonuç (kullanıcının hangi kapsamları kabul ettiği dahil) kaydedilmelidir.</p><p><strong><em>Adım 6.</em></strong></p><p>İstemci, sonucu almak için yapılan anketten sonra, talep edilen belirteçleri (kullanıcı isteği reddetmişse veya zaman aşımına uğramışsa uygun bir hata) alacaktır.</p><p>Şimdi basit bir CIBA örnek projesi yapalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*rMQ87MTdL94Mc3DOfKiV1g.png" /></figure><p>Resimde görüldüğü gibi .Net 8 projemizi oluşturduk. Projemize aşağıdaki paketleri ekleyelim.</p><pre>&lt;PackageReference Include=&quot;Duende.IdentityServer&quot; Version=&quot;7.0.6&quot; /&gt;<br>&lt;PackageReference Include=&quot;Swashbuckle.AspNetCore.SwaggerGen&quot; Version=&quot;6.7.2&quot; /&gt;<br>&lt;PackageReference Include=&quot;Microsoft.AspNetCore.OpenApi&quot; Version=&quot;8.0.8&quot; /&gt;<br>&lt;PackageReference Include=&quot;Swashbuckle.AspNetCore.SwaggerUI&quot; Version=&quot;6.7.2&quot; /&gt;</pre><p>Şimdi “Stores” isimli klasör altına bekleyen CIBA işlemlerimizi tamamlayacağımız bir “ICibaRequestStore.cs” interface’ini ve bu interface’den kalıtım alan “CibaRequestStore.cs” isimli sınıfımızı aşağıdaki gibi oluşturalım. (Kod satırlarını açıklamalarla anlatmaya çalıştım.):</p><pre>namespace CibaExample.Api.Stores;<br><br>public interface ICibaRequestStore<br>{<br>    Task CompleteCibaRequestAsync(string id); //Bekleyen Ciba isteğini tamamlar<br>}</pre><p>“CibaRequestStore.cs” sınıfına aşağıda biraz daha detaylı girmemiz gerekecek:</p><pre>using Duende.IdentityServer.Models;<br>using Duende.IdentityServer.Services;<br>using Duende.IdentityServer.Stores;<br>using Duende.IdentityServer.Stores.Serialization;<br>using System.Security.Claims;<br><br>namespace CibaExample.Api.Stores;<br><br>public class CibaRequestStore : DefaultGrantStore&lt;BackChannelAuthenticationRequest&gt;, ICibaRequestStore<br>{<br><br>    private IBackchannelAuthenticationInteractionService _cibaInteractionService;<br>    public CibaRequestStore(string grantType, IPersistedGrantStore store, IPersistentGrantSerializer serializer, IHandleGenerationService handleGenerationService, ILogger logger, IBackchannelAuthenticationInteractionService cibaInteractionService) : base(grantType, store, serializer, handleGenerationService, logger)<br>    {<br>        _cibaInteractionService = cibaInteractionService;<br>    }<br><br>    public async Task CompleteCibaRequestAsync(string id)<br>    {<br>       var persisted = await Store.GetAsync(id);<br>       if (persisted == null)<br>       {<br>           throw new NullReferenceException(&quot;Grant not found&quot;);<br>       }<br>       var backChannelAuthenticationRequestData = Serializer.Deserialize&lt;BackChannelAuthenticationRequest&gt;(persisted.Data);<br>        var completeRequest = new CompleteBackchannelLoginRequest(id)<br>       {<br>           InternalId = id,<br>           Subject = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]<br>           {<br>               new Claim(&quot;sub&quot;, persisted.SubjectId) // Kullanıcıyı tanımlayan subject (örneğin user_id)<br>           })),<br>           ScopesValuesConsented = backChannelAuthenticationRequestData.RequestedScopes<br>        };<br><br>       await _cibaInteractionService.CompleteLoginRequestAsync(completeRequest);<br>        <br>       <br>    }<br>  <br>}</pre><ul><li><strong>Constructure Parametreleri:</strong></li></ul><p><strong>grantType: </strong>Verilecek iznin türünü belirtir.</p><p><strong>store (<em>IPersistedGrantStore</em>): </strong>Kimlik doğrulama süreçlerinde kullanılan kalıcı izinleri (persisted grant) yönetmek için kullanılan arayüzdür. Bu kalıcı izinler, OAuth 2.0 veya OpenID Connect protokollerinde kullanılan uzun süreli izinler, erişim token’ları, yenileme token’ları ve diğer izin türlerini içerir. Başlıca işlevlerini aşağıdaki gibi özetleyebiliriz:</p><ol><li>Token Saklama</li><li>Token Güncelleme</li><li>Token Silme</li><li>Token Getirme</li></ol><p><strong>serializer: </strong>Verileri seri hale getirmek ve tekrar eski hale getirme için kullanılır.</p><p><strong>handleGenerationService:</strong> Eşsiz kimlik(handle) oluşturmak için kullanılan hizmettir.</p><p><strong>logger:</strong> Loglama işlemleri için kullanılır (ILogger arayüzü).</p><p><strong>cibaInteractionService (<em>IBackchannelAuthenticationInteractionService</em>):</strong> CIBA etkileşimlerini yönetmek için kullanılan hizmettir.</p><ul><li><strong>CompleteCibaRequestAsync Metodu:</strong></li></ul><p>Bekleyen CIBA işlemini tamamlamak için yazdığımız custom metot.</p><p>Şimdi kullanıcı doğrulama işlemlerini gerçekleştireceğimiz “<em>IBackchannelAuthenticationUserValidator</em>” arayüzünü implemente eden “<em>BackchannelAuthenticationUserValidator</em>” sınıfını ve tüm bu işlemlerde örnek olarak kullanacağımız kullanıcıları içeren “<em>TestUser</em>” sınıfını oluşturalım.</p><pre>using Duende.IdentityServer.Test;<br>using Duende.IdentityServer;<br>using IdentityModel;<br>using System.Security.Claims;<br>using System.Text.Json;<br><br>namespace CibaExample.Api;<br><br>public static class TestUsers<br>{<br>    public static List&lt;TestUser&gt; Users<br>    {<br>        get<br>        {<br>            var address = new<br>            {<br>                street_address = &quot;One Hacker Way&quot;,<br>                locality = &quot;Heidelberg&quot;,<br>                postal_code = &quot;69118&quot;,<br>                country = &quot;Germany&quot;<br>            };<br><br>            return new List&lt;TestUser&gt;<br>            {<br>                new TestUser<br>                {<br>                    SubjectId = &quot;1&quot;,<br>                    Username = &quot;alice&quot;,<br>                    Password = &quot;alice&quot;,<br>                    Claims =<br>                    {<br>                        new Claim(JwtClaimTypes.Name, &quot;Alice Smith&quot;),<br>                        new Claim(JwtClaimTypes.GivenName, &quot;Alice&quot;),<br>                        new Claim(JwtClaimTypes.FamilyName, &quot;Smith&quot;),<br>                        new Claim(JwtClaimTypes.Email, &quot;AliceSmith@email.com&quot;),<br>                        new Claim(JwtClaimTypes.EmailVerified, &quot;true&quot;, ClaimValueTypes.Boolean),<br>                        new Claim(JwtClaimTypes.WebSite, &quot;http://alice.com&quot;),<br>                        new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)<br>                    }<br>                },<br>                new TestUser<br>                {<br>                    SubjectId = &quot;2&quot;,<br>                    Username = &quot;bob&quot;,<br>                    Password = &quot;bob&quot;,<br>                    Claims =<br>                    {<br>                        new Claim(JwtClaimTypes.Name, &quot;Bob Smith&quot;),<br>                        new Claim(JwtClaimTypes.GivenName, &quot;Bob&quot;),<br>                        new Claim(JwtClaimTypes.FamilyName, &quot;Smith&quot;),<br>                        new Claim(JwtClaimTypes.Email, &quot;BobSmith@email.com&quot;),<br>                        new Claim(JwtClaimTypes.EmailVerified, &quot;true&quot;, ClaimValueTypes.Boolean),<br>                        new Claim(JwtClaimTypes.WebSite, &quot;http://bob.com&quot;),<br>                        new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)<br>                    }<br>                }<br>            };<br>        }<br>    }<br>}</pre><pre><br>using System.Security.Claims;<br>using Duende.IdentityServer.Validation;<br>using IdentityModel;<br><br>namespace CibaExample.Api.Validators;<br><br>public class <br>using System.Security.Claims;<br>using Duende.IdentityServer.Validation;<br>using IdentityModel;<br><br>namespace CibaExample.Api.Validators;<br><br>public class BackchannelAuthenticationUserValidator : IBackchannelAuthenticationUserValidator<br>{<br><br>    public Task&lt;BackchannelAuthenticationUserValidationResult&gt; ValidateRequestAsync(BackchannelAuthenticationUserValidatorContext userValidatorContext)<br>    {<br><br>        var user = TestUsers.Users.FirstOrDefault(u =&gt; u.Username == userValidatorContext?.LoginHint);<br><br>        return Task.FromResult(new BackchannelAuthenticationUserValidationResult<br>        {<br>            Subject = new ClaimsPrincipal(new ClaimsIdentity(new List&lt;Claim&gt;<br>            {<br>                new Claim(&quot;sub&quot;, user?.SubjectId),<br>                new Claim(JwtClaimTypes.AuthenticationTime, DateTime.UtcNow.ToEpochTime().ToString()), // auth_time claim&#39;i<br>                new Claim(JwtClaimTypes.IdentityProvider, &quot;local&quot;),<br>            })),<br>        });<br>    }<br>} : IBackchannelAuthenticationUserValidator<br>{<br><br>    public Task&lt;BackchannelAuthenticationUserValidationResult&gt; ValidateRequestAsync(BackchannelAuthenticationUserValidatorContext userValidatorContext)<br>    {<br><br>        var user = TestUsers.Users.FirstOrDefault(u =&gt; u.Username == userValidatorContext?.LoginHint);<br><br>        return Task.FromResult(new BackchannelAuthenticationUserValidationResult<br>        {<br>            Subject = new ClaimsPrincipal(new ClaimsIdentity(new List&lt;Claim&gt;<br>            {<br>                new Claim(&quot;sub&quot;, user?.SubjectId),<br>                new Claim(JwtClaimTypes.AuthenticationTime, DateTime.UtcNow.ToEpochTime().ToString()), // auth_time claim&#39;i<br>                new Claim(JwtClaimTypes.IdentityProvider, &quot;local&quot;),<br>            })),<br>        });<br>    }<br>}</pre><p>Şimdi CIBA isteği oluşturduğumuzda kullanıcıya push notification, SMS veya e-mail ile onay talebi göndereceğimiz sınıfı ekleyelim. Biz burada onay için konsola “ID” değerini yazdıracağız.</p><pre>using Duende.IdentityServer.Models;<br>using Duende.IdentityServer.Services;<br><br>namespace CibaExample.Api.Services;<br><br>public class BackchannelAuthenticationUserNotificationService : IBackchannelAuthenticationUserNotificationService<br>{<br>    public Task SendLoginRequestAsync(BackchannelUserLoginRequest request)<br>    {<br>        Console.WriteLine($&quot;**Sending login request to user with request ID {request.InternalId}&quot;);<br>        return Task.CompletedTask;<br>    }<br>}</pre><p>Bekleyen CIBA işlemimizi konsola yazdırdığımız “ID” değeri yardımıyla onaylayacağımız endpoint’i ekleyelim.</p><pre>using CibaExample.Api.Stores;<br>using Microsoft.AspNetCore.Mvc;<br>namespace CibaExample.Api.Apis;<br><br>public static class AuthMinimalApi<br>{<br><br>    public static void UseCibaEndPoints(this IEndpointRouteBuilder routes)<br>    {<br>        var group = routes.MapGroup(&quot;ciba&quot;);<br><br>        group.MapPost(&quot;verify-notification&quot;,VerifyAsync).WithName(&quot;verify&quot;).WithOpenApi();<br>    }<br><br>    private static async Task&lt;IResult&gt; VerifyAsync([FromServices] ICibaRequestStore store,string id)<br>    {<br><br>       await store.CompleteCibaRequestAsync(id);<br><br>       return Results.Ok(true);<br>    }<br>}</pre><p>Ve son olarak, IdentityServer konfigürasyonlarını ve “<em>Ciba Client</em>” tanımlamalarımızı “<em>Program.cs</em>” sınıfımız içerisinde gerçekleştirelim.</p><pre>using CibaExample.Api;<br>using CibaExample.Api.Apis;<br>using CibaExample.Api.Services;<br>using CibaExample.Api.Stores;<br>using CibaExample.Api.Validators;<br>using Duende.IdentityServer.Models;<br>using Duende.IdentityServer.Services;<br>using Duende.IdentityServer.Stores;<br>using Duende.IdentityServer.Stores.Serialization;<br>using IdentityModel;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br><br><br>builder.Services.AddIdentityServer(opt =&gt;<br>    {<br>        opt.Events.RaiseErrorEvents = true;<br>        opt.Events.RaiseSuccessEvents = true;<br>        opt.Events.RaiseFailureEvents = true;<br>        opt.Ciba.DefaultLifetime = 600;<br>    })<br>    .AddInMemoryClients(new List&lt;Client&gt;<br>    {<br>        new Client<br>        {<br>            ClientId = &quot;ciba_client&quot;,<br>            AllowedGrantTypes = { OidcConstants.GrantTypes.Ciba, OidcConstants.GrantTypes.RefreshToken},<br>            RefreshTokenExpiration = TokenExpiration.Sliding,<br>            AllowOfflineAccess = true,<br>            AllowAccessTokensViaBrowser = false,<br>            CoordinateLifetimeWithUserSession = true,<br>            UpdateAccessTokenClaimsOnRefresh = true,<br>            CibaLifetime = 180,<br>            RefreshTokenUsage = TokenUsage.ReUse,<br>            Enabled = true,<br>            ClientSecrets = { new Secret(&quot;secret&quot;.Sha256()) },<br>            AllowedScopes = {&quot;openid&quot;, &quot;profile&quot;, &quot;api&quot; },<br>            AccessTokenLifetime = 180,<br>            IdentityTokenLifetime = 180<br>            <br>        }<br>    })<br>    .AddInMemoryIdentityResources(new List&lt;IdentityResource&gt;<br>    {<br>        new IdentityResources.OpenId(),<br>        new IdentityResources.Profile()<br>    })<br>    .AddInMemoryApiScopes(new List&lt;ApiScope&gt;<br>    {<br>        new ApiScope(&quot;api&quot;, &quot;Ciba Api&quot;)<br>    }).AddTestUsers(TestUsers.Users)<br>    .AddBackchannelAuthenticationUserValidator&lt;BackchannelAuthenticationUserValidator&gt;()<br>    .AddBackchannelAuthenticationUserNotificationService&lt;BackchannelAuthenticationUserNotificationService&gt;()<br>    .AddDeveloperSigningCredential();<br><br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br>builder.Services.AddTransient&lt;ICibaRequestStore, CibaRequestStore&gt;(serviceProvider =&gt;<br>{<br>    var store = serviceProvider.GetRequiredService&lt;IPersistedGrantStore&gt;();<br>    var serializer = serviceProvider.GetRequiredService&lt;IPersistentGrantSerializer&gt;();<br>    var handleGenerationService = serviceProvider.GetRequiredService&lt;IHandleGenerationService&gt;();<br>    var logger = serviceProvider.GetRequiredService&lt;ILogger&lt;CibaRequestStore&gt;&gt;();<br>    var cibaInteractionService = serviceProvider.GetRequiredService&lt;IBackchannelAuthenticationInteractionService&gt;();<br><br>    return new CibaRequestStore(OidcConstants.GrantTypes.Ciba, store, serializer, handleGenerationService, logger, cibaInteractionService);<br>});<br><br>var app = builder.Build();<br><br>// Configure the HTTP request pipeline.<br><br>app.UseSwagger();<br>app.UseSwaggerUI();<br>app.UseIdentityServer();<br>app.UseCibaEndPoints();<br>app.Run();</pre><p>Bu konfigürasyonları açıklamak gerekirse:</p><pre>builder.Services.AddIdentityServer(opt =&gt;<br>{<br>    opt.Events.RaiseErrorEvents = true;<br>    opt.Events.RaiseSuccessEvents = true;<br>    opt.Events.RaiseFailureEvents = true;<br>    opt.Ciba.DefaultLifetime = 600;<br>})</pre><p>IdentityServer’ı uygulamaya ekledik ve “<em>opt.Events.Raise*</em>” ile hata, uyarı ve başarılı işlemleri izlememizi sağlayan ayarları tanımladık. “<em>opt.Ciba.DefaultLifetime</em>” ile de CIBA işlemlerimizin ömrünü tanımladık (saniye cinsinden).</p><pre> .AddInMemoryClients(new List&lt;Client&gt;<br> {<br>     new Client<br>     {<br>         ClientId = &quot;ciba_client&quot;,//İstemcinin benzersiz kimlik bilgisi.<br>         AllowedGrantTypes = { OidcConstants.GrantTypes.Ciba, OidcConstants.GrantTypes.RefreshToken},//İstemcinin kullanabileceği izin türleri (CIBA ve Refresh Token&#39;ı).<br>         RefreshTokenExpiration = TokenExpiration.Sliding,//Refresh token&#39;ının süresi, sürekli yenilenir<br>         AllowOfflineAccess = true,//İstemci çevrimdışı erişim için yenileme token&#39;ı alabilir.<br>         AllowAccessTokensViaBrowser = false,//Erişim token&#39;ı tarayıcı üzerinden alınamaz.<br>         CoordinateLifetimeWithUserSession = true,//Token ömrü, kullanıcı oturumu ile koordine edilir.<br>         UpdateAccessTokenClaimsOnRefresh = true, //Yenileme token&#39;ı kullanıldığında erişim token&#39;ı talep edilir.<br>         CibaLifetime = 180,//Ciba token&#39;ının süresi<br>         RefreshTokenUsage = TokenUsage.ReUse,//Refresh token&#39;ın kullanımı, tekrar kullanılabilir.<br>         Enabled = true,//İstemci etkin mi?<br>         ClientSecrets = { new Secret(&quot;secret&quot;.Sha256()) },//İstemci için paylaşılan secret.<br>         AllowedScopes = {&quot;openid&quot;, &quot;profile&quot;, &quot;api&quot; },//İstemcinin erişebileceği kapsamlar.<br>         AccessTokenLifetime = 180,//Erişim token&#39;ının süresi<br>         IdentityTokenLifetime = 180//Kimlik token&#39;ının süresi<br>         <br>     }<br> })</pre><p>Yukarıda “<em>Client</em>” tanımlamalarımızı yaptık.</p><pre>  .AddInMemoryIdentityResources(new List&lt;IdentityResource&gt;<br>  {<br>      new IdentityResources.OpenId(), //openid kapsamı<br>      new IdentityResources.Profile() //profile kapsamı<br>  })<br>  .AddInMemoryApiScopes(new List&lt;ApiScope&gt;<br>  {<br>      new ApiScope(&quot;api&quot;, &quot;Ciba Api&quot;) //Api kapsamı<br>  }).AddTestUsers(TestUsers.Users)<br>  .AddBackchannelAuthenticationUserValidator&lt;BackchannelAuthenticationUserValidator&gt;() //BackchannelAuthenticationUserValidator sınıfını ekler.<br>  .AddBackchannelAuthenticationUserNotificationService&lt;BackchannelAuthenticationUserNotificationService&gt;() //BackchannelAuthenticationUserNotificationService sınıfını ekler.<br>  .AddDeveloperSigningCredential(); //Geliştirici için imza anahtarı oluşturur.</pre><p>Şimdi uygulamamızı “Postman” ve “Console” üzerinden test edelim. Uygulama ayağa kalktıktan sonra,</p><blockquote><a href="http://localhost:5086/.well-known/openid-configuration">http://localhost:5086/.well-known/openid-configuration</a></blockquote><p>adresine gittiğimizde aşağıdaki konfigürasyon bilgilerini görmemiz gerekli:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-g7MEz8XwHsdZ1HwvQ1wAg.png" /></figure><p>Açık hali:</p><pre>{<br>  &quot;issuer&quot;: &quot;http://localhost:5086&quot;,<br>  &quot;jwks_uri&quot;: &quot;http://localhost:5086/.well-known/openid-configuration/jwks&quot;,<br>  &quot;authorization_endpoint&quot;: &quot;http://localhost:5086/connect/authorize&quot;,<br>  &quot;token_endpoint&quot;: &quot;http://localhost:5086/connect/token&quot;,<br>  &quot;userinfo_endpoint&quot;: &quot;http://localhost:5086/connect/userinfo&quot;,<br>  &quot;end_session_endpoint&quot;: &quot;http://localhost:5086/connect/endsession&quot;,<br>  &quot;check_session_iframe&quot;: &quot;http://localhost:5086/connect/checksession&quot;,<br>  &quot;revocation_endpoint&quot;: &quot;http://localhost:5086/connect/revocation&quot;,<br>  &quot;introspection_endpoint&quot;: &quot;http://localhost:5086/connect/introspect&quot;,<br>  &quot;device_authorization_endpoint&quot;: &quot;http://localhost:5086/connect/deviceauthorization&quot;,<br>  &quot;backchannel_authentication_endpoint&quot;: &quot;http://localhost:5086/connect/ciba&quot;,<br>  &quot;pushed_authorization_request_endpoint&quot;: &quot;http://localhost:5086/connect/par&quot;,<br>  &quot;require_pushed_authorization_requests&quot;: false,<br>  &quot;frontchannel_logout_supported&quot;: true,<br>  &quot;frontchannel_logout_session_supported&quot;: true,<br>  &quot;backchannel_logout_supported&quot;: true,<br>  &quot;backchannel_logout_session_supported&quot;: true,<br>  &quot;scopes_supported&quot;: [<br>    &quot;openid&quot;,<br>    &quot;profile&quot;,<br>    &quot;api&quot;,<br>    &quot;offline_access&quot;<br>  ],<br>  &quot;claims_supported&quot;: [<br>    &quot;sub&quot;,<br>    &quot;name&quot;,<br>    &quot;family_name&quot;,<br>    &quot;given_name&quot;,<br>    &quot;middle_name&quot;,<br>    &quot;nickname&quot;,<br>    &quot;preferred_username&quot;,<br>    &quot;profile&quot;,<br>    &quot;picture&quot;,<br>    &quot;website&quot;,<br>    &quot;gender&quot;,<br>    &quot;birthdate&quot;,<br>    &quot;zoneinfo&quot;,<br>    &quot;locale&quot;,<br>    &quot;updated_at&quot;<br>  ],<br>  &quot;grant_types_supported&quot;: [<br>    &quot;authorization_code&quot;,<br>    &quot;client_credentials&quot;,<br>    &quot;refresh_token&quot;,<br>    &quot;implicit&quot;,<br>    &quot;password&quot;,<br>    &quot;urn:ietf:params:oauth:grant-type:device_code&quot;,<br>    &quot;urn:openid:params:grant-type:ciba&quot;<br>  ],<br>  &quot;response_types_supported&quot;: [<br>    &quot;code&quot;,<br>    &quot;token&quot;,<br>    &quot;id_token&quot;,<br>    &quot;id_token token&quot;,<br>    &quot;code id_token&quot;,<br>    &quot;code token&quot;,<br>    &quot;code id_token token&quot;<br>  ],<br>  &quot;response_modes_supported&quot;: [<br>    &quot;form_post&quot;,<br>    &quot;query&quot;,<br>    &quot;fragment&quot;<br>  ],<br>  &quot;token_endpoint_auth_methods_supported&quot;: [<br>    &quot;client_secret_basic&quot;,<br>    &quot;client_secret_post&quot;<br>  ],<br>  &quot;id_token_signing_alg_values_supported&quot;: [<br>    &quot;RS256&quot;<br>  ],<br>  &quot;subject_types_supported&quot;: [<br>    &quot;public&quot;<br>  ],<br>  &quot;code_challenge_methods_supported&quot;: [<br>    &quot;plain&quot;,<br>    &quot;S256&quot;<br>  ],<br>  &quot;request_parameter_supported&quot;: true,<br>  &quot;request_object_signing_alg_values_supported&quot;: [<br>    &quot;RS256&quot;,<br>    &quot;RS384&quot;,<br>    &quot;RS512&quot;,<br>    &quot;PS256&quot;,<br>    &quot;PS384&quot;,<br>    &quot;PS512&quot;,<br>    &quot;ES256&quot;,<br>    &quot;ES384&quot;,<br>    &quot;ES512&quot;,<br>    &quot;HS256&quot;,<br>    &quot;HS384&quot;,<br>    &quot;HS512&quot;<br>  ],<br>  &quot;prompt_values_supported&quot;: [<br>    &quot;none&quot;,<br>    &quot;login&quot;,<br>    &quot;consent&quot;,<br>    &quot;select_account&quot;<br>  ],<br>  &quot;authorization_response_iss_parameter_supported&quot;: true,<br>  &quot;backchannel_token_delivery_modes_supported&quot;: [<br>    &quot;poll&quot;<br>  ],<br>  &quot;backchannel_user_code_parameter_supported&quot;: true,<br>  &quot;dpop_signing_alg_values_supported&quot;: [<br>    &quot;RS256&quot;,<br>    &quot;RS384&quot;,<br>    &quot;RS512&quot;,<br>    &quot;PS256&quot;,<br>    &quot;PS384&quot;,<br>    &quot;PS512&quot;,<br>    &quot;ES256&quot;,<br>    &quot;ES384&quot;,<br>    &quot;ES512&quot;<br>  ]<br>}</pre><p>Şimdi Postman ile CIBA isteğimizi başlatalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*id6ugibxwBjzqMJPjUUKvg.png" /></figure><blockquote><a href="http://localhost:5086/connect/token">http://localhost:5086/connect/token</a></blockquote><p>adresine “client_id”, “client_secret”, “grant_type”, “login_hint” (biz username olarak aldık), scope bilgileri ile istek attık. Tüm bu tanımlamalarımızı Program.cs sınıfında yapmıştık.</p><p>IdentityServer bizim için birçok şeyi halletti ancak kendi özelleştirdiğimiz yerler için işlem adımlarına bakarsak:</p><ol><li>BackchannelAuthenticationUserValidator sınıfı ile “alice” kullanıcısını doğruladık.</li><li>BackchannelAuthenticationUserNotificationService sınıfı ile konsola doğrulama yapacağımız “<em>InternalId</em>” değerini bastık.</li></ol><blockquote><strong><em>Bu kısımda SMS, PushNotification, Email gibi kullanıcıya doğrulama gönderdiğimizi hayal edebilirsiniz</em></strong></blockquote><p>Response değerimiz:</p><pre>{<br>    &quot;auth_req_id&quot;: &quot;3653C1E38A355A8978FCFEA87C48450AEA93A1A9044B20A1FEB37965DB5799AA-1&quot;,<br>    &quot;expires_in&quot;: 180,<br>    &quot;interval&quot;: 5<br>}</pre><p>Konsola bastığımız değer:</p><pre>**Sending login request to user with request ID 72A5AB4E8ABBE757AF2EDB094BEC9EF29E3557C000CCD37AFA5B72688F27166F</pre><p>Şimdi buradaki “<strong><em>request ID</em></strong>” değerimizi (<strong>ki aslında bu PersistedStore da saklanan CIBA isteğinin Id değeridir.</strong>) “<strong><em>ciba/verify-notification</em></strong>” endpoint’i yardımıyla doğrulayalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cfXAKuFjxul0muCOPqa6g.png" /></figure><p>Doğrulama isteği tamamlandıktan sonra artık ilk CIBA isteğimizden dönen “<strong>auth_req_id</strong>” değeri ile “id_token”, “access_token” ve “resfresh_token” parametrelerimizi alabiliriz.</p><blockquote><a href="http://localhost:5086/connect/token">http://localhost:5086/connect/token</a></blockquote><p>adresine aşağıdaki gibi “Postman” üzerinden isteğimizi atalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNsUMxkjN8-Zj8-mIId5Kg.png" /></figure><p>Ve token’larımızı başarılı şekilde aldık.</p><pre>{<br>    &quot;id_token&quot;: &quot;eyJhbGciOiJSUzI1NiIsImtpZCI6IjE1NjFDMEMxQUMzRTYzRjc1NUJGMDA0NTE5Rjg2NTBBIiwidHlwIjoiSldUIn0.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjUwODYiLCJuYmYiOjE3MjU3OTA5NzgsImlhdCI6MTcyNTc5MDk3OCwiZXhwIjoxNzI1NzkxMTU4LCJhdWQiOiJjaWJhX2NsaWVudCIsImF0X2hhc2giOiI3LU9LT25BRkQyX2NISzRzbFlLRFN3Iiwic3ViIjoiMSIsImF1dGhfdGltZSI6MTcyNTc5MDk2NiwiaWRwIjoibG9jYWwifQ.CzOzPbEqa8jN84tL13VH396Qt3IxDOUmPDtbldEC72n_cv_BuqFs1l6S_AGc3FGWA_eW5_lNPEAn-MOT83d0T1WH2CcrmyOICAkEechypZEJIfSPsSpZga911tcz5CRc7sQjEMdCiX7_1byl2ubpXS87HZt8mZkhRfUk0f2e2MfvX_aurBQtWNhXhBuL4VLTocAbPvRr09bDCEbuHuvy39jPcn36r86OjLrnVelATkjswjFnGVaDZkmsPNciDgo-Ivqst0RpvoTZvgwoDiKSQp9vVJ3qWxKfH4AJhLc9Ds8SYX9Rv66raFTosyvKodde8ZWh9DndE-oaigO-cqvmzQ&quot;,<br>    &quot;access_token&quot;: &quot;eyJhbGciOiJSUzI1NiIsImtpZCI6IjE1NjFDMEMxQUMzRTYzRjc1NUJGMDA0NTE5Rjg2NTBBIiwidHlwIjoiYXQrand0In0.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjUwODYiLCJuYmYiOjE3MjU3OTA5NzgsImlhdCI6MTcyNTc5MDk3OCwiZXhwIjoxNzI1NzkxMTU4LCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwiYXBpIiwib2ZmbGluZV9hY2Nlc3MiXSwiY2xpZW50X2lkIjoiY2liYV9jbGllbnQiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNzI1NzkwOTY2LCJpZHAiOiJsb2NhbCIsImp0aSI6IkMwRkIzOTlCRTc3NTEwNjBDOUIxQUJBNTU3MzFCMTI5In0.LLHS72AWpI5L4943dLD9UdYs4f08BM9TgWA_5LGIAOvloenER83U2ENmG_BHxFeU3mZOZPugvtfzyEQ8iruOMN80bwOZL7wb_bSE1FoBMepAvaHxc8BWNk_O6GBSJyO-0GPjkmFGu-mCENBmRGvwPVI2ydzubQnGrvXxHQs9OWfM9OOVeM44aRpVlcFX86ZDYCjd9uhtzMkNTJ4gMPRVDAPMOqqePPFbV8ON9RdleivjQmmrFJUrDfTOdSXjQW64VOEicJwZgg0Doi-XGtjmHDVD_Cfi-8zEeH2tNqIVuTpD9EszcnPGMWo5cJT3_fQ-EoQXwRAGNa_IC2Y6Y0y-hw&quot;,<br>    &quot;expires_in&quot;: 180,<br>    &quot;token_type&quot;: &quot;Bearer&quot;,<br>    &quot;refresh_token&quot;: &quot;0CA49D2668E29984C4622D1F12786D55E657793F1FF255876EAB6005B2BFE712-1&quot;,<br>    &quot;scope&quot;: &quot;openid profile api offline_access&quot;<br>}</pre><p>Böylece yazımızın sonuna geldik. Bir sonraki yazımda “.Net 8 ile Kafka Entegrasyonu” konusuna değinmeye çalışacağım.</p><h3>Proje kodları için:</h3><blockquote><a href="https://erdemkaya.com.tr/tr/posts/duende-identity-server-ile-ciba-authentication"><strong>https://www.erdemkaya.com.tr</strong></a></blockquote><h3>KAYNAK:</h3><p><a href="https://docs.duendesoftware.com/identityserver/v7">https://docs.duendesoftware.com/identityserver/v7</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c01a93e421dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akbank-teknoloji/duende-identity-server-ile-ciba-authentication-c01a93e421dc">Duende IdentityServer ile CIBA Authentication</a> was originally published in <a href="https://medium.com/akbank-teknoloji">Akbank Teknoloji</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.Net gRPC: Performanslı ve Ölçeklenebilir Servisler Geliştirmek (Örnek Proje)]]></title>
            <link>https://medium.com/akbank-teknoloji/net-grpc-performansl%C4%B1-ve-%C3%B6l%C3%A7eklenebilir-servisler-geli%C5%9Ftirmek-%C3%B6rnek-proje-be24feee5468?source=rss-375f2d327254------2</link>
            <guid isPermaLink="false">https://medium.com/p/be24feee5468</guid>
            <dc:creator><![CDATA[Erdem Kaya]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 11:48:00 GMT</pubDate>
            <atom:updated>2024-08-02T11:48:00.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4S-mhMs7UfZB2EeHUKr0Jg.jpeg" /></figure><h3><strong>gRPC Nedir?</strong></h3><p>gRPC (gRPC Remote Procedure Call), Google tarafından geliştirilen ve açık kaynaklı bir uzaktan prosedür çağrısı (RPC) çerçevesidir. gRPC, istemci ve sunucu uygulamaları arasında hızlı, düşük gecikmeli ve yüksek performanslı iletişim sağlamak amacıyla tasarlanmıştır.</p><p>gRPC, çeşitli programlama dilleri arasında kolayca iletişim kurmayı sağlayan, HTTP/2 protokolü üzerine inşa edilmiş bir framework’tür. Mesajların tanımlanması ve seri hale getirişmesi için Protokol Buffers (Protobuf) adı verilen verimli ve taşınabilir bir format kullanır.</p><p>gRPC, dört farklı iletişim modeli sunar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDW1cyKOxkEARoIwDWSBdQ.png" /><figcaption>gRPC İletişim Modelleri</figcaption></figure><p><strong>Unary: </strong>İstemci bir mesaj gönderir ve sunucu bir yanıt alır.</p><p><strong>Server Streaming:</strong> İstemci, bir mesaj gönderir ve sunucu zaman içinde birden fazla yanıt gönderir.</p><p><strong>Client Streaming:</strong> İstemci, sunucuya zaman içerisinde birden fazla mesaj gönderir ve sunucu, tüm mesajları aldıktan sonra bir yanıt gönderir.</p><p><strong>Bidirectional Streaming:</strong> Hem istemci hem de sunucu birbirlerine sürekli olarak mesaj gönderir ve alır.</p><p><strong>gRPC</strong>, günümüzde mikro hizmet mimarileri, bulut tabanlı uygulamalar ve yüksek performans gerektiren sistemler için popüler bir seçim olmaya devam etmektedir. Özellikle, HTTP/2&#39;nin sunduğu avantajlardan faydalanarak daha hızlı, güvenli ve verimli iletişim sağlar. <strong>Netflix</strong>, <strong>Square</strong>, <strong>Dropbox </strong>gibi büyük firmalar, yüksek performanslı mikro hizmet mimarilerini oluşturmak için gRPC’yi tercih etmişlerdir.</p><p><strong>gRPC</strong>’yi tanıdığımız bu kısa girişten sonra şimdi .net 8 framework’ü ile örnek bir uygulama geliştirmeye başlayabiliriz.</p><p>Öncelikle aşağıdaki resimde olduğu gibi <strong><em>GrpcExample </em></strong>isimli bir solution ve o solution altında <strong><em>Server </em></strong>ve <strong><em>Client </em></strong>isminde iki WebApi projesi oluşturalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*bQlqM7JE2siMgZ9sru9ABQ.png" /></figure><p>Bu projede; <strong><em>server </em></strong>uygulamasını gRPC servisimiz için <strong>“Sunucu”</strong>; <strong><em>Client </em></strong>uygulaması ise gRPC projemiz için <strong>“istemci”</strong> olacak şekilde ayarlayacağız.</p><p>Server uygulumasından başlayalım;</p><p>Öncelikle aşağıdaki nuget paketleri projemize ekleyelim.</p><ol><li><strong>Grpc.AspNetCore</strong>: Bu paket, ASP.NET Core uygulamalarında gRPC servisini barındırmak için gerekli bileşenleri içerir.</li><li><strong>Google.Protobuf</strong>: Protokol Buffers (Protobuf) mesajlarını tanımlamak ve işlemek için gerekli olan pakettir.</li><li><strong>Grpc.Tools</strong>: Protokol Buffers dosyalarını (.proto) derlemek için gerekli olan araçları sağlar. Bu paket sadece geliştirme zamanında kullanılır, çalışma zamanında (runtime) gerekli değildir.</li></ol><p><strong>Server.csproj</strong> dosyamızın içeriği aşağıdaki gibi oldu.</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;<br><br>  &lt;PropertyGroup&gt;<br>    &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;<br>    &lt;Nullable&gt;enable&lt;/Nullable&gt;<br>    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;<br>  &lt;/PropertyGroup&gt;<br><br>  &lt;ItemGroup&gt;<br>    &lt;PackageReference Include=&quot;Google.Protobuf&quot; Version=&quot;3.27.1&quot; /&gt;<br>    &lt;PackageReference Include=&quot;Grpc.AspNetCore&quot; Version=&quot;2.63.0&quot; /&gt;<br>    &lt;PackageReference Include=&quot;Grpc.Tools&quot; Version=&quot;2.64.0&quot;&gt;<br>      &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;<br>      &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;<br>    &lt;/PackageReference&gt;<br>  &lt;/ItemGroup&gt;<br><br>&lt;/Project&gt;</pre><p>Server projemizde “Protos” isimli bir klasör oluşturalım. Bu klasör altına greet.proto isminde bir dosya oluşturacağız. greet.proto dosya içeriği;</p><pre>syntax = &quot;proto3&quot;; /*Protobuf 3 sürümünü kullanacağımızı beklirttik*/<br>option csharp_namespace = &quot;Server&quot;; /*Oluşturulacak C# sınıflarımızın Server isimli namespace de yer alacağını belirttik*/<br>package server; /* Bu satır protobuf dosyasının server adlı bir paket içinde olduğunu belirtir<br>    Bu, kodu organize etmeye ve isim çakışmalarını önlemeye yardımcı olur */<br>import &quot;google/protobuf/wrappers.proto&quot;; /* google.protobuf.StringValue tipini kullanabilmek için bu dosyayı import ettik */<br><br>service Greeter { /* Greeter isimli bir gRPC servis oluşturduk*/<br> rpc SayHelloUnary(HelloRequest) returns (HelloReply); /* Unary RPC Metot*/<br> rpc SayHelloServerStream(HelloRequest) returns (stream HelloReply); /* Server Stream RPC Metot*/<br> rpc SayHelloClientStream(stream HelloRequest) returns (HelloReply); /* Client Stream RPC Metot*/<br> rpc SayHelloBidirectionalStream(stream HelloRequest) returns (stream HelloReply); /* Bi-directional Stream RPC Metot*/<br>}<br><br>message HelloRequest {<br> string first_name = 1;<br> string last_name = 2;<br> google.protobuf.StringValue mother_name = 3; /*nullable string*/<br>}<br><br>message HelloReply {<br> string message = 1;<br>}</pre><p>Protobuf dosyamız içerisinde her bir satırı açıklamaya çalıştım. Her bir mesaj (message) içeriğimizde dikkat ettiğiniz gibi her bir parametreye (property) alan numarası verdik. <strong>Protobuf mesajlarında alan numaralarının sıralı ve benzersiz olması önemlidir.</strong></p><p>Ancak; belirli bir sıraya bağlı kalmak zorunda da değiliz. Alan numaralarını aşağıdaki gibi de tanımlayabilirdik.</p><pre>message HelloRequest {<br> string first_name = 1;<br> string last_name = 3;<br> google.protobuf.StringValue mother_name = 4; /*nullable string*/<br>}</pre><p>Bu, Protobuf’un çalışma şeklini etkilemez, çünkü her alan numarası benzersizdir ve veri paketleme ve çözme süreçlerinde doğru şekilde kullanılacaktır.</p><p>Alan numaraları arasında yukarıdaki örnekte olduğu gibi boşluklar bırakmanın avantajları ve dezavantajlarına değinelim;</p><h4><strong>Avantajlar;</strong></h4><ul><li><strong>Esneklik</strong>: Alan numaralarını 1,3,4 örneğinde olduğu gibi boşluklar vererek tanımlamak, gelecekte eklemeler yapmanıza olanak tanır. Örneğin 2 numaralı alanı sonradan ekleyebilirsiniz.</li><li><strong>Uyumluluk</strong>: Alan numaralarının benzersiz ve tutarlı olması, geriye ve ileriye dönük uyumluluğu korumanıza yardımcı olur.</li></ul><h4><strong>Dezavantajlar;</strong></h4><ul><li><strong>Düzensizlik</strong>: Alan numaralarının sıralı olmaması, mesajın okunabilirliğini ve yönetilebilirliğini zorlaştırabilir.</li><li><strong>Boş Alanlar: </strong>Alan numaralarının atlanması, mesaj yapısında gereksiz boşluklar bırakabilir, ancak bu genellikle bir sorun yaratmaz.</li></ul><p>Protobuf mesajlarının alan numaralarına da kısaca değinmiş olduk. <strong>Burada avantaj ve dezavantajlara göre değerlendirmek sizlere kalmış olsa da iyi uygulama önerilerine (best practice) uymak daha doğru olabilir.</strong></p><p>Şimdi kodumuzu yazmaya devam edelim..</p><p>“greet.proto” Protobuf dosyamızı oluşturduktan sonra; hem dosyanın derlenip c# class larının oluşması hem de projemiz canlıya alınırken Protobuf dosyamızın dizinde olmasını garanti etmek için projemizin .csproj dosyasını aşağıdaki hale getirelim.</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;<br><br>  &lt;PropertyGroup&gt;<br>    &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;<br>    &lt;Nullable&gt;enable&lt;/Nullable&gt;<br>    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;<br>  &lt;/PropertyGroup&gt;<br><br>  &lt;ItemGroup&gt;<br>    &lt;PackageReference Include=&quot;Google.Protobuf&quot; Version=&quot;3.27.1&quot; /&gt;<br>    &lt;PackageReference Include=&quot;Grpc.AspNetCore&quot; Version=&quot;2.63.0&quot; /&gt;<br>    &lt;PackageReference Include=&quot;Grpc.Tools&quot; Version=&quot;2.64.0&quot;&gt;<br>      &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;<br>      &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;<br>    &lt;/PackageReference&gt;<br>  &lt;/ItemGroup&gt;<br><br>  &lt;ItemGroup&gt;<br>    &lt;Protobuf Include=&quot;Protos\greet.proto&quot; ProtoRoot=&quot;Protos\&quot; GrpcServices=&quot;Server&quot; /&gt;<br>  &lt;/ItemGroup&gt;<br><br>  &lt;ItemGroup&gt;<br>    &lt;None Update=&quot;Protos\**\*.*&quot;&gt;<br>      &lt;CopyToOutputDirectory&gt;Always&lt;/CopyToOutputDirectory&gt;<br>    &lt;/None&gt;<br>  &lt;/ItemGroup&gt;<br><br>&lt;/Project&gt;</pre><p>Bundan sonrasında; Server projemizi derlediğimiz zaman “Grpc.Tools” paketi bizim adımıza C# class’larımızı oluşturacaktır.</p><p>Bizde “Grpc.Tools” paketinin bizim için oluşturduğu Base class’ı kullanmak için <strong>“GreetGrpcService.cs” </strong>isimli bir class oluşturalım ve <strong>“Greeter.GreeterBase” </strong>base class’ından kalıtım alalım.</p><p>Artık override ederek Protobuf dosyasında oluşturduğumuz <strong>“rpc”</strong> metotlarını kullanıp içeriğini aşağıdaki gibi ayarlayabiliriz:</p><pre>using Grpc.Core;<br><br>namespace Server.Services;<br><br>public class GreetGrpcService : Greeter.GreeterBase // Greeter.GreeterBase sınıfından türeyen GreetGrpcService sınıfı.<br>{<br>    // Unary gRPC çağrısını gerçekleştiren metot.<br>    public override Task&lt;HelloReply&gt; SayHelloUnary(HelloRequest request, ServerCallContext context)<br>    {<br>        // HelloReply mesajı oluşturur ve döner. İstemciden gelen ad ve soyadı birleştirir ve mesaj olarak döner.<br>        return Task.FromResult(new HelloReply<br>        {<br>            Message = request.FirstName + &quot; &quot; + request.LastName + &quot; from Unary&quot;<br>        });<br>    }<br><br>    // Server Streaming gRPC çağrısını gerçekleştiren metot.<br>    public override async Task SayHelloServerStream(HelloRequest request, IServerStreamWriter&lt;HelloReply&gt; responseStream, ServerCallContext context)<br>    {<br>        int i = 0; // Döngü sayacını başlatır.<br>        while (!context.CancellationToken.IsCancellationRequested &amp;&amp; i &lt; 10) // İptal edilmediği sürece ve sayaç 10&#39;dan küçük olduğu sürece döngü devam eder.<br>        {<br>            // Sunucuya her bir döngüde yanıt mesajı gönderir.<br>            await responseStream.WriteAsync(new HelloReply<br>            {<br>                Message = request.FirstName + &quot; &quot; + request.LastName + &quot; from Server Streaming&quot;<br>            });<br>            i++; // Sayaç artırılır.<br>        }<br>    }<br><br>    // Client Streaming gRPC çağrısını gerçekleştiren metot.<br>    public override async Task&lt;HelloReply&gt; SayHelloClientStream(IAsyncStreamReader&lt;HelloRequest&gt; requestStream, ServerCallContext context)<br>    {<br>        var names = new List&lt;string&gt;(); // İstemciden gelen ad ve soyadları tutacak bir liste oluşturur.<br>        await foreach (var message in requestStream.ReadAllAsync()) // İstemciden gelen tüm mesajları okur.<br>        {<br>            // Her bir mesajdan adı ve soyadı alıp listeye ekler.<br>            names.Add(message.FirstName + &quot; &quot; + message.LastName);<br>        }<br>        // Tüm adları birleştirir ve yanıt olarak döner.<br>        return new HelloReply<br>        {<br>            Message = string.Join(&quot;, &quot;, names) + &quot; from Client Streaming&quot;<br>        };<br>    }<br><br>    // Bidirectional Streaming gRPC çağrısını gerçekleştiren metot.<br>    public override async Task SayHelloBidirectionalStream(IAsyncStreamReader&lt;HelloRequest&gt; requestStream, IServerStreamWriter&lt;HelloReply&gt; responseStream,<br>        ServerCallContext context)<br>    {<br>        await foreach (var message in requestStream.ReadAllAsync()) // İstemciden gelen tüm mesajları okur.<br>        {<br>            // Her bir mesaj için sunucuya yanıt mesajı gönderir.<br>            await responseStream.WriteAsync(new HelloReply<br>            {<br>                Message = message.FirstName + &quot; &quot; + message.LastName + &quot; from Bidirectional Streaming&quot;<br>            });<br>        }<br>    }<br>}</pre><p>Örnek rpc metotlarımızı tamamlamış olduk. Şimdi “Program.cs” dosyası içerisinde yapmamız gereken konfigürasyonları yapalım.</p><p>“Program.cs” dosyasımızın son hali aşağıdaki gibi olacaktır.</p><pre>using System.Net;<br>using Microsoft.AspNetCore.Server.Kestrel.Core;<br>using Server.Services;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>//ConfigurationKestrel<br>builder.WebHost.ConfigureKestrel((context, options) =&gt;<br>{<br>    options.Listen(IPAddress.Any, 5858); //http trafiğini için<br>    <br>    options.Listen(IPAddress.Any, 5859, listenOptions =&gt; //gRPC trafiğini dinleyecek<br>    {<br>        listenOptions.Protocols = HttpProtocols.Http2; //gRPC için HTTP/2 protokolünü kullanacağız<br>       // listenOptions.UseHttps(&quot;certificate.pfx&quot;, &quot;password&quot;); //https yapılandırması gerekirse..<br>    });<br>});<br>// Add services to the container.<br>builder.Services.AddGrpc();//gRPC hizmetlerini DI (Dependency Injection) konteynerine ekler.<br><br>var app = builder.Build();<br><br>// Configure the HTTP request pipeline.<br>app.MapGrpcService&lt;GreetGrpcService&gt;(); //GreetGrpcService adlı gRPC hizmetini HTTP istek hattına (pipeline) ekler. Bu hizmet, gRPC isteklerini karşılar.<br><br>app.MapGet(&quot;/protos/greet-protobuf&quot;, async httpContext =&gt; ///greet-protobuf endpointi yardımıyla Protobuf dosyasımızı istemcilere sunacağız.<br>{ //Bu kısımı generic hale getirip belli bir klasöraltındaki tüm proto dosyalarını sunacak şekilde değiştirebiliriz. Bu kısmı hayal gücünüze bırakıyorum. :)<br>    httpContext.Response.ContentType = &quot;text/plain;charset=utf-8&quot;;<br>    using var fs = File.OpenRead(&quot;Protos/greet.proto&quot;);<br>    using var sr = new StreamReader(fs, System.Text.Encoding.UTF8);<br>    while (!sr.EndOfStream)<br>    {<br>       var  protoLine = await sr.ReadLineAsync();<br>       if(protoLine != &quot;/*&gt;&gt;&quot; || protoLine != &quot;&lt;&lt;*/&quot;)<br>       {<br>           await httpContext.Response.WriteAsync(protoLine);<br>       }<br>       <br>    }<br>});<br>app.Run();<br></pre><p>gRPC Server Örnek Uygulamamızı bu şekilde tamamlamış olduk.</p><p>Şimdi Client uygulamamızın kodlamasıyla devam edelim..</p><p>Burada kuracağımız topolojiyi basit halde anlatmak gerekirse her bir gRPC metotumuz için birer RestAPI kodlayacağız. Bu REST API’ler içerisinden de gRPC server’ımıza istek atacağız. Basit bir çizim yaparsak bu örneğimiz aşağıdaki gibi çalışacak:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*eHmsNNEGFFcJ_bfBq3JsgQ.png" /></figure><p>Şimdi “<strong>client</strong>” Uygulamamızı kodlamaya başlayabiliriz.</p><p>Öncelikle “<strong>client</strong>” uygulamamız için gerekli nuget paketleri ekleyelim.</p><ol><li><strong>Grpc.Net.Client</strong>: Bu paket, gRPC istemcilerini oluşturmak ve yönetmek için kullanılan bir pakettir.</li><li><strong>Grpc.Net.ClientFactory:</strong> ASP.NET Core uygulamalarında gRPC istemcilerini oluşturmak ve yapılandırmak için kullanılan bir fabrikadır. Bu paket, Dependency Injection (DI) ile gRPC istemcilerini kaydetmenizi ve yapılandırmanızı sağlar. <strong><em>HttpClientFactory </em></strong>ile benzer bir şekilde çalışır ve istemci yapılandırmalarını merkezi bir yerden yönetmenize olanak tanır.</li><li><strong>Google.Protobuf</strong>: Protokol Buffers (Protobuf) mesajlarını tanımlamak ve işlemek için gerekli olan pakettir.</li><li><strong>Grpc.Tools</strong>: Protokol Buffers dosyalarını (.proto) derlemek için gerekli olan araçları sağlar. Bu paket sadece geliştirme zamanında kullanılır, çalışma zamanında (runtime) gerekli değildir.</li></ol><p>Paketlerimizi yükledikten sonra “<strong>Client.csproj</strong>” dosyamızın son hali aşağıdaki gibi olacaktır:</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;<br><br>  &lt;PropertyGroup&gt;<br>    &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;<br>    &lt;Nullable&gt;enable&lt;/Nullable&gt;<br>    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;<br>  &lt;/PropertyGroup&gt;<br><br>  &lt;ItemGroup&gt;<br>    &lt;PackageReference Include=&quot;Google.Protobuf&quot; Version=&quot;3.27.2&quot; /&gt;<br>    &lt;PackageReference Include=&quot;Grpc.Net.Client&quot; Version=&quot;2.63.0&quot; /&gt;<br>    &lt;PackageReference Include=&quot;Grpc.Net.ClientFactory&quot; Version=&quot;2.63.0&quot; /&gt;<br>    &lt;PackageReference Include=&quot;Grpc.Tools&quot; Version=&quot;2.64.0&quot;&gt;<br>      &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;<br>      &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;<br>    &lt;/PackageReference&gt;<br>  &lt;/ItemGroup&gt;<br><br>&lt;/Project&gt;</pre><p>Şimdi daha önce yayınladığımız protobuf dosyamızı;</p><blockquote><a href="http://localhost:5858/protos/greet-protobuf">http://localhost:5858/protos/greet-protobuf</a></blockquote><p>Adresinden Client projemize import edelim. Bu işlem için adımlar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*M0bVkarLhDRMwMaT0yOBJw.png" /></figure><blockquote>Connected Services (sağ click) =&gt; Manage Connected Services</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zX4VLnilwQ7ZH-iOHKdC-A.png" /><figcaption>Ok İşaretine Tıklıyoruz</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*wOx9FOfDKNrOeXsODRE0hA.png" /><figcaption>gRPC seçip Next diyoruz</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*qdEPMrJarCukh0Iyn3BEmQ.png" /><figcaption>Ekrandan URL seçtik ve yayında olan Server için Protobuf Adresimizi Yazdık.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*xi2ssbUj_fiIFWl2oPOt8Q.png" /><figcaption>Vee success aldık</figcaption></figure><p>Visual Studio gRPC nuget paketlerimizinde yardımıyla bize GrpcClient sınıfımızı oluşturdu.</p><p>Artık RPC metotlarımızı çağıracağımız endpointlerimizi hazırlayabiliriz. Bu endpointler için .Net Minimal API’lardan faydalanacağımız Apis klasörü altında “GreetMinimalApi.cs” isimli static class ımızı aşağıdaki gibi oluşturalım ve “Grpc.Tools” nuget paketinin oluşturduğu “Greeter.GreeterClient” sınıfımızı bu endpointler altında aşağıdaki gibi kullanalım.</p><pre>using Grpc.Core;<br>using Microsoft.AspNetCore.Mvc;<br>using Server;<br><br>namespace Client.Apis;<br><br>public static class GreetMinimalApi<br>{<br>    // Minimal API endpointlerini eklemek için extension metodu.<br>    public static void UseGreetEndPoints(this IEndpointRouteBuilder routes)<br>    {<br>        // Tüm greet endpointlerini gruplayarak organize eder.<br>        var group = routes.MapGroup(&quot;greet&quot;);<br><br>        // Unary gRPC çağrısını gerçekleştiren GET endpointi.<br>        group.MapGet(&quot;unary&quot;, UnaryExample).WithName(&quot;unary&quot;).WithOpenApi();<br><br>        // Server Streaming gRPC çağrısını gerçekleştiren GET endpointi.<br>        group.MapGet(&quot;serverstream&quot;, ServerStreamExample).WithName(&quot;serverstream&quot;).WithOpenApi();<br><br>        // Client Streaming gRPC çağrısını gerçekleştiren GET endpointi.<br>        group.MapGet(&quot;clientstream&quot;, ClientStreamExample).WithName(&quot;clientstream&quot;).WithOpenApi();<br><br>        // Bidirectional Streaming gRPC çağrısını gerçekleştiren GET endpointi.<br>        group.MapGet(&quot;bidirectionalstream&quot;, BidirectionalStreamExample).WithName(&quot;bidirectionalstream&quot;).WithOpenApi();<br>    }<br><br>    // Unary gRPC çağrısı örneği. İstemciden adı ve soyadı alır, sunucuya gönderir ve yanıtı döner.<br>    private static async Task&lt;string&gt; UnaryExample([FromServices] Greeter.GreeterClient grpClient, [FromQuery] string name, [FromQuery] string surname)<br>    {<br>        // Sunucuya bir HelloRequest mesajı gönderir ve yanıtı alır.<br>        var grpcResponse = await grpClient.SayHelloUnaryAsync(new HelloRequest { FirstName = name, LastName = surname });<br>        // Yanıt mesajını döner.<br>        return grpcResponse.Message;<br>    }<br><br>    // Server Streaming gRPC çağrısı örneği. İstemciden adı ve soyadı alır, sunucuya gönderir ve sunucudan birden fazla yanıt alır.<br>    private static async Task&lt;string&gt; ServerStreamExample([FromServices] Greeter.GreeterClient grpClient, [FromQuery] string name, [FromQuery] string surname)<br>    {<br>        // Sunucuya bir HelloRequest mesajı gönderir ve yanıt akışını alır.<br>        var grpcResponse = grpClient.SayHelloServerStream(new HelloRequest { FirstName = name, LastName = surname });<br>        var response = &quot;&quot;;<br>        // Yanıt akışından tüm mesajları okur ve birleştirir.<br>        await foreach (var message in grpcResponse.ResponseStream.ReadAllAsync())<br>        {<br>            response += message.Message + &quot;\n&quot;;<br>        }<br>        // Tüm mesajları döner.<br>        return response;<br>    }<br><br>    // Client Streaming gRPC çağrısı örneği. İstemciden adı ve soyadı alır, sunucuya birden fazla mesaj gönderir ve sunucudan yanıt alır.<br>    private static async Task&lt;string&gt; ClientStreamExample([FromServices] Greeter.GreeterClient grpClient, [FromQuery] string name, [FromQuery] string surname)<br>    {<br>        // Sunucuya mesaj akışı başlatır.<br>        var grpcResponse = grpClient.SayHelloClientStream();<br>        // İstemciden gelen mesajları sunucuya gönderir.<br>        await grpcResponse.RequestStream.WriteAsync(new HelloRequest { FirstName = name, LastName = surname });<br>        await grpcResponse.RequestStream.CompleteAsync();<br>        // Sunucudan gelen yanıtı döner.<br>        return (await grpcResponse).Message;<br>    }<br><br>    // Bidirectional Streaming gRPC çağrısı örneği. İstemciden adı ve soyadı alır, sunucuya ve istemciye sürekli mesaj gönderir ve alır.<br>    private static async Task&lt;string&gt; BidirectionalStreamExample([FromServices] Greeter.GreeterClient grpClient, [FromQuery] string name, [FromQuery] string surname)<br>    {<br>        // Sunucuya iki yönlü mesaj akışı başlatır.<br>        var grpcResponse = grpClient.SayHelloBidirectionalStream();<br>        // İstemciden gelen mesajları sunucuya gönderir.<br>        await grpcResponse.RequestStream.WriteAsync(new HelloRequest { FirstName = name, LastName = surname });<br>        await grpcResponse.RequestStream.CompleteAsync();<br>        var response = &quot;&quot;;<br>        // Sunucudan gelen tüm mesajları okur ve birleştirir.<br>        await foreach (var message in grpcResponse.ResponseStream.ReadAllAsync())<br>        {<br>            response += message.Message + &quot;\n&quot;;<br>        }<br>        // Tüm mesajları döner.<br>        return response;<br>    }<br>}</pre><p>Şimdi “client” projemizin “Program.cs” class’ını oluşturduğumuz endpoint’lerin çalışması, Swagger ve ClientFactory işlemleri için yeniden organize edelim;</p><pre>var builder = WebApplication.CreateBuilder(args); // Web uygulaması oluşturucu nesnesini oluşturur.<br><br>builder.Services.AddEndpointsApiExplorer(); // API uç noktalarını keşfetmek ve belgelenmek için hizmetleri ekler.<br>builder.Services.AddSwaggerGen(c =&gt;<br>{<br>    // Swagger/OpenAPI belgelerini yapılandırır.<br>    c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;My API&quot;, Version = &quot;v1&quot; });<br>});<br><br>builder.Services.AddGrpcClient&lt;Greeter.GreeterClient&gt;(o =&gt; o.Address = new Uri(&quot;http://localhost:5859&quot;)); <br>// gRPC istemcisini hizmet olarak ekler ve bu istemcinin sunucu adresini yapılandırır.<br><br>var app = builder.Build(); // Uygulama nesnesini oluşturur.<br><br>app.UseSwagger(); // Swagger orta katmanını etkinleştirir.<br>app.UseSwaggerUI(); // Swagger kullanıcı arayüzünü etkinleştirir.<br>app.UseGreetEndPoints(); // GreetMinimalApi sınıfındaki gRPC endpointlerini yapılandırır.<br>app.Run(); // Uygulamayı çalıştırır.</pre><p>Ve böylelikle client projemizi de tamamlamış olduk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0eCTqONb5bnodAl7ik9yoA.png" /></figure><p>Pojeleri çalıştırıp yukarıdaki SwaggerUI ekranında test etmeyi size bırakıyorum :)</p><p>Kodları aşağıdaki adresten indirebilirsiniz;</p><blockquote><a href="https://github.com/erdemkayagentr/GrpcExample">https://github.com/erdemkayagentr/GrpcExample</a></blockquote><p>Bir sonraki yazımda sizlere <strong>Duende Identity Server — CIBA (Client Initiated Backchannel Authentication)</strong> ‘ı örnek bir projeyle anlatmaya çalışacağım.</p><p>Bir sonraki yazımızda görüşmek üzere…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be24feee5468" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akbank-teknoloji/net-grpc-performansl%C4%B1-ve-%C3%B6l%C3%A7eklenebilir-servisler-geli%C5%9Ftirmek-%C3%B6rnek-proje-be24feee5468">.Net gRPC: Performanslı ve Ölçeklenebilir Servisler Geliştirmek (Örnek Proje)</a> was originally published in <a href="https://medium.com/akbank-teknoloji">Akbank Teknoloji</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>