<?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 Kerim YILDIRIM on Medium]]></title>
        <description><![CDATA[Stories by Kerim YILDIRIM on Medium]]></description>
        <link>https://medium.com/@kerimhassan81?source=rss-e4bbdb6fb885------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TZC5ZLlJUGDQuo_J.jpg</url>
            <title>Stories by Kerim YILDIRIM on Medium</title>
            <link>https://medium.com/@kerimhassan81?source=rss-e4bbdb6fb885------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:49:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kerimhassan81/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[Rate Limiting Algorithms]]></title>
            <link>https://medium.com/@kerimhassan81/rate-limiting-algorithms-859fc1573983?source=rss-e4bbdb6fb885------2</link>
            <guid isPermaLink="false">https://medium.com/p/859fc1573983</guid>
            <category><![CDATA[rate-limit-algorithms]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[rate-limit]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Kerim YILDIRIM]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 20:43:16 GMT</pubDate>
            <atom:updated>2024-10-28T20:43:16.262Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Rate Limiting</h3><p>Rate limiting is a technique used to control the amount of the traffic sent or received by a server over a specific period. It sets limits on the number of request made to server. These limitations can be user based or request based.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M08SwCqvrjQN4yOHPhdYbA.jpeg" /></figure><h3>Rate Limiting Algorithms</h3><ul><li><strong>Fixed Window</strong></li><li><strong>Sliding Window</strong></li><li><strong>Leaky Bucket</strong></li><li><strong>Token Bucket</strong></li><li><strong>Concurrent Request Limiting</strong></li><li><strong>Quota-Based Limiting</strong></li></ul><h4>Fixed Window</h4><ul><li><strong>How it Works</strong>: Limits the number of requests in a fixed time window (e.g., 100 requests per minute). The counter resets at the end of each window.</li><li><strong>Use Case</strong>: Suitable for services with predictable traffic patterns. For instance, an API that restricts users to 100 requests per minute to avoid overloading a server.</li><li><strong>Example</strong>: A weather API allowing users 100 requests per minute; users exceeding this limit are blocked until the next minute.</li></ul><p>Also it can be customized. As an example, when the window is full then the coming a specific number of requests can queue up. The request in the queue will be processed when the new windows available.</p><h3>Sliding Window</h3><ul><li><strong>How it Works</strong>: It is similar to <strong>Fixed Window</strong>. Tracks requests over a rolling time window instead of a fixed one, counting requests based on the last complete time frame (e.g., last 60 seconds).</li><li><strong>Use Case</strong>: Reduces burstiness at the edges of time windows. Good for APIs requiring smoother request handling, like social media APIs where request loads can vary.</li><li><strong>Example</strong>: A messaging service with a 60-second window that allows only 20 requests, with limits applied continuously over the last 60 seconds to avoid sudden spikes. Also the queue logic can also be implemented in this approach.</li></ul><h3>Leaky Bucket</h3><ul><li><strong>How it Works</strong>: Requests are added to a bucket and processed at a fixed rate. If the bucket overflows, requests are dropped or delayed. This provides a steady request flow.</li><li><strong>Use Case</strong>: Effective for network traffic management or load balancing, where a consistent request rate is crucial to avoid server overloads.</li><li><strong>Example</strong>: An email server processing requests at a fixed rate to avoid congestion, dropping or delaying requests if they exceed the allowable limit.</li></ul><h3>Token Bucket</h3><ul><li><strong>How it Works</strong>: Tokens accumulate in a bucket at a fixed rate, with each request requiring one token. Burst traffic is allowed if tokens are available; otherwise, requests are limited.</li><li><strong>Use Case</strong>: Suitable for systems where occasional burst traffic is permissible, such as video streaming services.</li><li><strong>Example</strong>: A streaming API where users can make bursts of requests (e.g., loading a playlist) but are throttled if they consume too many tokens too quickly.</li></ul><h3>Concurrent Request Limiting</h3><ul><li><strong>How it Works</strong>: Limits the number of simultaneous requests rather than over a time window. Excess requests are queued or dropped until concurrency is reduced.</li><li><strong>Use Case</strong>: Useful for web services or database connections where controlling concurrent usage is more important than requests per second.</li><li><strong>Example</strong>: A file upload service allowing only 3 concurrent uploads per user to prevent server overuse.</li></ul><h3>Quota-Based Limiting</h3><ul><li><strong>How it Works</strong>: Sets a limit over a longer period, such as daily or monthly quotas, ideal for subscription or tiered plans.</li><li><strong>Use Case</strong>: Perfect for subscription-based APIs, where users are allocated a specific number of requests per period.</li><li><strong>Example</strong>: A cloud storage API offering a daily quota of 1,000 requests for free-tier users and 10,000 for paid users, with limits resetting at the end of the day.</li></ul><h3>Which algorithm is better?</h3><p>There is no algorithm that is better than the others. The best one will change every case. It depends on the situation. To make comparison between algorithms you should consider the cost of the endpoint. The cost of an endpoint includes the resource used, for instance time, CPU, I/O, data access.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=859fc1573983" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Policy Based Authorization with MediatR]]></title>
            <link>https://medium.com/@kerimhassan81/policy-based-authorization-with-mediatr-16b089da0b7d?source=rss-e4bbdb6fb885------2</link>
            <guid isPermaLink="false">https://medium.com/p/16b089da0b7d</guid>
            <category><![CDATA[mediatr]]></category>
            <category><![CDATA[policy]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[nets]]></category>
            <dc:creator><![CDATA[Kerim YILDIRIM]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 21:03:14 GMT</pubDate>
            <atom:updated>2023-11-06T21:04:05.411Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is Policy Based Authorization ?</h4><p>Policy based authorization is an authorization type that makes possible to create policies while authorizing the user. Here, some example policies;</p><p><em>User must be following the profile to see its contents if it’s private.</em></p><p><em>You want work a command between the hours 8 AM and 10 AM.</em></p><p><em>User must have bought the course to access its contents.</em></p><p>To create these type of authorization rules we need to use <strong>policy based authorization.</strong></p><h3><strong>How to Implement Policy Based Authorization using MediatR ?</strong></h3><p>In fact, we can create these authorization rules inside the request handler by writing a few methods. <strong>However</strong>, my main point in this writing will be reusability and flexibility. Therefore on the web I searched for how to implement policy based authorization with MediatR. Ultimately, I found a package on GitHub. <a href="https://github.com/AustinDavies/MediatR.Behaviors.Authorization">https://github.com/AustinDavies/MediatR.Behaviors.Authorization</a></p><p>This package allows you to intercept the request coming to the MediatR before it is handled. In my Kanban project, I will try to show how I used it.</p><p>First of all, you should install the package from nuget packages.</p><h4>Configuration</h4><p>After installation we need to register the authorization pipeline with all IAuthorizer.</p><pre>using MediatR.Behaviors.Authorization.Extensions.DependencyInjection;<br><br>    services.AddMediatorAuthorization(Assembly.GetExecutingAssembly());<br>    services.AddAuthorizersFromAssembly(Assembly.GetExecutingAssembly());</pre><h4>Scenerio</h4><p>In my Kanban project, I want the user only get the boards s/he is in. If s/he is <strong>not </strong>in the board then I do not want to return the board details for him/her.</p><h4>Folder Structure</h4><p>In the application layer I created a folder named Requirements (which refers to policies in this package).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*B7De3UF6ov2VuD6dwnm_PQ.png" /><figcaption>Folder Structure</figcaption></figure><p>Under requirements folder I created a class named <em>PersonMustBeAMemberOfBoardRequirement </em>implements IAuthorizationRequirement.</p><pre>public class PersonMustBeAMemberOfBoardRequirement : IAuthorizationRequirement<br>{<br>    <br>}</pre><p>And I added the parameters for Requirement.</p><pre>public class PersonMustBeAMemberOfBoardRequirement : IAuthorizationRequirement<br>{<br>    public int BoardId { get; set; }<br>    public int PersonId { get; set; }<br>}</pre><p>Under of it I created a class named <strong><em>PersonMustBeAMemberOfBoardRequirementHandler </em></strong>which implements<em> </em><strong><em>IAuthorizationHandler</em></strong>&lt;<strong><em>PersonMustBeAMemberOfBoardRequirement</em></strong>&gt;.</p><p><strong>IAuthorizationHandler </strong>interface comes with a method named Handle which will be using when a specified <strong>requirement </strong>needs to be handled. Now here, we’ll write our policy.</p><pre>public class<br>    PersonMustBeAMemberOfBoardRequirementHandler : IAuthorizationHandler&lt;PersonMustBeAMemberOfBoardRequirement&gt;<br>{<br>    private readonly IBoardRepository _boardRepository;<br>    private readonly BoardBusinessRules _boardBusinessRules;<br><br>    public PersonMustBeAMemberOfBoardRequirementHandler(IBoardRepository boardRepository,<br>        BoardBusinessRules boardBusinessRules)<br>    {<br>        _boardRepository = boardRepository;<br>        _boardBusinessRules = boardBusinessRules;<br>    }<br><br>    public async Task&lt;AuthorizationResult&gt; Handle(PersonMustBeAMemberOfBoardRequirement requirement,<br>        CancellationToken cancellationToken = new CancellationToken())<br>    {<br>        Board board = await _boardRepository.GetAsync(x =&gt; x.Id == requirement.BoardId,<br>            include: x =&gt; x.Include(x =&gt; x.PersonBoards).ThenInclude(x =&gt; x.Person));<br>        _boardBusinessRules.DoesBoardExist(board);<br>        List&lt;int&gt; personIds = board.PersonBoards.Select(x =&gt; x.Person).Select(x =&gt; x.Id).ToList();<br><br>        if (personIds.Any(x =&gt; x == requirement.PersonId))<br>            return AuthorizationResult.Succeed();<br>        return AuthorizationResult.Fail(&quot;You should be the member of the board to do this operation&quot;);<br>    }<br>}</pre><p>In here, I am getting the board and person using the properties of <strong>PersonMustBeAMemberOfBoardRequirement </strong>and if the person is <strong>not </strong>in the board members I am returning AuthorizationResult.<strong>Fail</strong>(message). If there is <strong>no problem</strong> in our case simply returning AuthorizationResult.<strong>Succed</strong>().</p><p>Until now, we created a <strong>policy</strong>. However we did not assign this policy to any request. In our scenerio we said that only the member of the board should be able to see board’s contents. So I will create a class under <strong>GetBoardAsWholeQuery </strong>folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*qGv5cqaiXz3F7-FhatHkYQ.png" /><figcaption>Authorizer Class for GetBoardAsWholeQuery request</figcaption></figure><pre>public class GetBoardAsWholeCommandAuthorizer : AbstractRequestAuthorizer&lt;GetBoardAsWholeQuery&gt;<br>{<br>    public override void BuildPolicy(GetBoardAsWholeQuery request)<br>    {<br>        UseRequirement(new PersonMustBeAMemberOfBoardRequirement()<br>        {<br>            BoardId = request.BoardId,<br>            PersonId = request.PersonId<br>        });<br>    }<br>}</pre><p>In here, I created a class under query folder then build the policy. This means when a <strong>GetBoardAsWholeQuery </strong>is sent MediatR first it will build the policy using requirements which we specify using <strong>UseRequirement</strong>() method. If there are <strong>no authorization</strong> issues with our requirement, MediatR will handle the request.</p><p>This part of the code provides <strong>flexibility </strong>to us. Because when we need to create a new MediatR request and it requires a scenerio that only the member of the board authorized, then I can simply create a new Authorizer class for this request and implement <strong>AbstractRequestAuthorizer </strong>for it, then use requirements that we need in BuildPolicy Method.</p><p>Let’s continue with our scenerio. I created a new command named <strong>AddCardToBoard </strong>and here <strong>again </strong>I do not want a person which is not the member of the board to be able to add new card to board. Therefore this request again needs a requirement. <strong>Luckily </strong>we have wroten a requirement which is suitable for this case. So what I need to do is a create a new <strong>authorizer </strong>class <strong>for AddCardToBoardCommand</strong> and use the requirement we wrote before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*dS0Z1Pb3d_5Yvvru5H4TTA.png" /><figcaption>Authorizer Class for AddCardToBoardCommand</figcaption></figure><pre>public class AddCardToBoardCommandAuthorizer : AbstractRequestAuthorizer&lt;AddCardToBoardCommand&gt;<br>{<br>    public override void BuildPolicy(AddCardToBoardCommand request)<br>    {<br>        UseRequirement(new PersonMustBeAMemberOfBoardRequirement()<br>        {<br>            BoardId = request.CardToAddDto.BoardId, PersonId = request.PersonId<br>        });<br>    }<br>}</pre><p>It’s okey we can create policies and use them flexibly. <strong>However</strong>, what happens when we encounter <strong>Authorization.Fail()</strong>? Let’s discuss it.</p><h4>When Authorization Fails</h4><p>By default, when our policy fails, an <strong>UnauthorizedException is thrown</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*cBuUCDOi-6Mj8d27HoNq5Q.png" /><figcaption>Default UnauthorizedHandlerStrategy</figcaption></figure><p>To make sense of this exception we can add a <strong>new exception type in our global exception handler</strong>. In exception handler class in my project I added two new lines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*aC_NyamSB_s3GKwAwLVd2w.png" /><figcaption>ExceptionHandler.cs</figcaption></figure><p>When an <strong>UnauthorizedException thrown its handler method handle it</strong>. See the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*sQpmqZ5z07VpjFd5RckNkA.png" /><figcaption>HandleException for UnauthorizedException</figcaption></figure><p>I <strong>included </strong>status code <strong>403 </strong>and the <strong>exception’s message</strong> in the response details.</p><p>This approach is what you can do basically.</p><p><strong>However</strong>, if you want more <strong>specialization </strong>this also possible. You can write a <strong>new IUnauthorizedResultHandler</strong> implement it you like.</p><pre>public class ExampleUnauthorizedResultHandler : IUnauthorizedResultHandler<br>    {<br>        public Task&lt;TResponse&gt; Invoke&lt;TResponse&gt;(AuthorizationResult result)<br>        {<br>            return Task.FromResult(default(TResponse));<br>        }<br>    }</pre><p>What you can inside of it;</p><p><em>Throwing different a exception type.</em></p><p><em>Add more functionaly etc.</em></p><p>If you <strong>prefer </strong>this way then you need to configure the options during IOC setup like this:</p><pre>services.AddMediatorAuthorization(Assembly.GetExecutingAssembly(), <br>            cfg =&gt; cfg.UseUnauthorizedResultHandlerStrategy(new ExampleUnauthorizedResultHandler));</pre><p>That’s all. Thank you for reading. If you have any question, please do not hesitate to ask. Also I will be happy to be informed if I am mistaken.</p><p>Have a good day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16b089da0b7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are JWTs? How they work? Implementation in .Net Core]]></title>
            <link>https://medium.com/@kerimhassan81/what-are-jwts-how-they-work-implementation-in-net-core-81f67f7aea85?source=rss-e4bbdb6fb885------2</link>
            <guid isPermaLink="false">https://medium.com/p/81f67f7aea85</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[jwt-token]]></category>
            <dc:creator><![CDATA[Kerim YILDIRIM]]></dc:creator>
            <pubDate>Sun, 12 Feb 2023 22:49:30 GMT</pubDate>
            <atom:updated>2023-02-12T22:49:30.241Z</atom:updated>
            <content:encoded><![CDATA[<h3>What are JWTs? How they work? Implementation in .Net Core</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*rlhUs9HLXLXgjAtf2GNKSQ.png" /></figure><h3><strong>What is JWT?</strong></h3><p>JWT also known as <strong>JSON Web Tokens</strong> are commonly used for authentication and authorization purposes. For example, when a user logs into an application, user gets a JWT which contains informations about the user. This information may contain the name, email, roles etc. The created JWT is sent to client side and can be used in the future coming requests to <strong>authenticate</strong> the user and <strong>authorize</strong> access to protected recourses.</p><h3><strong>What are the three parts of JWT?</strong></h3><p>JWT consists of three parts, seperated by dots(‘.’). They are <strong>Header, Payload</strong> and <strong>Signature</strong>.</p><ol><li><strong>Header</strong></li></ol><pre>{<br>  &quot;alg&quot;: &quot;HS512&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><p>Header defines the <strong>type </strong>of the token and which <strong>signing algorithm</strong> is used to sign the token. Nothing more! In this example HMAC-SHA512 algorithm is used and the type of the token is JWT.</p><p>2. <strong>Payload</strong></p><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;iat&quot;: 1516239022,<br>  &quot;name&quot;: &quot;kerim yildirim&quot;,<br>  &quot;email&quot;: &quot;kerimyildirimtest@gmail.com&quot;,<br>  &quot;exp&quot;: 1516239622<br>}</pre><p>We can say that Payload is the data layer which <strong>contains datas we want to hide</strong> in the JWT. “<strong>sub</strong>” which refers to subject should be an unique identifier for the user. “<strong>iat</strong>” (issued at) is the seconds since Unix epoch (1970–01–01 00:00:00 UTC). “<strong>exp</strong>”(expiration time) is like “<strong>iat</strong>” but this it refers not creating but expiration. “<strong>name</strong>”, “<strong>email</strong>” are some properties that used in a JWT. We can increase these examples.</p><p>3. <strong>Signature</strong></p><pre>HMACSHA512(<br>  base64UrlEncode(header) + &quot;.&quot; +<br>  base64UrlEncode(payload),<br>  &quot;mysecretkey&quot;<br>  <br>)</pre><p>Signature is the part makes JWTs <strong>safeful</strong>. This part consist by concanating the parts header and payload parts wiht a “.”. Then using the algorithm the defined at the header part with a secretkey you desire. You should choose a <strong>powerful secret key</strong>. In some signing algorithm <strong>errors </strong>may happen due to your secret key.</p><p>This is an example of a encoded JWT.</p><pre>eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.<br>eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNTE2MjM5MDIyLCJuYW1lIjoia2VyaW0geWlsZGlyaW0iLCJlbWFpbCI6ImtlcmlteWlsZGlyaW10ZXN0QGdtYWlsLmNvbSIsImV4cCI6MTUxNjIzOTYyMn0.<br>0wRj5MINUE7HxIOVqlaBU0M2FAWa4ng1trGrHsu7zSqrmwPK_6SzQWYM1A8Ahsvxq_smlVXzmPufhT9-0eWKFA</pre><p><strong>Realize </strong>that there is a <strong>dot </strong>(“.”) between the parts.</p><p><strong>How JWT validation works basically?</strong></p><p>An example scenerio, client wants to access protected data. To access this data client sent you a JWT. And we want to be sure that the JWT is secure. How can we be sure that is secure?</p><ol><li>Decode the encoded Header and Payload parts to get JSON form of these parts.</li><li>We create a new Signature with the informations given Header and Payload. For example Header will say “the used algorithm is HS256 in this token”, Payload will say “the datas inside this token are …..”.</li><li>Create a new Signature using the information in the given Payload and Header with using the securitykey which already define in our application.</li><li>Finally, compare two signatures(one you created with your own secretkey and one you receive from client) one by one.</li><li>If there is any mismatch then the received JWT is not secured. Do not let the do thing wants to do.</li></ol><p>This seems a lot. Right ? However do not worry there are bunches of libraries that does this process. Knowing what is done behind is important I think.</p><p>An implementation of JWT in .Net Core</p><p>I have created a <strong>WebAPI </strong>Project. Firstly, I am creating my model under a folder named “models”. I will try to make it simplier as I can.</p><p>I created a class named <strong>User</strong>.</p><pre>public class User<br>    {<br>        public int Id { get; set; }<br>        public string Username { get; set; }<br>        public string Email { get; set; }<br>        public string Name { get; set; }<br>    }</pre><p>Then created a folder named <strong>Helpers</strong>. Inside of it created a <strong>static </strong>class named <strong>JwtHelper</strong>.</p><pre>public static class JwtHelper<br>    {<br><br>    }</pre><p>Before writing any code inside of this class firstly, we should add “<strong>System.IdentityModel.Tokens.Jwt</strong>” from NugetPackages to our WebAPI project.</p><p>After adding the package we can create a method which returns a JWT.</p><pre>public static string CreateJwtToken(User user)<br>        {<br><br>        }</pre><p>To create a JWT first we should create a <strong>JwtSecurityToken </strong>instance. To create a <strong>JWTSecurityToken</strong> we need these parametres; i<em>ssuer, audience, claims, notBefore, expires</em> and <em>signingCredentials</em>. Before creating an instance let’s create these parametres.</p><pre>public static string CreateJwtToken(User user)<br>        {<br>            string issuer = &quot;kerimyildirim.com&quot;;<br>            string audience = &quot;thismyaudience.com&quot;;<br>        }</pre><p>“<em>issuer</em>” refers to the <strong>source </strong>of JwtToken and “<em>audience</em>” refers to the <strong>on which applications</strong> this jwt is valid.</p><pre>public static string CreateJwtToken(User user)<br>        {<br>            string issuer = &quot;kerimyildirim.com&quot;;<br>            string audience = &quot;thismyaudience.com&quot;;<br>            List&lt;Claim&gt; claims = new List&lt;Claim&gt;(); //using System.Security.Claims;<br>            Claim claim1 = new(ClaimTypes.Name, user.Name);<br>            Claim claim2 = new(ClaimTypes.NameIdentifier, user.Id.ToString());<br>            Claim claim3 = new(ClaimTypes.Email, user.Email);<br>            Claim claim4 = new(ClaimTypes.Role, &quot;admin&quot;);<br>            claims.Add(claim1);<br>            claims.Add(claim2);<br>            claims.Add(claim3);<br>            claims.Add(claim4);<br>        }</pre><p><em>Claims </em>contains informations about the user. That can be <strong>email, name, id</strong> or <strong>roles </strong>such as <strong>admin</strong>, <strong>moderator, etc</strong>. There are so many ClaimTypes.</p><pre>public static string CreateJwtToken(User user)<br>        {<br>            string issuer = &quot;kerimyildirim.com&quot;;<br>            string audience = &quot;thismyaudience.com&quot;;<br>            List&lt;Claim&gt; claims = new List&lt;Claim&gt;(); //using System.Security.Claims;<br>            Claim claim1 = new(ClaimTypes.Name, user.Name);<br>            Claim claim2 = new(ClaimTypes.NameIdentifier, user.Id.ToString());<br>            Claim claim3 = new(ClaimTypes.Email, user.Email);<br>            Claim claim4 = new(ClaimTypes.Role, &quot;admin&quot;);<br>            claims.Add(claim1);<br>            claims.Add(claim2);<br>            claims.Add(claim3);<br>            claims.Add(claim4);<br>            DateTime notBefore = DateTime.UtcNow;<br>            DateTime expires = DateTime.UtcNow.AddMinutes(10);<br>        }</pre><p><em>notBefore </em>means this token is valid <strong>since </strong>this Date. <em>expires </em>refers to this token is valid <strong>until </strong>this Date.</p><p>The last but not least parameter to construct <strong>JwtSecurityToken </strong>is <strong>SigningCredentials</strong>.</p><pre>string secretKey = &quot;myverysecretkey&quot;;<br><br>SecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));<br>SigningCredentials signingCredentials = new(securityKey, SecurityAlgorithms.HmacSha512Signature);</pre><p>To create an instance of <strong>SigningCredentials </strong>we need a <strong>SecurityKey </strong>instance and a <strong>SecurityAlgorithm</strong>. We create a <strong>SecurityKey </strong>just simply this 2 lines of code:</p><pre>string secretKey = &quot;myverysecretkey&quot;;<br><br>SecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));</pre><p>It is <strong>better </strong>to pick a <strong>long </strong>and <strong>complex </strong>secret key for <strong>safety</strong>. And you should <strong>not </strong>write your secret key here like this. You should put it a place <strong>more safe </strong>than here. (Maybe in your configuration file or as a enviromental variable)</p><p>After that you can create a <strong>SigningCredentials </strong>using the <strong>securityKey </strong>we created above and a type of <strong>SecurityAlgorithm</strong>. In this example I chose <strong>HMAC-SHA512</strong>.</p><pre>SigningCredentials signingCredentials = new(securityKey, SecurityAlgorithms.HmacSha512Signature);</pre><p>Finally, we can construct our <strong>JwtSecurityToken</strong>.</p><pre>JwtSecurityToken token = new JwtSecurityToken(issuer,audience,claims,notBefore,expires,signingCredentials);</pre><p>To get the <strong>string form of the token</strong>, we need <strong>JwtSecurityTokenHandler</strong>. Using <strong>WriteToken </strong>method we can get the token.</p><pre>JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();<br>return jwtSecurityTokenHandler.WriteToken(token);</pre><p>To test the code, I will create a controller named TestController. Create a <strong>pseudo user </strong>then create <strong>JWT </strong>token for the user.</p><pre>[Route(&quot;api/[controller]&quot;)]<br>    [ApiController]<br>    public class TestController : ControllerBase<br>    {<br>        [HttpGet]<br>        public async Task&lt;IActionResult&gt; GetToken()<br>        {<br>            User user = new()<br>            {<br>                Id = 1,<br>                Username = &quot;ashwor&quot;,<br>                Email = &quot;kerimhassan81@gmail.com&quot;,<br>                Name = &quot;Kerim Hasan Yildirim&quot;<br>            };<br>            string token = JwtHelper.CreateJwtToken(user);<br>            return Ok(token);<br>        }<br>    }</pre><p><strong>Run </strong>the application. Go to localhost:7175/swagger/index.html.Make the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_L4vOIKITYCuFQoS9NqPFA.png" /></figure><p>I get the following error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqhMfUq8tFuZBvFNLOvzfQ.png" /></figure><p>As earlier I said that short security keys may cause problems. Here is one example. I get this error because the security algorithm I chose before requires<strong> a key size of at least ‘128’ bits</strong>. Mine was ‘<strong>myverysecretkey</strong>’ which consist of <strong>15 </strong>characters each of <strong>8 bits</strong>. So my secret key is <strong>120 bit</strong>. If I <strong>add another character, </strong>it makes<strong> 128 bit </strong>and I shouldn’t get this exception. Let’s try ‘<strong>myverysecretkey1</strong>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYYdZaKZMa75WIL3dj9bmw.png" /></figure><p>Response code is 200. And the token is in the response body. <strong>However </strong>how can we know that they are the informations we sent inside of it? So let’s check it in <a href="http://jwt.io/">jwt.io</a>. jwt.io is a website that you create your JWTs and mess around with them and understand better how JWTs work better. This what we get when we open the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8QwOAM7zrQGQ2ZyLaW9dw.png" /><figcaption>jwt.io</figcaption></figure><p>After pasting our JWT token. We get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8IUOywXSHW7gL9iHYUc-Qw.png" /></figure><p>Everything we passed into our token is here. This is how you create a JWT token and inspect it.</p><p>I tried to explain the JWTs and how they work basically as clear as I can. I am sharing this <a href="https://github.com/ashwor11/JwtIntroduction">repository</a>.</p><p>In the following days I’ll come with a new article explains how to do Authorization and Authentication with JWT.</p><p>If you have any question you can ask. I’ll be glad to help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81f67f7aea85" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>