<?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 Tanmay Saxena on Medium]]></title>
        <description><![CDATA[Stories by Tanmay Saxena on Medium]]></description>
        <link>https://medium.com/@tanmaysaxena2904?source=rss-72163c738a76------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cG_RPzhZYqiILCP3</url>
            <title>Stories by Tanmay Saxena on Medium</title>
            <link>https://medium.com/@tanmaysaxena2904?source=rss-72163c738a76------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:08:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanmaysaxena2904/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[Role of Tokens in Authentication and Authorization and JWT]]></title>
            <link>https://medium.com/@tanmaysaxena2904/role-of-tokens-in-authentication-and-authorization-and-jwt-a18929891f4b?source=rss-72163c738a76------2</link>
            <guid isPermaLink="false">https://medium.com/p/a18929891f4b</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[jwt-token]]></category>
            <dc:creator><![CDATA[Tanmay Saxena]]></dc:creator>
            <pubDate>Sat, 30 Mar 2024 07:16:54 GMT</pubDate>
            <atom:updated>2024-03-30T07:16:54.393Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>token</strong> typically refers to a piece of data that serves as a proof of authentication or authorization. Tokens are often used in authentication systems to verify the identity of users and grant them access to restricted resources or functionalities. And a token can be a plain string of format <strong>universally unique identifier(UUID)</strong> or it can be a of type <strong>JSON Web Token(JWT)</strong> usually that gets generated when the user is authenticated for the first time during login.</p><p>On every request to a restricted resource, the client sends the access token in the query string or Authorization header. The server then validates the token and, if it’s valid, returns the secure resource to the client. Lets understand this with the help of below diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suSPk8G3U5UFfIuRsejvSQ.png" /></figure><p>Token offers several advantages particularly in the realms of security, scalability and user experience. Below are some key advantages:</p><ol><li>Token helps us not to share the credentials for every request which is a security risk to make credentials send over the network frequently.</li><li>Tokens can be <strong>invalidated</strong> during any<strong> suspicious activities</strong> without invalidating the user credentials.</li><li><strong>Statelessness</strong>: Tokens enable stateless authentication reduces server overhead, simplifying scalability across multiple servers or scaling horizontally.</li><li><strong>Offline Access and Scalability</strong>: Refresh tokens, like in OAuth 2.0, ensure users can access resources offline, improving reliability and scalability.</li><li><strong>Reusability: </strong>We can have many separate servers, running on multiple platforms and domains, reusing the same token for authenticating the user.</li></ol><p>Now lets go through some of the type of tokens and their functionalities and how it eases our life.</p><ol><li><strong>CSRF Token</strong> : CSRF tokens are used to protect against Cross-Site Request Forgery attacks by ensuring that the request originated from the expected source. These tokens are typically included in forms or requests and validated on the server-side to prevent unauthorized actions.<br>A CSRF token is typically a randomly generated string of characters, often encoded in hexadecimal or base64 format. It may look something like this: <strong>b8c93fc2–85d5–4e5e-a742–9e7dcb94c3a7 o</strong>r it might be encoded in <strong>base64</strong> format: <strong>NDI5NzgxMzE1NDg3NzUyNDE5MzM2NjExOTk4MjE3NDk4Njg0NzQzNDM3NTc5Nzc4NzYxNTU2Mzk=<br></strong>These tokens are generated by the server and then embedded into forms or included in HTTP headers as a means of protection against CSRF attacks. Each token is unique and tied to a specific user session or request, ensuring that malicious requests from other sites cannot be successfully executed.</li><li><strong>Session Tokens: </strong>Session tokens are unique identifiers assigned to each user session on a website. They are typically generated by the server when a user logs in or visits the website for the first time. They allow the server to associate incoming requests with the correct user session and maintain statefulness across multiple interactions. <strong>JSESSIONID </strong>is one of the session tokens which is used in java web applications so in this a server creates ad new session id and typically store it as a cookie in user browser. The JSESSIONID is then included in subsequent requests to the server, allowing the server to identify and associate each request with the correct session.<br><strong>JSESSIONID=ABCDEF1234567890ABCDEF1234567890</strong></li></ol><blockquote><strong>JSON Web Tokens(JWT) : </strong>JWT is a token implementation which will be in the JSON format and designed to use for the web requests. JWT is the most common and favorite token type that many systems use these days due to its special features and advantages. JWT tokens can be used both in the scenarios of Authorization/Authentication along with information exchange which means you can share certain user related data in the token itself which will reduce the burden of maintaining such details in the sessions on the server side.<br>A JWT token has 3 parts each separated by a dot(.). Below is a sample JWT token :<br><strong><em>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.</em>SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</strong></blockquote><p>a. <strong>Header</strong> : <strong><em>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9</em></strong></p><p>In the <strong>header</strong>, we store<strong> metadata/info</strong> related to the token. If I chose to sign the token, the header contains the name of the algorithm that generates the signature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*Ao7FZug62so5dc0qGlK3cw.png" /></figure><p><em>b.</em><strong><em>Payload:</em></strong><em>eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWf0IjoxNTE2MjM5MDIyfQ</em></p><p>In the <strong>body</strong>, we can <strong>store details related to user, roles etc</strong>. which can be used later for Authentication and authorization. Though there is no such limitation what we can send and how we can send in the body, but we should put our best efforts to keep it as light as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*5YKuBTXyuFxeSYrvZUJHEQ.png" /></figure><p>c. Signature(Optional) : <strong>SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</strong></p><p>The last part of the token is the digital signature. This part can be optional if the party that you share the JWT token is internal and that someone who you can trust but not open in the web.</p><p>But if you are sharing this token to the client applications which will be used by all the users in the open web then we need to make sure that no one changed the header and body values like Authorities, username etc.</p><p>To make sure that no one tampered the data on the network, we can send the signature of the content when initially the token is generated. To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.</p><p>For example if you want to use the <strong>HMAC SHA256 algorithm</strong>, the signature will be created in the following way:</p><p><strong>HMACSHA256 (base64UrlEncode(header) + “.” + base64UrlEncode(payload), secret)</strong></p><p>The signature is used to verify the message wasn’t changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.</p><p>See you in another article. Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a18929891f4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Security — The Security Filter Chain]]></title>
            <link>https://medium.com/@tanmaysaxena2904/spring-security-the-security-filter-chain-e09e1f53b73d?source=rss-72163c738a76------2</link>
            <guid isPermaLink="false">https://medium.com/p/e09e1f53b73d</guid>
            <category><![CDATA[spring-security]]></category>
            <dc:creator><![CDATA[Tanmay Saxena]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 13:19:42 GMT</pubDate>
            <atom:updated>2023-10-10T13:19:42.957Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Security — The Security Filter Chain</h3><p>In this article, we are going to learn about spring security, its internal flow and filter chain.</p><p><strong>Spring Security i</strong>s a powerful and highly customizable security framework for building secure applications in the Java ecosystem, particularly within the Spring Framework. Spring Security framework also <strong>handles the most common security vulnerabilities like CSRF, CORS</strong> etc. So for any security vulnerabilities that are identified in the market on day to day basis, the spring security team they’re going to patch or update the framework immediately. Using spring security we can secure our pages/API paths, method level security etch with minimum configurations easily. Also Spring security supports various standards of security to implement authentication like username/password authentication by default, JWT tokens, OAuth2 etc.</p><p>Before getting to spring security internal flow lets go through typical scenario inside a web application. So any java web application accepts request and sends response through HTTP protocol because browsers can only understand HTTP protocols. But the java code cannot understand those HTTP protocol requests there is need of someone in the middle who ca convert the received HTTP message into an HTTP solid request object, this middle man is called servlets or web servers like Apache Tomcat but because of its complex nature no one uses them directly. So to make the job easy Springboot came into picture which creates servlets internally and handles complex logic related to servlets on its own.</p><p>Just like servlets we have <strong>filters</strong> inside the web application which we use to define any pre logic work before actual business logic executes. Lets understand this scenario with the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WVdzrsZoGsew-OMYWE2_g.png" /></figure><p>Here the client application is trying to send a request to the backend web application, which I have deployed inside a solid container like Tomcat. So in between my client and actual servlets, we can use filters. And these filters are responsible to intercept each and every request of the web application. And they execute what logic we have defined inside these filters. It is almost like a <strong>Middleware</strong> and it has the name of <strong>FilterChain </strong>because of the <strong>chain of responsibility pattern</strong>. The HTTP request going to pass through it and the response also pass through the filters based on the way that it is going. Then finally the request is routed to the controllers by this servlet. Servlet takes the HTTP request and does some kind of action to it depending on the Java code.</p><p>Before deep diving into filter chain lets go through spring security internal flow. Below is the diagram demonstrates the flow and explains why filters are important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5Am0prlQZKy1ijZcAZeLg.png" /></figure><p>Let us understand what does each component do.</p><p><strong>Spring Security Filters</strong><br>A series of Spring Security filters intercept each request &amp; work together to identify if Authentication is required or not. If authentication is<br>required, accordingly navigate the user to login page or use the existing details stored during initial authentication.</p><ul><li><strong>Authentication : </strong>Filters like UsernamePasswordAuthenticationFilter will extract username/ password from HTTP request &amp; prepare Authentication type object<br>Because Authentication is the core standard of storing authenticated user details insdie Spring Security framework.</li><li><strong>AuthenticationManager : </strong>Once received request from filter, it delegates the validating of the user details to the authentication providers available. Since there can be<br>multiple providers inside an app, it is the responsibility of the AuthenticationManager to manage all the authentication providers available.</li><li><strong>AuthenticationProvider : </strong>AuthenticationProviders has all the core logic of validating user details for authentication</li><li><strong>UserDetailsManager/UserDetailsService : </strong>It helps in retrieving, creating, updating, deleting the User Details from the DB/storage systems.</li><li><strong>PasswordEncoder : </strong>Service interface that helps in encoding &amp; hashing passwords. Otherwise we may have to live with plain text passwords &amp;</li><li><strong>SecurityContext : </strong>Once the request has been authenticated, the Authentication will usually be stored in a thread-local SecurityContext managed by the SecurityContextHolder. This helps during the upcoming requests from the same user.</li></ul><p>Now its time to deep dive into filter chain. The name <strong>filterchain </strong>proposes that you have a <strong>sequence of filters</strong>, with each filter doing some handling and afterward giving to the following in succession, so each object has a chain member to highlight the following filter in the sequence, which gets called after the filter has played out its own handling. The rearward in the arrangement will then presumably have invalid as the chain worth or it realizes on its own that it is the final remaining one in the sequence.</p><p>This process internally invokes <strong>doFilter </strong>of the next filter in the filter chain, and, when the chain is over, it invokes the target servlet. All filters are chained (in the order of their definition in web.xml). The <strong>chain.doFilter()</strong> is proceeding to the next element in the chain. The last element of the chain is the target resource/servlet.</p><p>Following are Core Components of the Spring Security Filter Chain:</p><ol><li><strong>Security Filter Chain</strong>: The security filter chain is a sequence of filters that Spring Security applies to each incoming HTTP request. These filters work together to perform various security-related tasks.</li><li><strong>Security Filter Chain Configuration</strong>: You define the security filter chain and its configuration in your Spring Security configuration class. This class typically extends SecurityConfigurerAdapter and overrides configure(HttpSecurity http) to specify how the filter chain should behave.</li><li><strong>Security Filters</strong>: These are individual filters that perform specific security tasks.</li></ol><p>Some of the core security filters include:</p><ul><li><strong>Authentication Filter</strong>: Responsible for handling user authentication.</li><li><strong>Authorization Filter</strong>: Enforces access control policies and checks whether a user is authorized to access a resource.</li><li><strong>Exception Handling Filter</strong>: Manages exceptions and handles security-related errors.</li><li><strong>CSRF (Cross-Site Request Forgery) Filter</strong>: Protects against CSRF attacks.</li><li><strong>Session Management Filter</strong>: Manages user sessions and their associated security contexts.</li></ul><p>Let’s implement this logic to get a perfect idea of what is this Security Filter Chain. Now create a folder called <strong>config </strong>in your project and create a class called <strong>ProjectSecurityConfig</strong>.</p><p>This is the class we use to add our filter chain. Now add the annotation <strong>@Configuration </strong>to let the spring boot this is a configuration class and this needs to be added to the <strong>Bean Context</strong>.</p><p><strong>Configuring HttpSecurity</strong></p><p>In Spring Security 5.4 they introduces the ability to configure HttpSecurity by creating a SecurityFilterChain bean.</p><p>Below is an example configuration by registering aSecurityFilterChain bean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Z7z622Xl4caLaQshJXSZQ.png" /></figure><p>In the configuration we are securing endpoints like /myAccounts, /myCards, /myLoans and /myBalance i.e user cannot access these without successfully logged in but endpoints like /notices and /contacts can be accessed.</p><p>We can always check the registered filters inside the spring security with below configurations but this is not a recommended in production.</p><ol><li><strong>@EnableWebSecurity(debug=true)</strong>- this will enable the logging of security details.</li><li>Enable logging of the details by adding the below property in application.properties.</li></ol><p><strong>logging.level.org.springframework.security.web.FilterChainProxy=true</strong></p><p>Now its time to look on how to create a custom filter. So ome can create a custom filter by implementing the Filter interface from the jakarta.servlet package. Post that we need to override the<strong> doFilter() </strong>method to have our own custom logic. This method accepts three parameters the <strong>ServletRequest, ServletResponse andFilterChain.</strong></p><p><strong>ServletRequest —</strong> It represents the HT TP request. We use the ServletRequest object to retrieve details about the request from the<br>client.</p><p><strong>ServletResponse —</strong> It represents the HTTP response. We use the ServletResponse object to modify the response before sending it<br>back to the client or further along the filter chain.</p><p><strong>FilterChain — </strong>The filter chain represents a collection of filters with a defined order in which they act. We use the FilterChain object<br>to forward the request to the next filter in the chain.</p><p>Each position of the filter is an index (a number) and <br>one can add a new filter to the spring security chain either before, after, or at the position of a known one.</p><p>Below are the methods available to configure a custom filter in the spring security flow:</p><ul><li><strong>addFilterBefore(filter, class) — </strong>adds a filter before the position of the specified filter class</li><li><strong>addFilterAfter(filter, class) — </strong>adds a filter after the position of the specified filter class.</li><li><strong>addFilterAt(filter, class) —</strong> adds a filter at the location of the specified filter class.</li></ul><p>Now lets create a custom filter using addFilterAfter method which will simply log about the successful authentication and the authority details of the logged in user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*tCRXxOerZs3I9t0vAC1pdQ.png" /></figure><p>After creating the custom authentication filter we need to inject this filter in spring security filter chain. Please refer the below snapshot of code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9aIt1GNgBUrVQT116wMwA.png" /></figure><p>Here the addFilterAfter method takes two arguments in which the first one is the custom filter we need to invoke and the second argument we need to pass what is a Spring Security internal filter that we need to consider. So the internal filter that we are considering here is BasicAuthenticationFilter.class.</p><p>In this article, we looked at the basic concept that applies to spring security. As we have seen, spring provides a lot of flexibility and allows us to customize security for complex applications. See you in another article.</p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e09e1f53b73d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>