<?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 amir razavi on Medium]]></title>
        <description><![CDATA[Stories by amir razavi on Medium]]></description>
        <link>https://medium.com/@amirrazavi_49547?source=rss-d06c92562dc0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hSw17Atashcri52eDbXbGQ.jpeg</url>
            <title>Stories by amir razavi on Medium</title>
            <link>https://medium.com/@amirrazavi_49547?source=rss-d06c92562dc0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 13:05:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amirrazavi_49547/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[Understanding Request/Response Flow in NestJS ]]></title>
            <link>https://medium.com/@amirrazavi_49547/request-response-execution-order-in-nestjs-9d76fb550e49?source=rss-d06c92562dc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d76fb550e49</guid>
            <dc:creator><![CDATA[amir razavi]]></dc:creator>
            <pubDate>Sat, 29 Jun 2024 19:14:02 GMT</pubDate>
            <atom:updated>2024-06-29T19:17:39.364Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Understanding Request/Response Flow in NestJS 🚀</strong></p><p>In NestJS, requests and responses go through several steps to make sure everything works smoothly. Let’s break down these steps in a simple way with emojis! 🌟</p><h3>1. Middleware 🛤️</h3><p>First, the request passes through <strong>Middleware</strong>. Think of middleware as checkpoints that can modify the request before it goes further.</p><ul><li><strong>CORS</strong>: 🌐 Handles access from different domains.</li><li><strong>Body-Parser</strong>: 📝 Turns request data into a usable format.</li><li><strong>Morgan</strong>: 📋 Logs details of each request.</li><li><strong>JWT Decoding</strong>: 🔑 Decodes tokens to get user info.</li></ul><pre>app.use(cors());<br>app.use(bodyParser.json());<br>app.use(morgan(&#39;dev&#39;));<br>app.use(jwtMiddleware);</pre><h3>2. Guards 🚧</h3><p>After Middleware, Guards come into play. Guards control access to routes and check whether the user has permission to access the specific handler. This layer is primarily used for authentication and authorization logic.</p><pre>@Injectable()<br>export class AuthGuard implements CanActivate {<br>  canActivate(context: ExecutionContext): boolean {<br>    const request = context.switchToHttp().getRequest();<br>    return validateRequest(request);<br>  }<br>}</pre><h3>3. Interceptors (Before next.handle()) 🔄</h3><p>Interceptors play a significant role in processing requests and responses. At this stage, code before next.handle() is executed. This layer is used to modify or transform requests before reaching the main handler.</p><pre>@Injectable()<br>export class LoggingInterceptor implements NestInterceptor {<br>  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {<br>    console.log(&#39;Before...&#39;);<br>    return next.handle().pipe(<br>      tap(() =&gt; console.log(&#39;After...&#39;)),<br>    );<br>  }<br>}</pre><h3>4. PipeTransform 🚰</h3><p>Pipes are used to transform and validate incoming data. This layer modifies and validates the data before it reaches the main handler.</p><pre>@Injectable()<br>export class ValidationPipe implements PipeTransform {<br>  transform(value: any, metadata: ArgumentMetadata) {<br>    if (!isValid(value)) {<br>      throw new BadRequestException(&#39;Validation failed&#39;);<br>    }<br>    return value;<br>  }<br>}</pre><h3>5. Handler 🛠️</h3><p>This stage is the handler itself, which processes the request and returns the appropriate response. This layer is where the main logic of your application is executed.</p><pre>@Controller(&#39;cats&#39;)<br>export class CatsController {<br>  @Get()<br>  findAll(): string {<br>    return &#39;This action returns all cats&#39;;<br>  }<br>}</pre><h3>6. Interceptors (Inside next.handle()) 🔄</h3><p>After the handler is executed, the second phase of Interceptors, which includes the code inside next.handle(), runs. This part is used for final processing of the response and sending it back to the client.</p><h3>Exception Filters 🚨</h3><p>Finally, Exception Filters are used to handle exceptions and errors that occur throughout the execution of the application. This layer allows you to manage application errors in a centralized and comprehensive manner.</p><pre>@Catch(HttpException)<br>export class HttpErrorFilter implements ExceptionFilter {<br>  catch(exception: HttpException, host: ArgumentsHost) {<br>    const ctx = host.switchToHttp();<br>    const response = ctx.getResponse&lt;Response&gt;();<br>    const status = exception.getStatus();<br><br>    response.status(status).json({<br>      statusCode: status,<br>      timestamp: new Date().toISOString(),<br>      message: exception.message,<br>    });<br>  }<br>}</pre><h3>Conclusion 🎉</h3><p>In NestJS, the flow of requests and responses goes through multiple processing layers, each playing a specific role in access control, data processing, and error management. Using Middleware, Guards, Interceptors, Pipes, Handlers, and Exception Filters allows for easy and flexible implementation and management of application logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d76fb550e49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding XSS (Cross-Site Scripting) ]]></title>
            <link>https://medium.com/@amirrazavi_49547/understanding-xss-cross-site-scripting-7e305f423580?source=rss-d06c92562dc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e305f423580</guid>
            <dc:creator><![CDATA[amir razavi]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 17:29:26 GMT</pubDate>
            <atom:updated>2024-06-28T17:29:26.898Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction 📜</h4><p>Cross-Site Scripting, or XSS, is a common attack in the web world that allows bad actors to inject harmful scripts into web pages. This can let them access sensitive user information or alter the site’s behavior. XSS exploits a flaw in the “Same-Origin Policy” (SOP), an important web security principle. Let’s dive into the types of XSS and how they work.</p><h4>SOP and How XSS Breaks It 🛡️🔓</h4><p>The Same-Origin Policy (SOP) is a mechanism that browsers use to prevent interactions between resources from different origins. This means scripts from one origin can’t access data or scripts from another. But with XSS, attackers inject harmful scripts into a web page, bypassing this policy and gaining full access to the victim site’s resources.</p><h4>Types of XSS 🕵️‍♂️</h4><p><strong>1.Normal XSS</strong></p><ul><li><strong>Stored XSS</strong> 💾: Harmful data is saved by the server and sent to any user who opens the infected page later. For example, an attacker can store a malicious message in a contact form, which is later displayed to the site admin.</li><li><strong>Reflected XSS</strong> 🔄: Harmful data is immediately returned to the user without being stored on the server. This often happens through malicious links that include harmful scripts, directing users to an infected page.</li></ul><p><strong>2. DOM-based XSS</strong> 📜</p><ul><li><strong>Stored DOM XSS</strong> 🗄️: The harmful code is executed on the client side by JavaScript and may come from data previously stored by the server.</li><li><strong>Reflected DOM XSS</strong> 🚀: Similar to stored, but the harmful data is instantly received from user inputs and executed by JavaScript.</li></ul><p><strong>3. Blind XSS</strong> 👁️‍🗨️ In this type of attack, the attacker runs harmful code without seeing the result directly. The code might be executed somewhere else and at a different time, like in a site’s admin panel. Hackers use techniques like “Out of Band” (OOB) to detect if a site is vulnerable.</p><h4>Conclusion 🎯</h4><p>XSS attacks can be very harmful, leading to unauthorized access to sensitive user information or unwanted changes in site functionality. By understanding the different types of XSS and their attack mechanisms, web developers can better protect their sites and users from these threats. Implementing security measures like sanitizing user inputs, using Content Security Policy (CSP), and regularly updating software can help reduce the risks of XSS.</p><p>Stay safe and keep your websites secure! 🛡️🌟</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e305f423580" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Web Security: SOP, SameSite Cookies, and CORS]]></title>
            <link>https://medium.com/@amirrazavi_49547/understanding-web-security-sop-samesite-cookies-and-cors-fec241fad3d3?source=rss-d06c92562dc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fec241fad3d3</guid>
            <dc:creator><![CDATA[amir razavi]]></dc:creator>
            <pubDate>Thu, 27 Jun 2024 21:22:27 GMT</pubDate>
            <atom:updated>2024-06-27T21:22:27.742Z</atom:updated>
            <content:encoded><![CDATA[<p>Web security helps keep your data safe and your web applications running smoothly. In this article, I’ll explain three key concepts in web security: Same-Origin Policy (SOP), SameSite cookies, and Cross-Origin Resource Sharing (CORS). We’ll also see how they help protect against attacks like CSRF.</p><h4>Same-Origin Policy (SOP) 🔒</h4><p>The Same-Origin Policy (SOP) is like a security guard for your browser. It makes sure that a web page can only request information from the same origin (the same protocol, domain, and port). This means a page on http://example.com can’t fetch data from http://anotherdomain.com. This guard stops bad actors from stealing sensitive data, protecting you from attacks like Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF).</p><h4>SameSite Cookies 🍪</h4><p>SameSite cookies are a way to control how cookies are shared across different sites. Cookies can store your login information or preferences. There are three levels of security for SameSite cookies:</p><ul><li><strong>Strict</strong>: The cookie is only sent with requests from the same site. It’s very secure but can be a bit restrictive.</li><li><strong>Lax</strong>: The cookie is sent when you navigate to a different site (e.g., clicking a link), but not with requests made by third-party scripts. It’s a good balance between security and usability.</li><li><strong>None</strong>: The cookie is sent with all requests, even across different sites. This requires the Secure attribute, meaning it can only be sent over HTTPS.</li></ul><h4>Cross-Origin Resource Sharing (CORS) 🌐</h4><p>Sometimes, you need to fetch resources from different origins. This is where Cross-Origin Resource Sharing (CORS) comes in. CORS allows servers to specify who can access their resources from different origins using HTTP headers.</p><p>How CORS Works</p><p>CORS uses specific HTTP headers to control access:</p><ul><li><strong>Access-Control-Allow-Origin</strong>: Tells the browser which origin can access the resource. It can be a specific origin like http://example.com or * to allow any origin.</li><li><strong>Access-Control-Allow-Methods</strong>: Lists the HTTP methods (e.g., GET, POST) allowed when accessing the resource.</li><li><strong>Access-Control-Allow-Headers</strong>: Lists the headers that can be used in the actual request.</li><li><strong>Access-Control-Allow-Credentials</strong>: Allows the request to include user credentials (e.g., cookies).</li></ul><p>Here’s a simple Node.js example to set up CORS:</p><p>const allowedOrigins =[‘http://localhost:5500&#39;,‘http://127.0.0.1:5500&#39;,‘http://example.com&#39;];</p><p>app.use((req, res, next) =&gt; {<br> const origin = req.headers.origin;<br> if (allowedOrigins.includes(origin)) {<br> res.setHeader(‘Access-Control-Allow-Origin’, origin);<br> res.setHeader(‘Access-Control-Allow-Methods’, ‘GET,POST,PUT,DELETE,OPTIONS’);<br> res.setHeader(‘Access-Control-Allow-Credentials’, true);<br> }<br> next();<br>});</p><p>In this example, the server checks if the request’s origin is allowed and sets the appropriate CORS headers if it is. The Access-Control-Allow-Credentials header is important for requests with credentials like cookies. This header must be set to true and the Access-Control-Allow-Origin cannot be a wildcard (*).</p><h4>Simple Requests and Preflight Requests 🚦</h4><p>CORS requests come in two types: simple and preflighted.</p><ul><li><strong>Simple Requests</strong>: These use methods like GET, POST, or HEAD and have specific headers (e.g., Content-Type set to application/x-www-form-urlencoded, multipart/form-data, or text/plain). These do not need a preflight request.</li><li><strong>Preflight Requests</strong>: For more complex requests, the browser sends an OPTIONS request first. This preflight request checks if the actual request is safe to send. Preflight helps stop CSRF attacks because SOP alone can’t fully protect against them.</li></ul><p>By understanding SOP, SameSite cookies, and CORS, you can help keep web interactions secure and ensure your web applications work smoothly. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fec241fad3d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>