<?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 Kübra Utman on Medium]]></title>
        <description><![CDATA[Stories by Kübra Utman on Medium]]></description>
        <link>https://medium.com/@kbrautman?source=rss-91247c2ada0b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vuywKzoDYZw-AbRtHQrD7Q.jpeg</url>
            <title>Stories by Kübra Utman on Medium</title>
            <link>https://medium.com/@kbrautman?source=rss-91247c2ada0b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 01:04:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kbrautman/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[Git History den commit nasıl silinir?]]></title>
            <link>https://kbrautman.medium.com/git-history-den-commit-nas%C4%B1l-silinir-38e677bb94a0?source=rss-91247c2ada0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/38e677bb94a0</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[gitflow]]></category>
            <category><![CDATA[bfg-repo-cleaner]]></category>
            <dc:creator><![CDATA[Kübra Utman]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 14:17:23 GMT</pubDate>
            <atom:updated>2023-11-19T14:28:38.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*aynvQ3Tlv4ESCgqU.png" /></figure><p>Merhabalar, Git history nizden sensetive bir dosyanız var password, ssh key vs içeriyor ve bunu silmek istiyorsanız doğru yerdesiniz.</p><p>Commit history nizde yeni eklediğiniz bir dosyayı sonradan history den de kaldırıp silmek isterseniz git rebase yöntemi ile bunu yapabilirsiniz. Ancak iki ya da üç yıl geçmiş bir dosyayı history den silmek istiyorsanız rebase yöntemi yapılması işleri zorlaştırır bu yüzdende farklı alternatifler araştırarak 2 farklı <a href="https://confluence.atlassian.com/bitbucketserverkb/how-do-i-remove-sensitive-unwanted-content-that-was-pushed-to-my-bitbucket-server-instance-1019389998.html">yöntem</a> buldum. Bu yazıda size BFG kütüphanesinden bahsedeceğim.</p><p>BFG Repo Cleaner kütüphanesi, açık kaynak kodlu, repository commit history sinden istenmeyen datayı basit bir şekilde silmeyi sunuyor.</p><p>BFG kütüphanesini çalıştırmadan önce proje dizininizin temiz olmasına dikkat edin.</p><p>BFG kütüphanesinin dökümanına <a href="https://rtyley.github.io/bfg-repo-cleaner/">burdan</a> ulaşabilirsiniz.</p><p>Ben burdaki örnekte eklediğim dosyayı daha sonrasında sildim. Bunu commit history sinden nasıl sildiğimi anlatacağım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKn81af_XPWwTECXjq-agA.png" /></figure><p>BFG kütüphanesi adımları şu şekildedir:</p><ol><li>git clone — mirror komutunu kullanarak etkilenen reponun localinizde bir kopyasını klonlayın.</li><li>komut sisteminden proje dizinine gidin.</li><li>İndirdiğiniz bfg jarını proje dizininde çalıştırın.</li><li>Silmek istediğiniz dosyanın adını ekleyin.</li><li>Dosyalar birden fazla ise {} içerisine isimleri ekleyebilirsiniz. Ben sadece 1 dosya sileceğim için bu şekilde yazdım.</li></ol><pre>bfg --delete-files  {&quot;A.properties&quot;,&quot;B.properties&quot;}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Uppy62ns0_usXkiKTrKgA.png" /></figure><p>Komutu çalıştırdığında gördüğünüz gibi bu dosyanın kullanıldığı 2 commit var. Bu yüzden Refers 2 yazıyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYqbGoE7furP7P7dVx9RLA.png" /></figure><p>Updating 2 ref 2 commit in id değiştirerek yeni bir commit id verdiğini gösteriyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qd5sSYm5-NGFosgFVvBNWA.png" /></figure><p>Son olarak git repolarını tamamen temizlemek için aşağıdaki komutu çalıştırın</p><pre>git reflog expire - expire=now - all &amp;&amp; git gc - prune=now - aggressive</pre><p>En son remote repo ya bu değişikliği yapmak için pushlamamız gerekli.</p><pre>git push -f</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*QJcuEcyUhjEueAfpJVMYIA.png" /></figure><p>Gördüğünüz gibi sourcetree den eklenen ve silinen dosyası tamamen kayboldu. Yeni commitid si ile gösteriliyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NFR8WFSpHqvRrbKNOxH-A.png" /></figure><p>Ekledğiniz ve sonradan pişman olup sildiğiniz dosyaları bu şekilde commit history sinden silebilirsiniz.</p><p>Referanslar</p><ul><li><a href="https://confluence.atlassian.com/bitbucketserverkb/how-do-i-remove-sensitive-unwanted-content-that-was-pushed-to-my-bitbucket-server-instance-1019389998.html">How do I remove sensitive/unwanted content that was pushed to my Bitbucket Server instance?</a></li><li><a href="https://rtyley.github.io/bfg-repo-cleaner/">BFG Repo-Cleaner</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38e677bb94a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React BrowserRouter Kullanımı]]></title>
            <link>https://kbrautman.medium.com/react-browserrouter-kullan%C4%B1m%C4%B1-db6ccae1dd40?source=rss-91247c2ada0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/db6ccae1dd40</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[browserrouing]]></category>
            <dc:creator><![CDATA[Kübra Utman]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 16:20:07 GMT</pubDate>
            <atom:updated>2023-10-15T17:18:32.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*u-L-I3j455wtG3abkqdA4A.jpeg" /></figure><h3>React Router Kullanımı</h3><p><strong>Routing nedir ?</strong></p><p>Routing, web sayfalarında gezinme işlemlerini yönetmek ve belirli bir URL’e göre hangi içeriğin görüntüleneceğini belirlemek için kullanılan bir tekniktir. Kısacası, web sayfaları arasındaki geçişleri, URL’leri ve sayfalar arasındaki ilişkileri kontrol etmeye yardımcı olur. Routing, web uygulamalarının çok sayfa yerine tek sayfa (Single Page Application — SPA) olarak çalışabilmesini sağlar.</p><p><strong>React da Routing Nasıl Yapılır ?</strong></p><p>React projelerinde, kullanıcıların farklı sayfalar arasında geçiş yapabilmesi için react-router-dom kütüphanesini kullanabiliriz. Bu kütüphane, tarayıcıda URL’yi güncellemek ve farklı bileşenlerin görüntülenmesini sağlamak için kullanılır. Aşağıda, BrowserRouter&#39;ı kullanarak temel bir React uygulaması oluşturmanın adımlarını bulabilirsiniz.</p><h4>Adım 1: react-router-dom Kurulumu</h4><p>Öncelikle, projenizde react-router-dom kütüphanesini yüklemeniz gerekir. Terminal veya komut istemcisinde projenizin dizininde şu komutu çalıştırarak kütüphaneyi ekleyin</p><pre>npm install react-router-dom</pre><p>Kütüphaneyi indirdikten sonra React projenizin index.js dosyasında routing yapısı oluşturarak uygulamanın nasıl yapılandırılacağını ve hangi bileşenlerin hangi URL’lere yönlendirileceğini belirleyebiliriz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/927614b32d3907c6d791ba6ec9ab2460/href">https://medium.com/media/927614b32d3907c6d791ba6ec9ab2460/href</a></iframe><p>App.js den açılan react uygulamamızda routing yapacağımız componentleri şu şekilde ekleriz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d15e6f81bd516b0f9a935ebed3f966e0/href">https://medium.com/media/d15e6f81bd516b0f9a935ebed3f966e0/href</a></iframe><p><strong>Route exact ne işe yarar ?</strong></p><p>Bu yapı, uygulamanızdaki farklı URL’ler arasında geçiş yapmak için kullanılabilir. exact özelliğinin kullanılmaması durumunda, bir yolu tam olarak eşleştirmek yerine, verilen yolun içeriğine eşleşip eşleşmediği kontrol edilir. Bu, özellikle alt sayfalar veya alt rotaların olduğu durumlarda kullanışlı olabilir.</p><ul><li>/ yolu ile eşleştiğinde, ProductList bileşeni (&lt;ProductList /&gt;) render edilir.</li><li>/cart yolu ile eşleştiğinde, CartList bileşeni (&lt;CartList /&gt;) render edilir.</li><li>Hiçbir yolu ile eşleşmeyen (yani, yukarıdaki yollar dışındaki tüm yollar) URL’ler için, NotFound bileşeni (&lt;NotFound /&gt;) render edilir.</li></ul><p><strong>Link to nedir?</strong></p><p>react-router-dom kütüphanesinde yer alan Link bileşeni, uygulamanızda farklı sayfalar veya rotalar arasında gezinmeyi sağlayan bir bileşendir. Link bileşeni, kullanıcıların belirli bir URL&#39;e tıkladığında uygulamanın farklı rotalarına yönlendirilmesini sağlar. Link bileşeni, sayfa yenilenmediği veya tamamen yeniden yüklenmediği için, uygulamanın daha hızlı ve daha duyarlı olmasını sağlar.</p><p>Link bileşeni genellikle navigasyon menülerinde, yanıtlarda, kartlarda, düğmelerde veya herhangi bir yerde kullanılabilir. Kullanıcılar Link bileşenine tıkladığında, ilgili rotaya yönlendirilirler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fcc48b4cd35e215f5fee45cb1b0527e/href">https://medium.com/media/6fcc48b4cd35e215f5fee45cb1b0527e/href</a></iframe><p>React da Routing yapılan örnek projeme aşağıdaki linkten erişebilirsiniz.</p><p><a href="https://github.com/kubrautman/React-Init">GitHub - kubrautman/React-Init</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db6ccae1dd40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Vulnerabilities 1]]></title>
            <link>https://kbrautman.medium.com/spring-vulnerabilities-1-11a2ea8c7077?source=rss-91247c2ada0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/11a2ea8c7077</guid>
            <category><![CDATA[vulnerability-assessment]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Kübra Utman]]></dc:creator>
            <pubDate>Thu, 16 Mar 2023 20:43:32 GMT</pubDate>
            <atom:updated>2023-03-16T20:43:32.753Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Cross-Site Request Forgery</strong> (CSRF) is a security vulnerability that occurs when a malicious website or attacker tricks a user into unknowingly sending a request to a different website. This type of attack can result in unauthorized actions on the victim’s behalf, such as changing their account information, making purchases, or accessing sensitive data.</p><p>In Spring, there are several ways to mitigate CSRF attacks. Here are some steps you can take to fix the issue:</p><ol><li>Enable CSRF protection in Spring Security: Spring Security provides built-in support for CSRF protection. To enable it, add the following code to your Spring Security configuration file:</li></ol><pre>http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());<br></pre><p>This code retrieves the CSRF token from the cookie and includes it as a hidden field in the form. When the form is submitted, the token is sent along with the other form data.</p><ol><li>Set SameSite attribute for cookies: The SameSite attribute can prevent CSRF by ensuring that cookies are only sent to the same site that set them. To set the SameSite attribute for cookies in Spring, add the following code to your configuration:</li></ol><pre>@Bean<br>public TomcatServletWebServerFactory servletContainer() {<br>   TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {<br>       @Override<br>       protected void postProcessContext(Context context) {<br>           SessionCookieConfig cookieConfig = context.getServletContext().getSessionCookieConfig();<br>           cookieConfig.setSameSiteMode(SameSiteMode.LAX);<br>           super.postProcessContext(context);<br>       }<br>   };<br>   return tomcat;<br>}<br></pre><p>This code sets the SameSite attribute for session cookies to “Lax”, which means that cookies will only be sent in first-party contexts (i.e., when the user is directly interacting with your site).</p><ol><li>Avoid using GET requests for state-changing operations: GET requests can be easily forged and should not be used for state-changing operations (e.g., updating data, deleting data, etc.). Instead, use POST or PUT requests, which are more secure and cannot be forged as easily.</li></ol><p>By implementing these steps, you can significantly reduce the risk of CSRF attacks in your Spring applications.</p><p><strong>Cross-Site Scripting (XSS) i</strong>s a security vulnerability that occurs when an attacker injects malicious code into a web page viewed by other users. This code can then execute in the user’s browser and perform unauthorized actions, such as stealing sensitive data, logging keystrokes, or taking over the user’s account.</p><p>In Spring, there are several ways to mitigate XSS attacks. Here are some steps you can take to fix the issue:</p><ol><li>Use Thymeleaf or another template engine: Thymeleaf is a popular template engine that provides built-in protection against XSS attacks. When you use Thymeleaf to render your HTML pages, it automatically escapes any user input that could contain malicious code. This ensures that any injected code is treated as plain text and not executed in the user’s browser.</li><li>Sanitize user input: If you are using plain HTML or another template engine that does not provide built-in protection against XSS, you should sanitize user input to remove any potentially malicious code. There are several Java libraries that can help with this, such as OWASP Java Encoder and JSoup.</li></ol><p>For example, you can use the following code to sanitize user input using OWASP Java Encoder</p><pre>import org.owasp.encoder.Encode;</pre><pre>String userInput = &quot;&lt;script&gt;alert(&#39;XSS&#39;);&lt;/script&gt;&quot;;<br>String sanitizedInput = Encode.forHtml(userInput)</pre><p>This code replaces any characters that could be used to inject malicious code with their HTML entity equivalents, effectively neutralizing any injected code.</p><ol><li>Use Content Security Policy (CSP): Content Security Policy (CSP) is a security feature that allows you to specify which sources of content are allowed to be loaded on a page. By using CSP, you can prevent malicious scripts from executing even if they are injected into the page.</li></ol><p>To use CSP in Spring, you can add the following code to your configuration:</p><pre>@Override<br>protected void configure(HttpSecurity http) throws Exception {<br>    http.headers()<br>            .contentSecurityPolicy(&quot;default-src &#39;self&#39;&quot;);<br>}</pre><p>This code sets the default Content Security Policy to only allow content from the same origin as the page. You can customize the policy to fit your specific needs.</p><p>By implementing these steps, you can significantly reduce the risk of XSS attacks in your Spring applications.</p><p><strong>SQL injection is a security vulnerability</strong> that occurs when an attacker injects malicious SQL code into a web application. This code can then be executed by the application’s database, allowing the attacker to access, modify, or delete data from the database.</p><p>In Spring, there are several ways to mitigate SQL injection attacks. Here are some steps you can take to fix the issue:</p><ol><li>Use prepared statements: Prepared statements are a way to execute SQL queries with parameters that are filled in later. By using prepared statements, you can prevent SQL injection attacks by ensuring that user input is always treated as a parameter and not as part of the SQL query.</li></ol><p>For example, instead of using a plain SQL query like this:</p><pre>String username = request.getParameter(&quot;username&quot;);<br>String password = request.getParameter(&quot;password&quot;);</pre><pre>String sql = &quot;SELECT * FROM users WHERE username = &#39;&quot; + username + &quot;&#39; AND password = &#39;&quot; + password + &quot;&#39;&quot;;</pre><p>You can use a prepared statement like this:</p><pre>String sql = &quot;SELECT * FROM users WHERE username = ? AND password = ?&quot;;<br>PreparedStatement stmt = connection.prepareStatement(sql);<br>stmt.setString(1, username);<br>stmt.setString(2, password);<br>ResultSet rs = stmt.executeQuery();</pre><p>This code uses a prepared statement to execute the SQL query with placeholders for the username and password parameters. The actual values are set using the setString() method, which automatically escapes any special characters and prevents SQL injection attacks.</p><ol><li>Use parameterized queries: Parameterized queries are similar to prepared statements but are used for executing SQL queries that do not return a result set, such as INSERT, UPDATE, and DELETE statements. Parameterized queries are a way to pass parameters to the SQL query without having to concatenate them into the SQL string.</li></ol><p>For example, instead of using a plain SQL query like this:</p><pre>String username = request.getParameter(&quot;username&quot;);<br>String password = request.getParameter(&quot;password&quot;);<br><br>String sql = &quot;INSERT INTO users (username, password) VALUES (&#39;&quot; + username + &quot;&#39;, &#39;&quot; + password + &quot;&#39;)&quot;;</pre><p>You can use a parameterized query like this:</p><pre>String sql = &quot;INSERT INTO users (username, password) VALUES (?, ?)&quot;;<br>PreparedStatement stmt = connection.prepareStatement(sql);<br>stmt.setString(1, username);<br>stmt.setString(2, password);<br>stmt.executeUpdate();</pre><p>This code uses a parameterized query to execute the INSERT statement with placeholders for the username and password parameters. The actual values are set using the setString() method, which automatically escapes any special characters and prevents SQL injection attacks.</p><ol><li>Use an ORM framework: Object-Relational Mapping (ORM) frameworks like Hibernate and MyBatis provide built-in protection against SQL injection attacks by automatically escaping any user input that is used in SQL queries. By using an ORM framework, you can prevent SQL injection attacks without having to manually escape user input or use prepared statements.</li></ol><p>For example, instead of manually constructing SQL queries like this:</p><pre>String username = request.getParameter(&quot;username&quot;);<br>String password = request.getParameter(&quot;password&quot;);<br><br>String sql = &quot;SELECT * FROM users WHERE username = &#39;&quot; + username + &quot;&#39; AND password = &#39;&quot; + password + &quot;&#39;&quot;;</pre><p>You can use an ORM framework like Hibernate to construct the SQL query automatically:graphqlCopy code</p><pre>String username = request.getParameter(&quot;username&quot;);<br>String password = request.getParameter(&quot;password&quot;);<br><br>Session session = sessionFactory.getCurrentSession();<br>Query query = session.createQuery(&quot;FROM User WHERE username = :username AND password = :password&quot;);<br>query.setParameter(&quot;username&quot;, username);<br>query.setParameter(&quot;password&quot;, password);<br>List&lt;User&gt; users = query.list();</pre><p>This code uses Hibernate to construct the SQL query automatically based on the User entity and the provided parameters. Hibernate automatically escapes any special characters and prevents SQL injection attacks.</p><p>By implementing these steps, you can significantly reduce the risk of SQL injection attacks in your Spring applications.</p><p><strong>A Denial-of-Service (DoS) attack</strong> is a security vulnerability that occurs when an attacker floods a web application with traffic or requests, causing it to become unavailable or unresponsive to legitimate users.</p><p>In Spring, there are several ways to mitigate DoS attacks. Here are some steps you can take to fix the issue:</p><ol><li>Limit request rates: You can limit the rate of incoming requests to your Spring application by using a rate limiter. This can prevent an attacker from overwhelming your application with too many requests.</li></ol><p>One way to implement a rate limiter in Spring is to use the Spring RateLimiter annotation. This annotation allows you to limit the number of requests that can be processed within a specified time period.</p><p>For example, you can annotate a method in your controller class with the @RateLimiter annotation like this:</p><pre>@RateLimiter(value = &quot;myMethod&quot;, limit = 10, duration = 1, timeUnit = TimeUnit.SECONDS)<br>public void myMethod() {<br>    // method code here<br>}</pre><p>This code limits the number of requests that can be processed by the myMethod() method to 10 requests per second.</p><ol><li>Use caching: Caching is a way to store frequently accessed data in memory, reducing the number of database queries and improving application performance. By caching frequently accessed data, you can reduce the load on your application and prevent DoS attacks.</li></ol><p>In Spring, you can use caching by enabling the Spring Cache abstraction and adding caching annotations to your methods. For example, you can annotate a method in your service class with the @Cacheable annotation like this:</p><pre>@Cacheable(&quot;users&quot;)<br>public User getUserById(int id) {<br>    // method code here<br>}</pre><p>This code caches the User object returned by the getUserById() method with the cache name “users”. Subsequent calls to this method with the same ID will return the cached User object, reducing the number of database queries and improving application performance.</p><ol><li>Use request throttling: Request throttling is a way to limit the number of requests that can be processed by your application within a specified time period. By limiting the number of requests that can be processed, you can prevent an attacker from overwhelming your application with too many requests.</li></ol><p>In Spring, you can implement request throttling by using a library like Spring Cloud Gateway or Spring Security. These libraries provide request throttling capabilities out-of-the-box, allowing you to limit the number of requests that can be processed by your application within a specified time period.</p><p>For example, you can configure request throttling in Spring Cloud Gateway by adding the following configuration to your application.yaml file:</p><pre>yamlCopy code</pre><pre>spring:<br>  cloud:<br>    gateway:<br>      routes:<br>        - id: myRoute<br>          uri: http://localhost:8080<br>          predicates:<br>            - Path=/myPath<br>          filters:<br>            - name: RequestRateLimiter<br>              args:<br>                redis-rate-limiter.replenishRate: 1<br>                redis-rate-limiter.burstCapacity: 2</pre><p>This code configures a route in Spring Cloud Gateway with request throttling enabled. The RequestRateLimiter filter limits the number of requests that can be processed to 1 request per second with a burst capacity of 2 requests.</p><p>By implementing these steps, you can significantly reduce the risk of DoS attacks in your Spring applications.</p><p>There are several steps you can take to fix configuration vulnerabilities in Spring:</p><ol><li>Secure sensitive configuration properties: Sensitive configuration properties such as database credentials, API keys, and passwords should be encrypted or stored in a secure location. In Spring, you can use the Spring Security framework to secure sensitive configuration properties. You can also use the Spring Cloud Config Server to store configuration properties in a secure location.</li><li>Disable debug mode: Debug mode can expose sensitive information about your application and its configurations. In Spring, you can disable debug mode by setting the logging level to a higher level, such as INFO or ERROR.</li><li>Use secure communication protocols: Communication between your Spring application and other services or clients should be encrypted using secure communication protocols such as HTTPS or TLS. In Spring, you can configure secure communication protocols using the Spring Security framework.</li><li>Use strong encryption algorithms: Encryption algorithms should be strong enough to prevent attackers from decrypting sensitive information. In Spring, you can use strong encryption algorithms by configuring encryption properties in the application.properties or application.yaml file.</li><li>Avoid hardcoding configuration values: Hardcoding configuration values such as URLs, paths, and ports can make your application vulnerable to attacks. In Spring, you can avoid hardcoding configuration values by using environment variables or external configuration files such as the application.properties or application.yaml file.</li><li>Validate user input: User input should be validated to prevent attackers from injecting malicious code into your application. In Spring, you can use validation annotations such as @NotBlank, @NotNull, and @Valid to validate user input.</li></ol><p>By implementing these steps, you can significantly reduce the risk of configuration vulnerabilities in your Spring applications. It’s important to keep your Spring application up to date with the latest security patches and follow secure coding practices to prevent future vulnerabilities.</p><p>One example of a configuration vulnerability in Spring is the exposure of sensitive information such as database credentials, API keys, or passwords in plain text in configuration files.</p><p>For instance, consider a Spring application that connects to a database to store and retrieve sensitive data. The database credentials are stored in the application.properties file in plain text as follows:</p><pre>spring.datasource.username=admin<br>spring.datasource.password=admin123<br>spring.datasource.url=jdbc:mysql://localhost:3306/mydb</pre><p>If an attacker gains access to the application.properties file, they can easily obtain the database credentials and potentially access the database.</p><p>To fix this configuration vulnerability, you can encrypt the sensitive configuration properties using Jasypt (Java Simplified Encryption). Jasypt is a library that provides simple encryption and decryption of text using a strong encryption algorithm.</p><p>Here’s an example of how you can encrypt the database credentials using Jasypt:</p><ol><li>Add the Jasypt dependency to your project:</li></ol><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.jasypt&lt;/groupId&gt;<br>    &lt;artifactId&gt;jasypt-spring-boot-starter&lt;/artifactId&gt;<br>    &lt;version&gt;2.2.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><ol><li>Generate an encryption key:</li></ol><pre>java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=&quot;admin123&quot; password=&quot;mysecretkey&quot; algorithm=PBEWithMD5AndDES</pre><p>This command generates an encrypted string for the password “admin123” using the encryption algorithm PBEWithMD5AndDES and the password “mysecretkey”. The encrypted string will be used in the application.properties file.</p><ol><li>Update the application.properties file with the encrypted properties:</li></ol><pre>spring.datasource.username=admin<br>spring.datasource.password=ENC(vyLfD2mWk4+Y4X9a/rFQ2Q==)<br>spring.datasource.url=jdbc:mysql://localhost:3306/mydb</pre><pre>jasypt.encryptor.password=mysecretkey</pre><p>Note that the password property is now encrypted using the prefix ENC, indicating that the value is encrypted. The jasypt.encryptor.password property is used to configure the Jasypt encryption algorithm.</p><p>By encrypting sensitive configuration properties using Jasypt, you can protect your Spring application from configuration vulnerabilities such as exposure of sensitive information in plain text.</p><p>One example of a vulnerability in Spring RestTemplate is the potential for <strong>Man-in-the-Middle (MitM) attacks </strong>due to the use of an unsecured connection.</p><p>For instance, consider a Spring application that uses RestTemplate to make API requests to a third-party service. The following code snippet shows an example of how RestTemplate can be used to make a GET request:javaCopy code</p><pre>RestTemplate restTemplate = new RestTemplate();<br>String response = restTemplate.getForObject(&quot;http://example.com/api&quot;, String.class);</pre><p>If the third-party service does not use HTTPS or TLS, the API request is transmitted over an unsecured connection, making it vulnerable to MitM attacks. An attacker can intercept the API request and modify or inject malicious content.</p><p>To fix this vulnerability, you can configure RestTemplate to use HTTPS or TLS to establish a secure connection with the third-party service. Here’s an example of how to configure RestTemplate to use HTTPS:</p><pre>RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());<br><br>private ClientHttpRequestFactory getClientHttpRequestFactory() {<br>    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory<br>                      = new HttpComponentsClientHttpRequestFactory();<br>    clientHttpRequestFactory.setHttpClient(getHttpClient());<br>    return clientHttpRequestFactory;<br>}<br>private HttpClient getHttpClient() {<br>    SSLContext sslContext = SSLContextBuilder.create()<br>                            .loadTrustMaterial(null, new TrustSelfSignedStrategy())<br>                            .build();<br>    HttpClient httpClient = HttpClients.custom()<br>                              .setSSLContext(sslContext)<br>                              .build();<br>    return httpClient;<br>}<br></pre><p>This code snippet shows how to create a custom HttpClient that uses SSL/TLS to establish a secure connection with the third-party service. The HttpClient is then passed to the HttpComponentsClientHttpRequestFactory, which is used to create the RestTemplate.</p><p>Note that this example uses a self-signed certificate, which is not recommended for production use. In a production environment, you should use a trusted SSL/TLS certificate issued by a trusted Certificate Authority.</p><p>By configuring RestTemplate to use HTTPS or TLS, you can protect your Spring application from vulnerabilities such as MitM attacks due to unsecured connections.</p><p><strong>Spring Server-Side Request Forgery (SSRF)</strong> vulnerabilities occur when an attacker can manipulate the URL or input parameters of a web application to send requests to an arbitrary server, including internal servers or servers outside the trusted network.</p><p>One example of an SSRF vulnerability in Spring is shown below:</p><pre>@RequestMapping(value = &quot;/fetch&quot;, method = RequestMethod.GET)<br>@ResponseBody<br>public String fetchData(@RequestParam(&quot;url&quot;) String url) throws IOException {<br>    URL obj = new URL(url);<br>    HttpURLConnection con = (HttpURLConnection) obj.openConnection();<br>    con.setRequestMethod(&quot;GET&quot;);<br><br>BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));<br>    String inputLine;<br>    StringBuffer response = new StringBuffer();<br>    while ((inputLine = in.readLine()) != null) {<br>        response.append(inputLine);<br>    }<br>    in.close();<br>    return response.toString();<br>}</pre><p>In this example, an endpoint is created that takes in a URL parameter and fetches the content of that URL using a GET request. However, this code is vulnerable to SSRF attacks since an attacker can pass in a URL that points to an internal server or to a vulnerable service running on a public-facing server.</p><p>To fix this vulnerability, you can implement input validation on the URL parameter to prevent the injection of malicious URLs. One approach is to use a whitelist of trusted domains and only allow requests to URLs that are within that whitelist.</p><pre>private static final List&lt;String&gt; WHITELISTED_DOMAINS = Arrays.asList(&quot;example.com&quot;, &quot;trusted.com&quot;);<br>@RequestMapping(value = &quot;/fetch&quot;, method = RequestMethod.GET)<br>@ResponseBody<br>public String fetchData(@RequestParam(&quot;url&quot;) String url) throws IOException {<br>    if (!isValidUrl(url)) {<br>        throw new IllegalArgumentException(&quot;Invalid URL&quot;);<br>    }<br>    URL obj = new URL(url);<br>    HttpURLConnection con = (HttpURLConnection) obj.openConnection();<br>    con.setRequestMethod(&quot;GET&quot;);<br>    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));<br>    String inputLine;<br>    StringBuffer response = new StringBuffer();<br>    while ((inputLine = in.readLine()) != null) {<br>        response.append(inputLine);<br>    }<br>    in.close();<br>    return response.toString();<br>}<br>private boolean isValidUrl(String url) {<br>    try {<br>        URI uri = new URI(url);<br>        String domain = uri.getHost();<br>        return WHITELISTED_DOMAINS.contains(domain);<br>    } catch (URISyntaxException e) {<br>        return false;<br>    }<br>}</pre><p>In this example, the isValidUrl method is used to validate the URL parameter against the whitelist of trusted domains. If the URL parameter is not valid or not within the whitelist, an IllegalArgumentException is thrown, preventing the request from being executed.</p><p>By implementing input validation on the URL parameter and using a whitelist of trusted domains, you can protect your Spring application from Server-Side Request Forgery (SSRF) attacks.</p><p><strong>Mass Assignment vulnerabilities</strong> in Spring occur when an attacker can manipulate the values of a request parameter to modify data fields that were not intended to be modified. This can happen if the application allows incoming requests to bind to model objects, and the attacker includes additional parameters to modify fields that should be protected.</p><p>One example of a Mass Assignment vulnerability in Spring is shown below:javaCopy code</p><pre>@PostMapping(&quot;/users&quot;)<br>public String createUser(@ModelAttribute(&quot;user&quot;) User user) {<br>    userService.saveUser(user);<br>    return &quot;redirect:/users&quot;;<br>}</pre><p>In this example, the createUser endpoint takes in a User object and saves it using the userService. However, if an attacker submits additional parameters to the request, those parameters could be used to modify fields that should not be modifiable, such as the user&#39;s role or password.</p><p>To fix this vulnerability, you can configure Spring’s binder to ignore certain fields that should not be modified by incoming requests. Here’s an example of how to configure the binder to ignore certain fields:javaCopy code</p><pre>@PostMapping(&quot;/users&quot;)<br>public String createUser(@ModelAttribute(&quot;user&quot;) @Validated User user, BindingResult result) {<br>    if (result.hasErrors()) {<br>        return &quot;createUserForm&quot;;<br>    }<br><br>PropertyValues propertyValues = new MutablePropertyValues()<br>            .add(&quot;firstName&quot;, user.getFirstName())<br>            .add(&quot;lastName&quot;, user.getLastName())<br>            .add(&quot;email&quot;, user.getEmail());<br>    WebDataBinder binder = new WebDataBinder(user);<br>    binder.initDirectFieldAccess();<br>    binder.setDisallowedFields(&quot;id&quot;, &quot;role&quot;, &quot;password&quot;);<br>    binder.bind(propertyValues);<br>    userService.saveUser(user);<br>    return &quot;redirect:/users&quot;;<br>}</pre><p>In this example, the WebDataBinder is used to bind incoming parameters to the User object. The setDisallowedFields method is used to exclude certain fields from being bound, preventing an attacker from modifying them.</p><p>By configuring the binder to exclude certain fields, you can protect your Spring application from Mass Assignment vulnerabilities. It’s important to note that this is just one of many ways to mitigate this type of vulnerability, and there may be other factors to consider depending on the specifics of your application.</p><p><strong>A race condition vulnerability occurs</strong> when multiple threads access and modify shared resources simultaneously, leading to unexpected and potentially harmful behavior. In a Spring application, this vulnerability can occur when multiple threads access and modify the same singleton bean member field.</p><p>Here’s an example of a Spring singleton bean with a member field that can be modified by multiple threads simultaneously:</p><pre>@Component<br>public class ExampleService {<br>    private List&lt;String&gt; data = new ArrayList&lt;&gt;();<br><br>public void addData(String newData) {<br>        data.add(newData);<br>    }<br>    public List&lt;String&gt; getData() {<br>        return data;<br>    }<br>}</pre><p>In this example, multiple threads can call the addData method simultaneously, leading to a race condition. If two threads call addData at the same time, the list may become corrupted, and data may be lost.</p><p>To fix this vulnerability, you can use synchronized methods or locks to ensure that only one thread can modify the shared resource at a time. Here’s an example of how to fix the above example using synchronized methods:</p><pre>@Component<br>public class ExampleService {<br>    private List&lt;String&gt; data = new ArrayList&lt;&gt;();<br><br><br>public synchronized void addData(String newData) {<br>        data.add(newData);<br>    }<br>    public synchronized List&lt;String&gt; getData() {<br>        return data;<br>    }<br>}</pre><p>In this example, the addData and getData methods are synchronized, ensuring that only one thread can modify or access the data list at a time. This prevents the race condition vulnerability from occurring.</p><p>Another option to fix this vulnerability is to use locks instead of synchronized methods. Here’s an example of how to fix the above example using locks:</p><pre>@Component<br>public class ExampleService {<br>    private List&lt;String&gt; data = new ArrayList&lt;&gt;();<br>    private final Lock lock = new ReentrantLock();<br><br>public void addData(String newData) {<br>        lock.lock();<br>        try {<br>            data.add(newData);<br>        } finally {<br>            lock.unlock();<br>        }<br>    }<br>    public List&lt;String&gt; getData() {<br>        lock.lock();<br>        try {<br>            return data;<br>        } finally {<br>            lock.unlock();<br>        }<br>    }<br>}</pre><p>In this example, the addData and getData methods use a ReentrantLock to lock the data list, ensuring that only one thread can modify or access it at a time. This also prevents the race condition vulnerability from occurring.</p><p>In summary, to fix the race condition vulnerability in Spring singleton bean member fields, you can use synchronized methods or locks to ensure that only one thread can modify the shared resource at a time.</p><p>Resource injection is a vulnerability that occurs when an attacker can inject malicious code into the resources of a Spring application. This can happen when the application uses resource injection to load resources dynamically at runtime.</p><p>Here’s an example of resource injection in a Spring application:</p><pre>@Controller<br>public class ExampleController {<br>    @Resource(name = &quot;userDao&quot;)<br>    private UserDao userDao;<br><br>@GetMapping(&quot;/users/{id}&quot;)<br>    public String getUser(@PathVariable(&quot;id&quot;) Long id, Model model) {<br>        User user = userDao.findById(id);<br>        model.addAttribute(&quot;user&quot;, user);<br>        return &quot;user&quot;;<br>    }<br>}</pre><p>In this example, the ExampleController class uses resource injection to load the userDao bean dynamically. However, if an attacker can modify the resource being injected, they can inject malicious code into the application.</p><p>To fix this vulnerability, you can use constructor injection or setter injection instead of resource injection. Here’s an example of how to fix the above example using constructor injection:</p><pre>@Controller<br>public class ExampleController {<br>    private final UserDao userDao;<br><br>public ExampleController(UserDao userDao) {<br>        this.userDao = userDao;<br>    }<br>    @GetMapping(&quot;/users/{id}&quot;)<br>    public String getUser(@PathVariable(&quot;id&quot;) Long id, Model model) {<br>        User user = userDao.findById(id);<br>        model.addAttribute(&quot;user&quot;, user);<br>        return &quot;user&quot;;<br>    }<br>}</pre><p>In this example, the ExampleController class uses constructor injection to load the userDao bean. This prevents an attacker from modifying the resource being injected at runtime, as the resource is loaded at application startup.</p><p>Alternatively, you can also use setter injection to load the resource. Here’s an example of how to fix the above example using setter injection:</p><pre>@Controller<br>public class ExampleController {<br><br>private UserDao userDao;<br><br>@Resource(name = &quot;userDao&quot;)<br>    public void setUserDao(UserDao userDao) {<br>        this.userDao = userDao;<br>    }<br>    @GetMapping(&quot;/users/{id}&quot;)<br>    public String getUser(@PathVariable(&quot;id&quot;) Long id, Model model) {<br>        User user = userDao.findById(id);<br>        model.addAttribute(&quot;user&quot;, user);<br>        return &quot;user&quot;;<br>    }<br>}</pre><p>In this example, the ExampleController class uses setter injection to load the userDao bean. This also prevents an attacker from modifying the resource being injected at runtime, as the resource is loaded at application startup.</p><p>In summary, to fix resource injection vulnerabilities in Spring, you can use constructor injection or setter injection instead of resource injection. This ensures that resources are loaded at application startup and prevents attackers from modifying them at runtime.</p><p><strong>Password management vulnerabilities in</strong> Spring can occur when developers include sensitive information such as passwords or API keys in comments or logs within the application code. Attackers can exploit this vulnerability to gain unauthorized access to the system or its resources.</p><p>Here’s an example of a password management vulnerability in Spring:</p><pre>public class ExampleService {<br>    private final String password = &quot;password123&quot;;<br>public void doSomething() {<br>        // This method uses the password to access a secure resource<br>        // ...<br>    }<br>}</pre><p>In this example, the password is hard-coded into the ExampleService class and is used to access a secure resource. However, the password is stored in plain text and can be easily viewed by anyone who has access to the code. This makes the password vulnerable to attackers who can gain unauthorized access to the system.</p><p>To fix this vulnerability, you can use external configuration files or environment variables to store sensitive information such as passwords. Here’s an example of how to fix the above example using external configuration files:</p><p>application.properties file:</p><pre>example.password=password123</pre><pre>@Configuration<br>public class ExampleConfig {<br>    @Value(&quot;${example.password}&quot;)<br>    private String password;<br>@Bean<br>    public ExampleService exampleService() {<br>        return new ExampleService(password);<br>    }<br>}<br>public class ExampleService {<br>    private final String password;<br>    public ExampleService(String password) {<br>        this.password = password;<br>    }<br>    public void doSomething() {<br>        // This method uses the password to access a secure resource<br>        // ...<br>    }<br>}</pre><p>In this example, the password is stored in an external configuration file and is loaded into the ExampleConfig class using the @Value annotation. The ExampleService class is then instantiated with the password value as a constructor argument.</p><p>This approach ensures that the password is not stored in plain text within the application code, making it more secure and less vulnerable to attackers.</p><p>In summary, to fix password management vulnerabilities in Spring, you can use external configuration files or environment variables to store sensitive information such as passwords. This ensures that the password is not stored in plain text within the application code and is less vulnerable to attackers.</p><p>Path manipulation vulnerabilities in Spring can occur when the application code does not properly sanitize user input before using it to construct file paths or URLs. Attackers can exploit this vulnerability to access or modify files or resources on the server that they should not have access to.</p><p>Here’s an example of a path manipulation vulnerability in Spring:</p><pre>@RestController<br>public class ExampleController {<br>    @GetMapping(&quot;/files/{fileName}&quot;)<br>    public ResponseEntity&lt;Resource&gt; downloadFile(@PathVariable String fileName) {<br>        Resource resource = new FileSystemResource(&quot;/path/to/files/&quot; + fileName);<br>        // ...<br>    }<br>}</pre><p>In this example, the fileName variable is used to construct a file path without proper input validation or sanitization. An attacker can manipulate the fileName parameter to access or modify files outside of the intended directory.</p><p>To fix this vulnerability, you should validate and sanitize user input before using it to construct file paths or URLs. Here’s an example of how to fix the above example:</p><pre>@RestController<br>public class ExampleController {   <br> @GetMapping(&quot;/files/{fileName}&quot;)<br>    public ResponseEntity&lt;Resource&gt; downloadFile(@PathVariable String fileName) throws MalformedURLException {<br>        String sanitizedFileName = sanitizeInput(fileName);<br>        URL fileUrl = new URL(&quot;file:/path/to/files/&quot; + sanitizedFileName);<br>        Resource resource = new UrlResource(fileUrl);<br>        // ...<br>    }<br>private String sanitizeInput(String input) {<br>        // Sanitize the input to prevent path manipulation attacks<br>        // ...<br>        return sanitizedInput;<br>    }<br>}</pre><p>In this example, the fileName parameter is first passed through a sanitizeInput() method to validate and sanitize the user input. The sanitizedFileName is then used to construct a URL object using the UrlResource class. The UrlResource class is used instead of the FileSystemResource class to ensure that the file path is properly escaped and validated.</p><p>This approach ensures that user input is properly validated and sanitized before being used to construct file paths or URLs, making the application less vulnerable to path manipulation attacks.</p><p>In summary, to fix path manipulation vulnerabilities in Spring, you should validate and sanitize user input before using it to construct file paths or URLs. This ensures that user input is properly validated and sanitized before being used to access files or resources, making the application less vulnerable to path manipulation attacks.</p><p><strong>Weak cryptographic hash algorithms can </strong>be exploited by attackers to crack password hashes and gain access to user accounts. In Spring, this vulnerability can occur if weak cryptographic hash algorithms are used to store user passwords.</p><p>Here’s an example of a weak cryptographic hash vulnerability in Spring:</p><pre>@Service<br>public class UserServiceImpl implements UserService {<br><br>@Autowired<br>    private UserRepository userRepository;<br>    @Override<br>    public void createUser(String username, String password) {<br>        String hash = DigestUtils.md5DigestAsHex(password.getBytes());<br>        User user = new User(username, hash);<br>        userRepository.save(user);<br>    }<br>    @Override<br>    public User authenticate(String username, String password) {<br>        String hash = DigestUtils.md5DigestAsHex(password.getBytes());<br>        User user = userRepository.findByUsernameAndPassword(username, hash);<br>        return user;<br>    }<br>}</pre><p>In this example, the createUser() method is using the MD5 algorithm to hash the user&#39;s password. MD5 is considered a weak cryptographic hash algorithm and can be easily cracked by attackers using modern hardware and techniques. This makes it easier for an attacker to gain access to user accounts.</p><p>To fix this vulnerability, you should use stronger cryptographic hash algorithms to store user passwords. Here’s an example of how to fix the above example:</p><pre>javaCopy code</pre><pre>@Service<br>public class UserServiceImpl implements UserService {<br><br>@Autowired<br>    private UserRepository userRepository;<br>    @Override<br>    public void createUser(String username, String password) throws NoSuchAlgorithmException {<br>        String hash = generateHash(password);<br>        User user = new User(username, hash);<br>        userRepository.save(user);<br>    }<br>    @Override<br>    public User authenticate(String username, String password) throws NoSuchAlgorithmException {<br>        String hash = generateHash(password);<br>        User user = userRepository.findByUsernameAndPassword(username, hash);<br>        return user;<br>    }<br>    private String generateHash(String password) throws NoSuchAlgorithmException {<br>        // Use a stronger cryptographic hash algorithm to hash the user&#39;s password<br>        MessageDigest digest = MessageDigest.getInstance(&quot;SHA-256&quot;);<br>        byte[] hashBytes = digest.digest(password.getBytes(StandardCharsets.UTF_8));<br>        String hash = DatatypeConverter.printHexBinary(hashBytes);<br>        return hash;<br>    }<br>}<br></pre><p>In this example, the generateHash() method is using the SHA-256 algorithm to hash the user&#39;s password. SHA-256 is a stronger cryptographic hash algorithm than MD5 and is less susceptible to cracking by attackers.</p><p>This approach ensures that stronger cryptographic hash algorithms are used to store user passwords, making it more difficult for attackers to gain access to user accounts.</p><p>In summary, to fix weak cryptographic hash vulnerabilities in Spring, you should use stronger cryptographic hash algorithms to store user passwords. This ensures that user passwords are properly protected, making it more difficult for attackers to gain access to user accounts.</p><p>Command injection is a vulnerability that occurs when an attacker is able to execute arbitrary commands on a system by injecting malicious input into a command string that is subsequently executed by the application. In Spring, this vulnerability can occur if an application accepts user input and passes it directly to a command shell without proper validation and sanitization.</p><p>Here’s an example of a command injection vulnerability in Spring:</p><h3>Spring Vulnerabilities</h3><p><strong>Cross-Site Request Forgery</strong> (CSRF) is a security vulnerability that occurs when a malicious website or attacker tricks a user into unknowingly sending a request to a different website. This type of attack can result in unauthorized actions on the victim’s behalf, such as changing their account information, making purchases, or accessing sensitive data.</p><p>In Spring, there are several ways to mitigate CSRF attacks. Here are some steps you can take to fix the issue:</p><ol><li>Enable CSRF protection in Spring Security: Spring Security provides built-in support for CSRF protection. To enable it, add the following code to your Spring Security configuration file:</li></ol><pre>http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());</pre><p>This code retrieves the CSRF token from the cookie and includes it as a hidden field in the form. When the form is submitted, the token is sent along with the other form data.</p><ol><li>Set SameSite attribute for cookies: The SameSite attribute can prevent CSRF by ensuring that cookies are only sent to the same site that set them. To set the SameSite attribute for cookies in Spring, add the following code to your configuration:</li></ol><pre>@Bean<br>public TomcatServletWebServerFactory servletContainer() {<br>   TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {<br>       @Override<br>       protected void postProcessContext(Context context) {<br>           SessionCookieConfig cookieConfig = context.getServletContext().getSessionCookieConfig();<br>           cookieConfig.setSameSiteMode(SameSiteMode.LAX);<br>           super.postProcessContext(context);<br>       }<br>   };<br>   return tomcat;<br>}</pre><p>This code sets the SameSite attribute for session cookies to “Lax”, which means that cookies will only be sent in first-party contexts (i.e., when the user is directly interacting with your site).</p><ol><li>Avoid using GET requests for state-changing operations: GET requests can be easily forged and should not be used for state-changing operations (e.g., updating data, deleting data, etc.). Instead, use POST or PUT requests, which are more secure and cannot be forged as easily.</li></ol><p>By implementing these steps, you can significantly reduce the risk of CSRF attacks in your Spring applications.</p><p><strong>Cross-Site Scripting (XSS) i</strong>s a security vulnerability that occurs when an attacker injects malicious code into a web page viewed by other users. This code can then execute in the user’s browser and perform unauthorized actions, such as stealing sensitive data, logging keystrokes, or taking over the user’s account.</p><p>In Spring, there are several ways to mitigate XSS attacks. Here are some steps you can take to fix the issue:</p><ol><li>Use Thymeleaf or another template engine: Thymeleaf is a popular template engine that provides built-in protection against XSS attacks. When you use Thymeleaf to render your HTML pages, it automatically escapes any user input that could contain malicious code. This ensures that any injected code is treated as plain text and not executed in the user’s browser.</li><li>Sanitize user input: If you are using plain HTML or another template engine that does not provide built-in protection against XSS, you should sanitize user input to remove any potentially malicious code. There are several Java libraries that can help with this, such as OWASP Java Encoder and JSoup.</li></ol><p>For example, you can use the following code to sanitize user input using OWASP Java Encoder</p><pre>import org.owasp.encoder.Encode;</pre><pre>String userInput = &quot;&lt;script&gt;alert(&#39;XSS&#39;);&lt;/script&gt;&quot;;<br>String sanitizedInput = Encode.forHtml(userInput)</pre><p>This code replaces any characters that could be used to inject malicious code with their HTML entity equivalents, effectively neutralizing any injected code.</p><ol><li>Use Content Security Policy (CSP): Content Security Policy (CSP) is a security feature that allows you to specify which sources of content are allowed to be loaded on a page. By using CSP, you can prevent malicious scripts from executing even if they are injected into the page.</li></ol><p>To use CSP in Spring, you can add the following code to your configuration:</p><pre>@Override<br>protected void configure(HttpSecurity http) throws Exception {<br>    http.headers()<br>            .contentSecurityPolicy(&quot;default-src &#39;self&#39;&quot;);<br>}</pre><p>This code sets the default Content Security Policy to only allow content from the same origin as the page. You can customize the policy to fit your specific needs.</p><p>By implementing these steps, you can significantly reduce the risk of XSS attacks in your Spring applications.</p><p><strong>SQL injection is a security vulnerability</strong> that occurs when an attacker injects malicious SQL code into a web application. This code can then be executed by the application’s database, allowing the attacker to access, modify, or delete data from the database.</p><p>In Spring, there are several ways to mitigate SQL injection attacks. Here are some steps you can take to fix the issue:</p><ol><li>Use prepared statements: Prepared statements are a way to execute SQL queries with parameters that are filled in later. By using prepared statements, you can prevent SQL injection attacks by ensuring that user input is always treated as a parameter and not as part of the SQL query.</li></ol><p>For example, instead of using a plain SQL query like this:</p><pre>String username = request.getParameter(&quot;username&quot;);<br>String password = request.getParameter(&quot;password&quot;);</pre><pre>String sql = &quot;SELECT * FROM users WHERE username = &#39;&quot; + username + &quot;&#39; AND password = &#39;&quot; + password + &quot;&#39;&quot;;</pre><p>You can use a prepared statement like this:</p><pre>String sql = &quot;SELECT * FROM users WHERE username = ? AND password = ?&quot;;<br>PreparedStatement stmt = connection.prepareStatement(sql);<br>stmt.setString(1, username);<br>stmt.setString(2, password);<br>ResultSet rs = stmt.executeQuery();</pre><p>This code uses a prepared statement to execute the SQL query with placeholders for the username and password parameters. The actual values are set using the setString() method, which automatically escapes any special characters and prevents SQL injection attacks.</p><ol><li>Use parameterized queries: Parameterized queries are similar to prepared statements but are used for executing SQL queries that do not return a result set, such as INSERT, UPDATE, and DELETE statements. Parameterized queries are a way to pass parameters to the SQL query without having to concatenate them into the SQL string.</li></ol><p>For example, instead of using a plain SQL query like this:</p><pre>String username = request.getParameter(&quot;username&quot;);<br>String password = request.getParameter(&quot;password&quot;);<br><br>String sql = &quot;INSERT INTO users (username, password) VALUES (&#39;&quot; + username + &quot;&#39;, &#39;&quot; + password + &quot;&#39;)&quot;;</pre><p>You can use a parameterized query like this:</p><pre>String sql = &quot;INSERT INTO users (username, password) VALUES (?, ?)&quot;;<br>PreparedStatement stmt = connection.prepareStatement(sql);<br>stmt.setString(1, username);<br>stmt.setString(2, password);<br>stmt.executeUpdate();</pre><p>This code uses a parameterized query to execute the INSERT statement with placeholders for the username and password parameters. The actual values are set using the setString() method, which automatically escapes any special characters and prevents SQL injection attacks.</p><ol><li>Use an ORM framework: Object-Relational Mapping (ORM) frameworks like Hibernate and MyBatis provide built-in protection against SQL injection attacks by automatically escaping any user input that is used in SQL queries. By using an ORM framework, you can prevent SQL injection attacks without having to manually escape user input or use prepared statements.</li></ol><p>For example, instead of manually constructing SQL queries like this:</p><pre>String username = request.getParameter(&quot;username&quot;);<br>String password = request.getParameter(&quot;password&quot;);<br><br>String sql = &quot;SELECT * FROM users WHERE username = &#39;&quot; + username + &quot;&#39; AND password = &#39;&quot; + password + &quot;&#39;&quot;;</pre><p>You can use an ORM framework like Hibernate to construct the SQL query automatically:graphqlCopy code</p><pre>String username = request.getParameter(&quot;username&quot;);<br>String password = request.getParameter(&quot;password&quot;);<br><br>Session session = sessionFactory.getCurrentSession();<br>Query query = session.createQuery(&quot;FROM User WHERE username = :username AND password = :password&quot;);<br>query.setParameter(&quot;username&quot;, username);<br>query.setParameter(&quot;password&quot;, password);<br>List&lt;User&gt; users = query.list();</pre><p>This code uses Hibernate to construct the SQL query automatically based on the User entity and the provided parameters. Hibernate automatically escapes any special characters and prevents SQL injection attacks.</p><p>By implementing these steps, you can significantly reduce the risk of SQL injection attacks in your Spring applications.</p><p><strong>A Denial-of-Service (DoS) attack</strong> is a security vulnerability that occurs when an attacker floods a web application with traffic or requests, causing it to become unavailable or unresponsive to legitimate users.</p><p>In Spring, there are several ways to mitigate DoS attacks. Here are some steps you can take to fix the issue:</p><ol><li>Limit request rates: You can limit the rate of incoming requests to your Spring application by using a rate limiter. This can prevent an attacker from overwhelming your application with too many requests.</li></ol><p>One way to implement a rate limiter in Spring is to use the Spring RateLimiter annotation. This annotation allows you to limit the number of requests that can be processed within a specified time period.</p><p>For example, you can annotate a method in your controller class with the @RateLimiter annotation like this:</p><pre>@RateLimiter(value = &quot;myMethod&quot;, limit = 10, duration = 1, timeUnit = TimeUnit.SECONDS)<br>public void myMethod() {<br>    // method code here<br>}</pre><p>This code limits the number of requests that can be processed by the myMethod() method to 10 requests per second.</p><ol><li>Use caching: Caching is a way to store frequently accessed data in memory, reducing the number of database queries and improving application performance. By caching frequently accessed data, you can reduce the load on your application and prevent DoS attacks.</li></ol><p>In Spring, you can use caching by enabling the Spring Cache abstraction and adding caching annotations to your methods. For example, you can annotate a method in your service class with the @Cacheable annotation like this:</p><pre>@Cacheable(&quot;users&quot;)<br>public User getUserById(int id) {<br>    // method code here<br>}</pre><p>This code caches the User object returned by the getUserById() method with the cache name “users”. Subsequent calls to this method with the same ID will return the cached User object, reducing the number of database queries and improving application performance.</p><ol><li>Use request throttling: Request throttling is a way to limit the number of requests that can be processed by your application within a specified time period. By limiting the number of requests that can be processed, you can prevent an attacker from overwhelming your application with too many requests.</li></ol><p>In Spring, you can implement request throttling by using a library like Spring Cloud Gateway or Spring Security. These libraries provide request throttling capabilities out-of-the-box, allowing you to limit the number of requests that can be processed by your application within a specified time period.</p><p>For example, you can configure request throttling in Spring Cloud Gateway by adding the following configuration to your application.yaml file:</p><pre>yamlCopy code</pre><pre>spring:<br>  cloud:<br>    gateway:<br>      routes:<br>        - id: myRoute<br>          uri: http://localhost:8080<br>          predicates:<br>            - Path=/myPath<br>          filters:<br>            - name: RequestRateLimiter<br>              args:<br>                redis-rate-limiter.replenishRate: 1<br>                redis-rate-limiter.burstCapacity: 2</pre><p>This code configures a route in Spring Cloud Gateway with request throttling enabled. The RequestRateLimiter filter limits the number of requests that can be processed to 1 request per second with a burst capacity of 2 requests.</p><p>By implementing these steps, you can significantly reduce the risk of DoS attacks in your Spring applications.</p><p>There are several steps you can take to fix configuration vulnerabilities in Spring:</p><ol><li>Secure sensitive configuration properties: Sensitive configuration properties such as database credentials, API keys, and passwords should be encrypted or stored in a secure location. In Spring, you can use the Spring Security framework to secure sensitive configuration properties. You can also use the Spring Cloud Config Server to store configuration properties in a secure location.</li><li>Disable debug mode: Debug mode can expose sensitive information about your application and its configurations. In Spring, you can disable debug mode by setting the logging level to a higher level, such as INFO or ERROR.</li><li>Use secure communication protocols: Communication between your Spring application and other services or clients should be encrypted using secure communication protocols such as HTTPS or TLS. In Spring, you can configure secure communication protocols using the Spring Security framework.</li><li>Use strong encryption algorithms: Encryption algorithms should be strong enough to prevent attackers from decrypting sensitive information. In Spring, you can use strong encryption algorithms by configuring encryption properties in the application.properties or application.yaml file.</li><li>Avoid hardcoding configuration values: Hardcoding configuration values such as URLs, paths, and ports can make your application vulnerable to attacks. In Spring, you can avoid hardcoding configuration values by using environment variables or external configuration files such as the application.properties or application.yaml file.</li><li>Validate user input: User input should be validated to prevent attackers from injecting malicious code into your application. In Spring, you can use validation annotations such as @NotBlank, @NotNull, and @Valid to validate user input.</li></ol><p>By implementing these steps, you can significantly reduce the risk of configuration vulnerabilities in your Spring applications. It’s important to keep your Spring application up to date with the latest security patches and follow secure coding practices to prevent future vulnerabilities.</p><p>One example of a configuration vulnerability in Spring is the exposure of sensitive information such as database credentials, API keys, or passwords in plain text in configuration files.</p><p>For instance, consider a Spring application that connects to a database to store and retrieve sensitive data. The database credentials are stored in the application.properties file in plain text as follows:</p><pre>spring.datasource.username=admin<br>spring.datasource.password=admin123<br>spring.datasource.url=jdbc:mysql://localhost:3306/mydb</pre><p>If an attacker gains access to the application.properties file, they can easily obtain the database credentials and potentially access the database.</p><p>To fix this configuration vulnerability, you can encrypt the sensitive configuration properties using Jasypt (Java Simplified Encryption). Jasypt is a library that provides simple encryption and decryption of text using a strong encryption algorithm.</p><p>Here’s an example of how you can encrypt the database credentials using Jasypt:</p><ol><li>Add the Jasypt dependency to your project:</li></ol><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.jasypt&lt;/groupId&gt;<br>    &lt;artifactId&gt;jasypt-spring-boot-starter&lt;/artifactId&gt;<br>    &lt;version&gt;2.2.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><ol><li>Generate an encryption key:</li></ol><pre>java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=&quot;admin123&quot; password=&quot;mysecretkey&quot; algorithm=PBEWithMD5AndDES</pre><p>This command generates an encrypted string for the password “admin123” using the encryption algorithm PBEWithMD5AndDES and the password “mysecretkey”. The encrypted string will be used in the application.properties file.</p><ol><li>Update the application.properties file with the encrypted properties:</li></ol><pre>spring.datasource.username=admin<br>spring.datasource.password=ENC(vyLfD2mWk4+Y4X9a/rFQ2Q==)<br>spring.datasource.url=jdbc:mysql://localhost:3306/mydb</pre><pre>jasypt.encryptor.password=mysecretkey</pre><p>Note that the password property is now encrypted using the prefix ENC, indicating that the value is encrypted. The jasypt.encryptor.password property is used to configure the Jasypt encryption algorithm.</p><p>By encrypting sensitive configuration properties using Jasypt, you can protect your Spring application from configuration vulnerabilities such as exposure of sensitive information in plain text.</p><p>One example of a vulnerability in Spring RestTemplate is the potential for <strong>Man-in-the-Middle (MitM) attacks </strong>due to the use of an unsecured connection.</p><p>For instance, consider a Spring application that uses RestTemplate to make API requests to a third-party service. The following code snippet shows an example of how RestTemplate can be used to make a GET request:javaCopy code</p><pre>RestTemplate restTemplate = new RestTemplate();<br>String response = restTemplate.getForObject(&quot;http://example.com/api&quot;, String.class);</pre><p>If the third-party service does not use HTTPS or TLS, the API request is transmitted over an unsecured connection, making it vulnerable to MitM attacks. An attacker can intercept the API request and modify or inject malicious content.</p><p>To fix this vulnerability, you can configure RestTemplate to use HTTPS or TLS to establish a secure connection with the third-party service. Here’s an example of how to configure RestTemplate to use HTTPS:</p><pre>RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());<br><br>private ClientHttpRequestFactory getClientHttpRequestFactory() {<br>    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory<br>                      = new HttpComponentsClientHttpRequestFactory();<br>    clientHttpRequestFactory.setHttpClient(getHttpClient());<br>    return clientHttpRequestFactory;<br>}<br>private HttpClient getHttpClient() {<br>    SSLContext sslContext = SSLContextBuilder.create()<br>                            .loadTrustMaterial(null, new TrustSelfSignedStrategy())<br>                            .build();<br>    HttpClient httpClient = HttpClients.custom()<br>                              .setSSLContext(sslContext)<br>                              .build();<br>    return httpClient;<br>}</pre><p>This code snippet shows how to create a custom HttpClient that uses SSL/TLS to establish a secure connection with the third-party service. The HttpClient is then passed to the HttpComponentsClientHttpRequestFactory, which is used to create the RestTemplate.</p><p>Note that this example uses a self-signed certificate, which is not recommended for production use. In a production environment, you should use a trusted SSL/TLS certificate issued by a trusted Certificate Authority.</p><p>By configuring RestTemplate to use HTTPS or TLS, you can protect your Spring application from vulnerabilities such as MitM attacks due to unsecured connections.</p><p><strong>Spring Server-Side Request Forgery (SSRF)</strong> vulnerabilities occur when an attacker can manipulate the URL or input parameters of a web application to send requests to an arbitrary server, including internal servers or servers outside the trusted network.</p><p>One example of an SSRF vulnerability in Spring is shown below:</p><pre>@RequestMapping(value = &quot;/fetch&quot;, method = RequestMethod.GET)<br>@ResponseBody<br>public String fetchData(@RequestParam(&quot;url&quot;) String url) throws IOException {<br>    URL obj = new URL(url);<br>    HttpURLConnection con = (HttpURLConnection) obj.openConnection();<br>    con.setRequestMethod(&quot;GET&quot;);<br><br>BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));<br>    String inputLine;<br>    StringBuffer response = new StringBuffer();<br>    while ((inputLine = in.readLine()) != null) {<br>        response.append(inputLine);<br>    }<br>    in.close();<br>    return response.toString();<br>}</pre><p>In this example, an endpoint is created that takes in a URL parameter and fetches the content of that URL using a GET request. However, this code is vulnerable to SSRF attacks since an attacker can pass in a URL that points to an internal server or to a vulnerable service running on a public-facing server.</p><p>To fix this vulnerability, you can implement input validation on the URL parameter to prevent the injection of malicious URLs. One approach is to use a whitelist of trusted domains and only allow requests to URLs that are within that whitelist.</p><pre>private static final List&lt;String&gt; WHITELISTED_DOMAINS = Arrays.asList(&quot;example.com&quot;, &quot;trusted.com&quot;);<br>@RequestMapping(value = &quot;/fetch&quot;, method = RequestMethod.GET)<br>@ResponseBody<br>public String fetchData(@RequestParam(&quot;url&quot;) String url) throws IOException {<br>    if (!isValidUrl(url)) {<br>        throw new IllegalArgumentException(&quot;Invalid URL&quot;);<br>    }<br>    URL obj = new URL(url);<br>    HttpURLConnection con = (HttpURLConnection) obj.openConnection();<br>    con.setRequestMethod(&quot;GET&quot;);<br>    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));<br>    String inputLine;<br>    StringBuffer response = new StringBuffer();<br>    while ((inputLine = in.readLine()) != null) {<br>        response.append(inputLine);<br>    }<br>    in.close();<br>    return response.toString();<br>}<br>private boolean isValidUrl(String url) {<br>    try {<br>        URI uri = new URI(url);<br>        String domain = uri.getHost();<br>        return WHITELISTED_DOMAINS.contains(domain);<br>    } catch (URISyntaxException e) {<br>        return false;<br>    }<br>}</pre><p>In this example, the isValidUrl method is used to validate the URL parameter against the whitelist of trusted domains. If the URL parameter is not valid or not within the whitelist, an IllegalArgumentException is thrown, preventing the request from being executed.</p><p>By implementing input validation on the URL parameter and using a whitelist of trusted domains, you can protect your Spring application from Server-Side Request Forgery (SSRF) attacks.</p><p><strong>Mass Assignment vulnerabilities</strong> in Spring occur when an attacker can manipulate the values of a request parameter to modify data fields that were not intended to be modified. This can happen if the application allows incoming requests to bind to model objects, and the attacker includes additional parameters to modify fields that should be protected.</p><p>One example of a Mass Assignment vulnerability in Spring is shown below:javaCopy code</p><pre>@PostMapping(&quot;/users&quot;)<br>public String createUser(@ModelAttribute(&quot;user&quot;) User user) {<br>    userService.saveUser(user);<br>    return &quot;redirect:/users&quot;;<br>}</pre><p>In this example, the createUser endpoint takes in a User object and saves it using the userService. However, if an attacker submits additional parameters to the request, those parameters could be used to modify fields that should not be modifiable, such as the user&#39;s role or password.</p><p>To fix this vulnerability, you can configure Spring’s binder to ignore certain fields that should not be modified by incoming requests. Here’s an example of how to configure the binder to ignore certain fields:javaCopy code</p><pre>@PostMapping(&quot;/users&quot;)<br>public String createUser(@ModelAttribute(&quot;user&quot;) @Validated User user, BindingResult result) {<br>    if (result.hasErrors()) {<br>        return &quot;createUserForm&quot;;<br>    }<br><br>PropertyValues propertyValues = new MutablePropertyValues()<br>            .add(&quot;firstName&quot;, user.getFirstName())<br>            .add(&quot;lastName&quot;, user.getLastName())<br>            .add(&quot;email&quot;, user.getEmail());<br>    WebDataBinder binder = new WebDataBinder(user);<br>    binder.initDirectFieldAccess();<br>    binder.setDisallowedFields(&quot;id&quot;, &quot;role&quot;, &quot;password&quot;);<br>    binder.bind(propertyValues);<br>    userService.saveUser(user);<br>    return &quot;redirect:/users&quot;;<br>}</pre><p>In this example, the WebDataBinder is used to bind incoming parameters to the User object. The setDisallowedFields method is used to exclude certain fields from being bound, preventing an attacker from modifying them.</p><p>By configuring the binder to exclude certain fields, you can protect your Spring application from Mass Assignment vulnerabilities. It’s important to note that this is just one of many ways to mitigate this type of vulnerability, and there may be other factors to consider depending on the specifics of your application.</p><p><strong>A race condition vulnerability occurs</strong> when multiple threads access and modify shared resources simultaneously, leading to unexpected and potentially harmful behavior. In a Spring application, this vulnerability can occur when multiple threads access and modify the same singleton bean member field.</p><p>Here’s an example of a Spring singleton bean with a member field that can be modified by multiple threads simultaneously:</p><pre>@Component<br>public class ExampleService {<br>    private List&lt;String&gt; data = new ArrayList&lt;&gt;();<br><br>public void addData(String newData) {<br>        data.add(newData);<br>    }<br>    public List&lt;String&gt; getData() {<br>        return data;<br>    }<br>}</pre><p>In this example, multiple threads can call the addData method simultaneously, leading to a race condition. If two threads call addData at the same time, the list may become corrupted, and data may be lost.</p><p>To fix this vulnerability, you can use synchronized methods or locks to ensure that only one thread can modify the shared resource at a time. Here’s an example of how to fix the above example using synchronized methods:</p><pre>@Component<br>public class ExampleService {<br>    private List&lt;String&gt; data = new ArrayList&lt;&gt;();<br><br><br>public synchronized void addData(String newData) {<br>        data.add(newData);<br>    }<br>    public synchronized List&lt;String&gt; getData() {<br>        return data;<br>    }<br>}</pre><p>In this example, the addData and getData methods are synchronized, ensuring that only one thread can modify or access the data list at a time. This prevents the race condition vulnerability from occurring.</p><p>Another option to fix this vulnerability is to use locks instead of synchronized methods. Here’s an example of how to fix the above example using locks:</p><pre>@Component<br>public class ExampleService {<br>    private List&lt;String&gt; data = new ArrayList&lt;&gt;();<br>    private final Lock lock = new ReentrantLock();<br><br>public void addData(String newData) {<br>        lock.lock();<br>        try {<br>            data.add(newData);<br>        } finally {<br>            lock.unlock();<br>        }<br>    }<br>    public List&lt;String&gt; getData() {<br>        lock.lock();<br>        try {<br>            return data;<br>        } finally {<br>            lock.unlock();<br>        }<br>    }<br>}</pre><p>In this example, the addData and getData methods use a ReentrantLock to lock the data list, ensuring that only one thread can modify or access it at a time. This also prevents the race condition vulnerability from occurring.</p><p>In summary, to fix the race condition vulnerability in Spring singleton bean member fields, you can use synchronized methods or locks to ensure that only one thread can modify the shared resource at a time.</p><p>Resource injection is a vulnerability that occurs when an attacker can inject malicious code into the resources of a Spring application. This can happen when the application uses resource injection to load resources dynamically at runtime.</p><p>Here’s an example of resource injection in a Spring application:</p><pre>@Controller<br>public class ExampleController {<br>    @Resource(name = &quot;userDao&quot;)<br>    private UserDao userDao;<br><br>@GetMapping(&quot;/users/{id}&quot;)<br>    public String getUser(@PathVariable(&quot;id&quot;) Long id, Model model) {<br>        User user = userDao.findById(id);<br>        model.addAttribute(&quot;user&quot;, user);<br>        return &quot;user&quot;;<br>    }<br>}</pre><p>In this example, the ExampleController class uses resource injection to load the userDao bean dynamically. However, if an attacker can modify the resource being injected, they can inject malicious code into the application.</p><p>To fix this vulnerability, you can use constructor injection or setter injection instead of resource injection. Here’s an example of how to fix the above example using constructor injection:</p><pre>@Controller<br>public class ExampleController {<br>    private final UserDao userDao;<br><br>public ExampleController(UserDao userDao) {<br>        this.userDao = userDao;<br>    }<br>    @GetMapping(&quot;/users/{id}&quot;)<br>    public String getUser(@PathVariable(&quot;id&quot;) Long id, Model model) {<br>        User user = userDao.findById(id);<br>        model.addAttribute(&quot;user&quot;, user);<br>        return &quot;user&quot;;<br>    }<br>}</pre><p>In this example, the ExampleController class uses constructor injection to load the userDao bean. This prevents an attacker from modifying the resource being injected at runtime, as the resource is loaded at application startup.</p><p>Alternatively, you can also use setter injection to load the resource. Here’s an example of how to fix the above example using setter injection:</p><pre>@Controller<br>public class ExampleController {<br><br>private UserDao userDao;<br><br>@Resource(name = &quot;userDao&quot;)<br>    public void setUserDao(UserDao userDao) {<br>        this.userDao = userDao;<br>    }<br>    @GetMapping(&quot;/users/{id}&quot;)<br>    public String getUser(@PathVariable(&quot;id&quot;) Long id, Model model) {<br>        User user = userDao.findById(id);<br>        model.addAttribute(&quot;user&quot;, user);<br>        return &quot;user&quot;;<br>    }<br>}</pre><p>In this example, the ExampleController class uses setter injection to load the userDao bean. This also prevents an attacker from modifying the resource being injected at runtime, as the resource is loaded at application startup.</p><p>In summary, to fix resource injection vulnerabilities in Spring, you can use constructor injection or setter injection instead of resource injection. This ensures that resources are loaded at application startup and prevents attackers from modifying them at runtime.</p><p><strong>Password management vulnerabilities in</strong> Spring can occur when developers include sensitive information such as passwords or API keys in comments or logs within the application code. Attackers can exploit this vulnerability to gain unauthorized access to the system or its resources.</p><p>Here’s an example of a password management vulnerability in Spring:</p><pre>public class ExampleService {<br>    private final String password = &quot;password123&quot;;<br>public void doSomething() {<br>        // This method uses the password to access a secure resource<br>        // ...<br>    }<br>}</pre><p>In this example, the password is hard-coded into the ExampleService class and is used to access a secure resource. However, the password is stored in plain text and can be easily viewed by anyone who has access to the code. This makes the password vulnerable to attackers who can gain unauthorized access to the system.</p><p>To fix this vulnerability, you can use external configuration files or environment variables to store sensitive information such as passwords. Here’s an example of how to fix the above example using external configuration files:</p><p>application.properties file:</p><pre>example.password=password123</pre><pre>@Configuration<br>public class ExampleConfig {<br>    @Value(&quot;${example.password}&quot;)<br>    private String password;<br>@Bean<br>    public ExampleService exampleService() {<br>        return new ExampleService(password);<br>    }<br>}<br>public class ExampleService {<br>    private final String password;<br>    public ExampleService(String password) {<br>        this.password = password;<br>    }<br>    public void doSomething() {<br>        // This method uses the password to access a secure resource<br>        // ...<br>    }<br>}</pre><p>In this example, the password is stored in an external configuration file and is loaded into the ExampleConfig class using the @Value annotation. The ExampleService class is then instantiated with the password value as a constructor argument.</p><p>This approach ensures that the password is not stored in plain text within the application code, making it more secure and less vulnerable to attackers.</p><p>In summary, to fix password management vulnerabilities in Spring, you can use external configuration files or environment variables to store sensitive information such as passwords. This ensures that the password is not stored in plain text within the application code and is less vulnerable to attackers.</p><p>Path manipulation vulnerabilities in Spring can occur when the application code does not properly sanitize user input before using it to construct file paths or URLs. Attackers can exploit this vulnerability to access or modify files or resources on the server that they should not have access to.</p><p>Here’s an example of a path manipulation vulnerability in Spring:</p><pre>@RestController<br>public class ExampleController {<br>    @GetMapping(&quot;/files/{fileName}&quot;)<br>    public ResponseEntity&lt;Resource&gt; downloadFile(@PathVariable String fileName) {<br>        Resource resource = new FileSystemResource(&quot;/path/to/files/&quot; + fileName);<br>        // ...<br>    }<br>}</pre><p>In this example, the fileName variable is used to construct a file path without proper input validation or sanitization. An attacker can manipulate the fileName parameter to access or modify files outside of the intended directory.</p><p>To fix this vulnerability, you should validate and sanitize user input before using it to construct file paths or URLs. Here’s an example of how to fix the above example:</p><pre>@RestController<br>public class ExampleController {   <br> @GetMapping(&quot;/files/{fileName}&quot;)<br>    public ResponseEntity&lt;Resource&gt; downloadFile(@PathVariable String fileName) throws MalformedURLException {<br>        String sanitizedFileName = sanitizeInput(fileName);<br>        URL fileUrl = new URL(&quot;file:/path/to/files/&quot; + sanitizedFileName);<br>        Resource resource = new UrlResource(fileUrl);<br>        // ...<br>    }<br>private String sanitizeInput(String input) {<br>        // Sanitize the input to prevent path manipulation attacks<br>        // ...<br>        return sanitizedInput;<br>    }<br>}</pre><p>In this example, the fileName parameter is first passed through a sanitizeInput() method to validate and sanitize the user input. The sanitizedFileName is then used to construct a URL object using the UrlResource class. The UrlResource class is used instead of the FileSystemResource class to ensure that the file path is properly escaped and validated.</p><p>This approach ensures that user input is properly validated and sanitized before being used to construct file paths or URLs, making the application less vulnerable to path manipulation attacks.</p><p>In summary, to fix path manipulation vulnerabilities in Spring, you should validate and sanitize user input before using it to construct file paths or URLs. This ensures that user input is properly validated and sanitized before being used to access files or resources, making the application less vulnerable to path manipulation attacks.</p><p><strong>Weak cryptographic hash algorithms can </strong>be exploited by attackers to crack password hashes and gain access to user accounts. In Spring, this vulnerability can occur if weak cryptographic hash algorithms are used to store user passwords.</p><p>Here’s an example of a weak cryptographic hash vulnerability in Spring:</p><pre>@Service<br>public class UserServiceImpl implements UserService {<br><br>@Autowired<br>    private UserRepository userRepository;<br>    @Override<br>    public void createUser(String username, String password) {<br>        String hash = DigestUtils.md5DigestAsHex(password.getBytes());<br>        User user = new User(username, hash);<br>        userRepository.save(user);<br>    }<br>    @Override<br>    public User authenticate(String username, String password) {<br>        String hash = DigestUtils.md5DigestAsHex(password.getBytes());<br>        User user = userRepository.findByUsernameAndPassword(username, hash);<br>        return user;<br>    }<br>}</pre><p>In this example, the createUser() method is using the MD5 algorithm to hash the user&#39;s password. MD5 is considered a weak cryptographic hash algorithm and can be easily cracked by attackers using modern hardware and techniques. This makes it easier for an attacker to gain access to user accounts.</p><p>To fix this vulnerability, you should use stronger cryptographic hash algorithms to store user passwords. Here’s an example of how to fix the above example:</p><pre>@Service<br>public class UserServiceImpl implements UserService {<br>@Autowired<br>private UserRepository userRepository;<br>@Override<br>public void createUser(String username, String password) throws NoSuchAlgorithmException {<br>String hash = generateHash(password);<br>User user = new User(username, hash);<br>userRepository.save(user);<br>}<br>@Override<br>public User authenticate(String username, String password) throws NoSuchAlgorithmException {<br>String hash = generateHash(password);<br>User user = userRepository.findByUsernameAndPassword(username, hash);<br>return user;<br>}<br>private String generateHash(String password) throws NoSuchAlgorithmException {<br>// Use a stronger cryptographic hash algorithm to hash the user&#39;s password<br>MessageDigest digest = MessageDigest.getInstance(&quot;SHA-256&quot;);<br>byte[] hashBytes = digest.digest(password.getBytes(StandardCharsets.UTF_8));<br>String hash = DatatypeConverter.printHexBinary(hashBytes);<br>return hash;<br>}<br>}</pre><p>In this example, the generateHash() method is using the SHA-256 algorithm to hash the user&#39;s password. SHA-256 is a stronger cryptographic hash algorithm than MD5 and is less susceptible to cracking by attackers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11a2ea8c7077" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Framework Property Placeholder kullanımı]]></title>
            <link>https://kbrautman.medium.com/spring-framework-property-placeholder-kullan%C4%B1m%C4%B1-ecb6574f23f4?source=rss-91247c2ada0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecb6574f23f4</guid>
            <category><![CDATA[placeholder]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[property]]></category>
            <category><![CDATA[property-placeholder]]></category>
            <dc:creator><![CDATA[Kübra Utman]]></dc:creator>
            <pubDate>Mon, 14 Mar 2022 18:06:02 GMT</pubDate>
            <atom:updated>2022-03-14T18:06:02.002Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba arkadaşlar bu yazımda sizlere Spring Framework de placeholder kullanımından bahsetmek istiyorum.</p><p><em>&lt;context:property-placeholder /&gt;</em> tagı PropertyPlaceholderConfigurer ı otomatik ayarlayıp configure eder ve böylece properties dosyalarındaki değerlere @value anotation ı sayesinde ${} ile içindeki değerleri okuyabiliriz.</p><p>Öncelikle applicationContext.xml de kullanmak isteğimiz dosyalar için bu tagı ekliyoruz. Buraya birden fazla properties dosyası vermek istiyorsak araya virgül koyup ekleyebiliriz.</p><pre>&lt;context:property-placeholder location=&quot;file:/application.properties&quot; /&gt;</pre><p>application.properties dosyasındaki değerleri set ve get edeceğimiz bean i de aynı şekilde applicationContext.xml dosyasında ekliyoruz.</p><pre>&lt;bean id=&quot;configparameter&quot; class=&quot;com.utmn.parameters.ConfigParameters&quot; /&gt;</pre><p>Gelelim bean i mize, ConfigParamaters da şimdi ${} ile beraber değerlerimizi alabiliriz.</p><pre>@Data<br>public class ConfigParameters{</pre><pre>@Value(&quot;${projectVersion}&quot;)<br>private String projectVersion;</pre><pre>@Value(&quot;${userName}&quot;)</pre><pre>private String userName;</pre><pre>}</pre><p>application.properties dosyamızda şu şekildedir.</p><pre>projectVersion = 3.4.2<br>username=testuser</pre><h3>Fallback ve override system properties</h3><p>Default olarak, placeholder belirtilen properties dosyaları tarafından çözülemezse, Spring bunu bir system property ile çözmeye çalışacaktır. Örneğin, Spring <strong>${user.dir} placeholder çözemezse , karşılık gelen user.dir</strong> system property i deneyecektir . Bu çağrı , system properties modu fallback dir. PropertyPlaceholderConfigurer’ın systemPropertiesModeName adlı bir property belirterek bu davranışı değiştirebiliriz</p><pre>&lt;context:property-placeholder system-properties-mode=&quot;FALLBACK&quot;location=&quot;file:/application.properties&quot; /&gt;</pre><p>Spring, aşağıdaki gibi üç mod sağlar:</p><ul><li>FALLBACK : Bu, yukarıda belirtildiği gibi varsayılan moddur.</li><li>OVERRIDE : Spring önce placeholder ı system property ile çözecektir. Bir system property varsa, değeri, properties dosyasındaki değeri geçersiz kılar.</li><li>NEVER : Spring, placeholder ı çözümlerken sistem özelliklerini dikkate almaz.</li></ul><h3>İstisnaları yoksaymak (Ignore Exceptions)</h3><p>Spring, bir properties dosyası bulamazsa veya bir placeholder ı çözemezse varsayılan olarak bir exception fırlatır. Bu, uygulamanın başlamamasına neden olur.</p><p>Bir properties dosyasının bulunamaması durumunda atılacak olan exception yok saymak için PropertyPlaceholderConfigurer bean’in aşağıdaki özelliğini belirtin:</p><pre>&lt;context:property-placeholder system-properties-mode=&quot;FALLBACK&quot; location=&quot;file:/application.properties&quot; ignore-resource-not-found=&quot;true /&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecb6574f23f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tsconfig.json dosyası ne işe yarar ?]]></title>
            <link>https://kbrautman.medium.com/tsconfig-json-dosyas%C4%B1-ne-i%C5%9Fe-yarar-be075b080ef2?source=rss-91247c2ada0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/be075b080ef2</guid>
            <category><![CDATA[tsconfig]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Kübra Utman]]></dc:creator>
            <pubDate>Mon, 18 Jan 2021 18:29:24 GMT</pubDate>
            <atom:updated>2021-01-18T18:29:24.120Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tsconfig.json dosyası ne işe yarar ?</h3><p>Merhaba arkadaşlar size Angular’da bulunan tsconfig.json dosyasının ne işe yaradığını anlatmak istiyorum.</p><p>TypeScript özellikleri son derece faydalıdır. Run time zamanından önce syntax hatalarını denetler. Hatta bazı kodların neden hata verebileceğini gösteren ipuçları bile saptar. Bazen Typescript’in uygulamaya çalıştığı tüm varsayılan kuralları uygulamak istemezsiniz. Bunun için tsconfig.json dosyası bunu bize sağlar. Ek olarak TypeScript derleyicisine hangi dosyaların çalıştırılacağını ve daha fazlasını yazabiliriz.</p><p>Öyleyse bu dosyanın neye benzediğini ve nasıl yardımcı olduğunu inceleyelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*cR2KjtXE-DAmnPjc1T4A6w.png" /></figure><p>Tsconfig.json dosyası her zaman projenizin kök dizinine yerleştirilir.</p><p>TypeScript derleyicisinin uygulamasını istediğiniz kuralları özelleştirebilirsiniz.</p><p>Tsconfig.json da birkaç özellik vardır:</p><p>TypeScript derleyicisinin uygulayacağı kuralları compilerOptions adı verilen nesnemize yazmalıyız.</p><p>Burda “target” “es2015” değeri projenin JavaScript için ECMAScript standartlarının 2015 sürümünü kullanacağı anlamına gelir.</p><p>“module” ise bu proje modülleri içe ve dışa aktarmak için commonjs i kullanacaktır.</p><p>“strictNullChecks” değişkenler eğer true atanmışsa null veya undefined değer olabilir.</p><p>“include” derleyicinin kuralları hangi dosyalara uygulanacağını belirtir.</p><p>Bu durumda [“**/*.Ts”] derleyicinin .ts uzantılı her dosyayı kontrol etmesi gerektiği anlamına gelir.</p><p>Bu kuralları seçtik çünkü size hangi kuralları uygulayacağınıza dair fikir vermek istedik.</p><p>Kendi projelerinizin için kuralları kendi tercihlerinize göre belirleyebilirsiniz. Tsconfig.json dosyası hem bireysel çalışma hem de ekip projeleri için harikadır. Çünkü herkesin aynı sayfada kodlarını nasıl yazacakları konusunda izin verir.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be075b080ef2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlinde RecyclerView kullanımı]]></title>
            <link>https://kbrautman.medium.com/kotlinde-recyclerview-kullan%C4%B1m%C4%B1-383f8a72e112?source=rss-91247c2ada0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/383f8a72e112</guid>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Kübra Utman]]></dc:creator>
            <pubDate>Mon, 24 Dec 2018 20:01:15 GMT</pubDate>
            <atom:updated>2018-12-25T09:21:56.297Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba arkadaşlar, Önceki yazımda recyclerView i temel olarak anlatmaya çalıştım Bu yazıyı okumadan önce göz atabilirsiniz.</p><p><a href="https://medium.com/@kbrautman/kotlin-recyclerviewe-giri%C5%9F-d7785d68396">Kotlin RecyclerView’e Giriş</a></p><p>Şimdi RecyclerView i uygulamamızda kullanmak için öncelikle Android Studiodan bir proje açalım. Ben bu uygulamada <a href="https://medium.com/@kbrautman/kotlin-retrofit-kullan%C4%B1m%C4%B1-663d9ab551f6">önceki yazımda</a> retrofit kullanımında hazırladığım recyclerView i mi anlatacağım.</p><p>Proje Kurulumu</p><ol><li>RecyclerView bağımlılığının proje kütüphanesine dahil edildiğinden emin olarak proje oluşturmaya başlamalıyız. Bu yüzden build.gradle (module: app) kısmına ekleyin.</li></ol><pre>dependencies {<br>    implementation &#39;com.android.support:recyclerview-v7:28.0.0&#39;<br>}</pre><p>2. RecyclerView i hangi activity de kullanmak istiyorsanız onu activity_main.xml ine eklememiz gerekir. Projemizde recyclerView imizi ekledik.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxSnptMxKaM9gJLuXpRYUw.png" /></figure><p>Ö<a href="https://medium.com/@kbrautman/kotlin-retrofit-kullan%C4%B1m%C4%B1-663d9ab551f6">nceki yazımda</a> Retrofit ten bahsetmiştim ve kullandığım api den bir data class oluşturmuştum. Biz recyclerView de kullanacağımız veriler için de Hero classımızı api den bakıp tasarlamıştık. <a href="https://www.simplifiedcoding.net/demos/marvel/">Burdaki link</a>ten bakıp dto classımızı oluşturduk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQOxhb9moYK2FeMR0H12IA.png" /></figure><p>Şimdi recycler view imizin bir item inda ne görüntülemek istiyorsak onu tasarlamak için heroes_list_item.xml adında bir layout oluşturduk. Ben layoutu şu şekilde ekledim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kALJw8YHNPSqJ2WbIGPFvw.png" /></figure><p>Bu componentleri bağlamak için sıra ViewHolder ımızı oluşturmaya geldi. heroes_list_item.xml da oluşturduğum her bir view i ViewHolder a ekliyorum. Bunları</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acGoZABTtmEsgJ7-Gtv03Q.png" /></figure><p>Burda gördüğünüz gibi heroesViewHolder recyclerView.ViewHolder dan extend edildi ve oluşturduğumuz layoutumuzu inflate ettik. Bu componentlere adapter classından ulaşmak içinde bindTo metodunu yazdık.</p><p>HeroesAdapter kısmına bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8YwVBfz3mKiGKUjilnBX_g.png" /></figure><p>Adapter classımızı da RecyclerView.Adapter dan extend ettik ve type olarak HeroesViewHolder ı verdik. Classımız bizden primary constructer beklediği için List tipinde classımızı ekledik. Önceki yazımda bunun json tipinden dolayı list tipinde olduğunu anlatmıştım. Daha sonra Adapter classımızdaki 3 metodumuzu override ettik.</p><p>Tüm bunları yaptıktan sonra biz hangi Activity mizde recyclerView kullanacaksak 2 şeyle onu çağırmamız gerekir.</p><p>1. layoutManager ile recyclerView in tipini belirlemek.</p><p>2. recyclerView e adapter ından ulaşmak.</p><p>MainAcitivty.kt</p><p>Activity dosyamızdan recyclerView’e id si ile erişiyoruz ve layoutManager ile LinearLayout şeklinde görülmesini sağlıyoruz. Daha sonra adapter ile bağlıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nm_ga4xrgNZxgJSaQUA3Q.png" /></figure><p>Bu yazının devamı olarak burdan devam edebilirsiniz.</p><p><a href="https://medium.com/@kbrautman/kotlin-retrofit-kullan%C4%B1m%C4%B1-663d9ab551f6">Kotlin Retrofit Kullanımı</a></p><p>Kotlini yeni öğrenmeye başlayan biri olarak ve Mediumda yeni yazmaya başlayan biri olarak yazdığım eksiklikler için şimdiden özür dilerim okuduğunuz için teşekkürler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=383f8a72e112" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin RecyclerView’e Giriş]]></title>
            <link>https://kbrautman.medium.com/kotlin-recyclerviewe-giri%C5%9F-d7785d68396?source=rss-91247c2ada0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7785d68396</guid>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <dc:creator><![CDATA[Kübra Utman]]></dc:creator>
            <pubDate>Mon, 24 Dec 2018 19:55:21 GMT</pubDate>
            <atom:updated>2018-12-25T09:22:57.074Z</atom:updated>
            <content:encoded><![CDATA[<h3>RecyclerView’e Giriş</h3><p>Merhaba Arkadaşlar bu yazımda sizlere kendi anlayabildiğim ve anlatabileceğim kadarıyla RecyclerView dan bahsetmek istiyorum. RecyclerView Android 5.0 ile gelen ve liste oluştururken kullanacağımız performanslı ve esnek bir View sınıfıdır.</p><p>Activity de görüntülenecek olan bir ya da birkaç component kullanacaksak ve bunların sayısını bilmiyorsak her seferinde layout a view ları yeniden yüklemek yerine RecyclerView bunları görüntülememizi sağlar. Tüm view ları başlangıçta Activity ye yüklemek CPU için bir yüktür ve CPU yu boşa harcar. Android cihazlarımızın belleğini sınırlı sayarsak bu bizim için kötü bir durumdur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*8go_yZFE5Gf9au_P48_qKw.png" /></figure><p>RecyclerView’ ın yaptığı şey, ilk önce ekranda gösterilecek olan sadece 4 view oluşturur ve kaydırmaya başladığımızda, yeterli sayıda view oluşturur (Bu örnekte, toplam 8 view oluşturur (4 + 4)) ve Görünür alandan çıkan view lar saklanır. Bu nedenle, CPU Döngüsü sayısı, viewlar için 30&#39;dan 8&#39;e düşürüldüğü için azaltılır. Böylece CPU yükü azalır. Bu da listView e göre daha performanslı olduğunu gösterir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qy8Lxk22w5dABLEtOD60jA.png" /></figure><p>RecyclerView oluştururken bizim için 4 şey gereklidir.</p><ol><li>Layout -Bu bizim her bir satırımızda ya da sütunumuzda çoğullamak istediğimiz componentleri eklediğimiz xml dosyasıdır.</li><li>ViewHolder, RecyclerView ve Adapter ın temel taşıdır. ViewHolder da oluşturduğumuz layouttaki view nesnelerinin önbelleğini saklarız.</li><li>LayoutManager, Adapter ın görünümlerinin alınmasına yardımcı olan ve RecyclerView ile verilerin ekrandaki görünümlerini ayarlamamızı sağlar.Linear layout, GridLayout vs seçebilirsiniz.</li><li>Adapter, Veri kaynağı ya da veri setinden verileri alıp bunları Kullanıcıya sunma görevi vardır. Ne şekilde sunmamızı ayarlamak içinde Adapter da bulunan 3 metodu override etmemiz gerekir.</li></ol><p>1. onCreateViewHolder()</p><p>Bu method adapter oluşturulduğunda oluşturduğumuz ViewHolder’ ın başlatılması için çağrılır.</p><p>2. onBindViewHolder()</p><p>onCreateViewHolder’ dan dönen verileri bind etme işlemini gerçekleştirildiği metottur.</p><p>3. getItemCount()</p><p>Listemizin eleman sayısını döndüren metottur.</p><p>Okuduğunuz için teşekkürler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7785d68396" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Retrofit Kullanımı]]></title>
            <link>https://kbrautman.medium.com/kotlin-retrofit-kullan%C4%B1m%C4%B1-663d9ab551f6?source=rss-91247c2ada0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/663d9ab551f6</guid>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[retrofit2]]></category>
            <category><![CDATA[json-api]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Kübra Utman]]></dc:creator>
            <pubDate>Tue, 06 Nov 2018 15:56:17 GMT</pubDate>
            <atom:updated>2018-12-25T09:32:38.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*O7i4QVeEHa1BZ_q8" /></figure><p>Bu yazımda sizlere Kotlinde retrofit kullanımını anlatacağım. Öncelikle Json ın çıkış amacı veri transferlerinde verilerin XML’den daha az yer kaplamasını sağlamak. Bizim birçok yerde uzak sunuculara request atmamızı sağlıyor. Uygulamamıza başlamadan önce kullanacağımız Json verilerini analiz etmek için tarayıcınıza şu eklentiyi ekleyebilirsiniz.</p><p><a href="https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa">JSON Formatter</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XH93wg6eNXm0o_ZJPAu7lw.png" /></figure><p>Uygulamamızın için öncelikle android manifest dosyasında internet izni alalım.</p><p>Android Studiodan yeni bir proje açalım. 1. adım projemize retrofit kütüphanesini dahil etmek.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvzPxOWNG4s50ptCHMfE4g.png" /></figure><p>Retrofit kütüphanesini uygulamamıza dahil ediyoruz. Ben uygulamamda bu <a href="https://www.simplifiedcoding.net/demos/marvel/"><strong>linkteki</strong></a> json i kullanacağım. Json dosyasına bakarak uygulamamızda data classlarımı oluşturalım. Json objelerimizdeki değişkenler ile data classlarımdaki değişkenler aynı olmak zorunda buna dikkat edelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzItRyXFlFei7n4FTDNacw.png" /></figure><p>2. adımda Json dosyamıza bakarak Classlarımızı oluşturmak. Bizde Hero adında data classı oluşturduk.</p><p>3. adım olarak Ağ isteklerini Retrofit ile RESTful API’ye göndermek için RetrofitClient adında bir sınıf oluşturduk. Retrofit Builder kullanarak Companion object ile singleton bir yapı sağlayarak classımıza adıyla erişebilmemizi sağlıyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yi-7Nv-qTsG3QNQJ0bdLDg.png" /></figure><p>Burada classımızda kullacağımız API nin baseurl i ve JSON <em>verimizi</em> daha önce tanımladığımız Hero classına <em>eşleyecek</em> olan <em>GsonConverterFactory’yi ekledik.</em></p><p>4. adım olarak Requestlerimi atacağımız bir service classı oluşturmak için interface tanımladık. Requestin tipini belirledik.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ecM5EZ7Mag3zPJFNewh42A.png" /></figure><p>İnterface imizde requestin tipini <strong>GET()</strong> olarak belirledik ve baseurl den sonra gelecek olan kısmı yazdık. Bu requestin sonucunu göndermek için bir fonksiyon oluşturduk . Call&lt;List&lt;Hero&gt;&gt; ile json tipi array olduğu için List dedik ve sorguyu cast edeceğimiz yeri belirttik.</p><p>Şimdi json dan uygulamamızda göstermek istediğimiz alanlar için Recycler view kullanacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3x5QNoRHRCh-rNDXgXa39Q.png" /><figcaption>Ben MainActivity de recyclerView kullandım. Android cihazda sadece ekrana sığan kısmını görürsünüz bu yüzden ScrollView kullandık böylece sayfada aşağı doğru nesneleri yerleştirebiliz.</figcaption></figure><p>MainActivity de request atacağımız classımıza erişmek için RetrofitClient tan Service interface ine eriştik ve istek atacağımız metotu çağardık. Sonrasında</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ziPUAlAM8DhkJtovkCkVVQ.png" /></figure><p>enqueue() asenkron bir istek göndermemizi sağlıyor ve yanıt geldiği zaman belirtmek için Callback ile classımızı kullandık .</p><p>enqueue() kullanarak 2 metodu implement ederiz.</p><ul><li>onResponse()</li><li>onFailure ()</li></ul><p>onResponse() alınan http yanıtı sonucunda yapacaklarımız için kullanırız. onFailure() sunucu ile iletişim kurarken yada yanıt işlenirken beklenmedik bir istisna oluştuğunda çağırılır. Bu metotları override ettik.</p><p>Biz burda recylerView mizde görüntülemek için response.body() metodundan gelecek cevabımızı ekledik. Uygulamamız bitti :)</p><p>Uygulamanın recyclerView kısmını burdan inceleyebilirsiniz.</p><p><a href="https://medium.com/@kbrautman/kotlinde-recyclerview-kullan%C4%B1m%C4%B1-383f8a72e112">Kotlinde RecyclerView kullanımı</a></p><p>Umarım sizin için yararlı olmuştur. Uygulamanın tamamını <a href="https://github.com/utmankbra/RetrofitKotlin">buradan</a> inceleyebilirsiniz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=663d9ab551f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Kullanımı]]></title>
            <link>https://kbrautman.medium.com/git-kullan%C4%B1m%C4%B1-c2a43163d04?source=rss-91247c2ada0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2a43163d04</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[repositories]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Kübra Utman]]></dc:creator>
            <pubDate>Thu, 11 Oct 2018 12:27:37 GMT</pubDate>
            <atom:updated>2018-10-11T12:27:37.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*EB9AtjrrbGZEUSi2t4SA3w.jpeg" /></figure><p>Git bir versiyon kontrol sistemidir. Bilgisayar üzerinde herhangi bir dosyada kullanılabilir. Açık kaynak kodludur. Git ,hemen hemen tüm dosya türlerini destekler. Yaptığımız projeleri adım adım versiyonlayarak ihtiyaç halinde bu versiyonlara kolayca geri dönebiliriz.</p><p><strong>Git e neden ihtiyaç duyulur?</strong></p><p>Bir proje ya da dosyada değişiklik yaptığımızda önlem almak amacıyla kopyalar oluştururuz.Bu işlemi tekrar tekrar uygulamak dosya sistemlerini karmaşık hale getirir. Bu yüzden de git sayesinde bu karmaşıklığın önüne geçilir.</p><p><strong>İlk Git Projesinin Oluşturulması</strong></p><p>Terminale gidip git — version yazarak git kurulumu yapıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*zFmyGSv2rg7YdZtAUAikig.png" /></figure><p>Git sistemine versiyon kontrolü kim tarafından yapılacağını tanımlıyoruz. Kullanıcı adı ve email ekledik.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*Q9EZbBFBkDUBGUd0mod7yg.png" /></figure><p>Kurulumumuzu tamamladık. Hadi şimdi versiyon kontrolü sağlamak istediğimiz klasöre terminalden erişelim ve terminale <strong>git init</strong> yazalım.</p><p><strong>Projemi git repository sine nasıl eklerim?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*y5DgB8J5Ig-o1DlyS2O97g.png" /></figure><p>Projemizde anlık olarak yaptığımız değişiklikler ve eklemeler working directory de gerçekleşir. Eğer git versiyonlama kullanacaksak<strong> git add .</strong> diyerek bu değişiklikleri Staging Area ya aktarırız. Burada bu değişiklikleri kontrol edebiliriz. Bu değişiklikleri git reposuna eklemek içinde commit etmemiz gerekir.</p><p><strong>İlk git projesinin oluşturulması</strong></p><p>Git versiyonu kullanacağım projeme terminalden ulaştıktan sonra git versiyonunu git init yazarak ayarlıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*KetwMztWGUYlj6eMvP4bsg.png" /></figure><p>Böylece git dizinlerini ekledik. Burada git dosyalarını görüntülemek istiyorsak Ls -a diyerek bakabiliriz. Git ile alakalı dosyalar projemizin takip edeceğimiz versiyonları içerir.</p><p><strong>Projenin git repository sine eklenmesi</strong></p><p>Git add . yazarak ekleriz fakat şuanda eklediğimiz dosyalar staging area denilen geçiş bölgesinde bulunur. Bunları git deposuna eklemek için commit etmemiz gerekir.Git commit -m “ilk versiyon ” yazarız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*IHdScX9P1eqakLjIVClC9A.png" /></figure><p><strong>Git status</strong></p><p>Hangi değişikliklerin geçiş bölgesine aktarılıp hangilerinin aktarılmadığını gösterir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*mEpzpMWrp1MZpcuC_RU8uA.png" /></figure><p>Örneğin burada yapılan değişiklikleri gösteriyor. Yaptığımız değişiklikleri onaylayıp repository ye göndermek için commitlemeliyiz. Bu yüzden önce working directoryde olan değişiklikleri önce staging area ya alıp sonra da commitleyip repository ye gönderiyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*bVsKBJ5nXiuiXy-tmWWxfQ.png" /></figure><p>Yaptığımız değişiklikler repository ye gönderilip gönderilmediğini kontrol etmek için tekrar git status yazıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*h82v6a7XVV3yDGpEFVuiyw.png" /></figure><p>Bu bizim tüm değişiklikleri repository ye gönderdiğimizi gösteriyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*qBE7sm30jIEU4WoErU7RpA.png" /></figure><p><strong>Git Log </strong>Komutuyla comittlerimizi inceleyebiliriz.</p><p><strong>Git diff </strong>komutu bize dosyada yapılan değişiklikleri satır satır gösterir. Ekleme yaptığımız kısım + ile ifade edilir. Silinenler ise -ile ifade edilir. Git diff, working directory ile staging area (index) arası farkları verir. Git diff –staged ise staging area ile git directory(repository) arasındaki farkları verir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*W_K9tAnxETMeJc4Cd2hmLg.png" /></figure><p>Git i daha detaylı anlamak istiyorsanız <a href="https://www.udacity.com/course/how-to-use-git-and-github--ud775">buradan</a> videolar izleyebilirsiniz. Hataları geri alabileceğiniz gitli projeleriniz olsun :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2a43163d04" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>