<?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 Ebinazerselvaraj on Medium]]></title>
        <description><![CDATA[Stories by Ebinazerselvaraj on Medium]]></description>
        <link>https://medium.com/@ebinazerselvaraj206?source=rss-25e8d881b82b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ql9_l-t8E9TVAfk2OEdXJw.jpeg</url>
            <title>Stories by Ebinazerselvaraj on Medium</title>
            <link>https://medium.com/@ebinazerselvaraj206?source=rss-25e8d881b82b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 07:55:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ebinazerselvaraj206/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding A Basic RAG Application]]></title>
            <link>https://medium.com/@ebinazerselvaraj206/understanding-a-basic-rag-application-6ac69c6bdb0f?source=rss-25e8d881b82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ac69c6bdb0f</guid>
            <category><![CDATA[basic-rag]]></category>
            <category><![CDATA[rag-application]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[rag-for-beginner]]></category>
            <dc:creator><![CDATA[Ebinazerselvaraj]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 06:45:18 GMT</pubDate>
            <atom:updated>2026-03-18T12:49:52.309Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog helps in understanding a basic RAG workflow.</p><h4>1) Introduction</h4><p>RAG means Retrieval Augmented Generation. RAG gives additional information to an LLM from documents and databases.</p><p>In general, ChatGPT and LLMs are trained until a particular date.</p><p>For example, if you ask ChatGPT, “Did you train up to date?” it will respond, “No, I am trained until August 2025.”</p><p>If you ask something about your company or personal questions, it won’t give an answer.</p><p>The main idea of RAG is that you can give company or personal documents as input, and you can ask queries from your documents. RAG gives answers based on those documents.</p><h4>2) Understanding a work flow</h4><p>It works based on two pipelines:</p><p>i) Ingestion pipeline <br>ii) Retrieval pipeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7IE77TFUOxweYzxgvz5NDg.png" /></figure><p>From the image:</p><p>Step 1) If we upload a source file (documents) <br>Step 2) It converts them into small chunks <br>Step 3) Then those chunks are converted into embedding values and stored along with the chunks in a vector DB</p><p>Example format:</p><p>{<br> “id”: “1”,<br> “embedding”: [0.012, -0.441, 0.982, …],<br> “document”: “chunks”,<br> “metadata”: {<br> “source”: “docs/spacex.txt”,<br> “chunk”: 3<br> }<br>}</p><p>Step 4) We give a query <br>Step 5) The query is converted into an embedding value <br>Step 6) Retrieval: based on the query embedding, it retrieves the matched chunks from the vector DB</p><p>Work behind this:</p><p>It uses a cosine similarity algorithm.</p><p>Formula:<br>cosine similarity = (a · b) / (||a|| * ||b||)</p><p>a -&gt; document chunk embedding value <br>b -&gt; query embedding value <br>||a|| -&gt; magnitude (length) of ‘a’ — it always starts with ‘1’ <br>||b|| -&gt; magnitude (length) of ‘b’ — it always starts with ‘1’</p><p>Workflow example:</p><p>Query: How to train a dog <br>Vector: [0.6, 0.3, 0.2, 0.7]</p><p>Chunk: Dog training techniques and methods <br>Chunk vector: [0.7, 0.4, 0.1, 0.6]</p><p>= ((0.6 * 0.7) + (0.3 * 0.4) + (0.2 * 0.1) + (0.7 * 0.6))</p><p>= 0.42 + 0.12 + 0.02 + 0.42</p><p>= 0.98</p><p>The value closest to 1 has the highest probability of matching the data.</p><h4>for coding u check my git hub</h4><p><a href="https://github.com/ebinazer005/basic_rag">https://github.com/ebinazer005/basic_rag</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ac69c6bdb0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple langChain Ai Assistent]]></title>
            <link>https://medium.com/@ebinazerselvaraj206/simple-langchain-ai-assistent-716ba0de3a15?source=rss-25e8d881b82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/716ba0de3a15</guid>
            <category><![CDATA[langchain-agents]]></category>
            <dc:creator><![CDATA[Ebinazerselvaraj]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 16:37:51 GMT</pubDate>
            <atom:updated>2025-11-12T16:37:51.802Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog we going to create a simple ai Assistent using long chain</p><p>lang chain?<br> <br> -lang chain is open source ai framework<br> -using lang chain we can create a LLM powered application <br> -we can using prebuild LLM components to build a application</p><p>lang chain using scenario <br> <br> user input — — — — — → <br> data retrieval from the external website or database — →<br> pass the retrieval data from the LLM <br> generate the output</p><p>Requirement :</p><p>-we using “OLLAMA Runtime” <br> -OLLAMA is large language model</p><p>for download the OLLAMA in local System visit this website “<a href="https://ollama.com/download/windows">https://ollama.com/download/windows</a>”</p><p>steps <br> -install OLLAMA →(LLM “llama2”)</p><p>— — — — for install run this cmd in terminal — →cmd ollama run llama2</p><p>LLM install based on your system specification</p><p>-install langchain-commuity</p><p>— — — — -pip install langchain-commuity</p><p>-install langchain_core</p><p>— — — — pip install langchain-core</p><p>-install streamlit</p><p>— — — — -pip install streamlit</p><p>code</p><pre>from langchin_core.promts import ChatPromtTemplate       #the many template we going to create a chatbot so we import this template <br><br>from langchin_core.output.parsers import StrOutputParser        #some time it give a special character this package control the output format<br><br>from langchin-commuity.llms import Ollama                # we useing ollama LLM <br><br>import streamlitas as st                                  #for creating a UI <br><br><br><br>st.title(&quot;ebi&#39;s assistent&quot;)              #we give a title for this a bot <br><br>input_txt = st.text_input(&quot;please enter your queries here&quot;)  #its like place holder<br><br> <br>prompt =  ChatPromtTemplate.from_messages(<br><br> [(&quot;system&quot;,&quot;you are a helpful AI assistant. your name is ebi&#39;s assistent&quot;),<br><br> (&quot;user&quot;,user query:{query})<br> <br> ])                                 #here we assig role&#39;s i assign a tow roles &quot;system&quot; ,&quot;user&quot;<br><br><br><br><br>llm = Ollama(model =&quot;llama2&quot;) #invoke llm model <br>output = StrOutputParser()  #output form<br><br>chain = prompt| llm | output #create chain <br><br><br>if input_txt :<br><br> st.write(chain.invoke({&quot;query&quot; : input_txt})) #if user give input we assign that input to the chain  <br><br><br><br># for run this project<br># ---------------------<br>#  -go the project path open the command prompt <br>#  -streamlit run filename.py<br><br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=716ba0de3a15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jwt token implement]]></title>
            <link>https://medium.com/@ebinazerselvaraj206/jwt-token-implement-f55f8e393e25?source=rss-25e8d881b82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f55f8e393e25</guid>
            <dc:creator><![CDATA[Ebinazerselvaraj]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 16:50:33 GMT</pubDate>
            <atom:updated>2025-10-09T16:50:33.302Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern applications rely on secure APIs — and the most common and scalable way to secure them is using <strong>JWT (JSON Web Tokens)</strong>.</p><p>In this guide, we’ll walk through <strong>implementing JWT authentication</strong> in a <strong>Spring Boot + Spring Security + MySQL</strong> application.</p><p>We’ll use <strong>Spring Security 6</strong>’s modern configuration approach and remove session-based authentication to make our app <strong>stateless</strong>.</p><blockquote><em>If you haven’t already generated your JWT token setup, visit this detailed guide:<br> Generate the JWT Token (</em><a href="https://medium.com/@ebinazerselvaraj206/generate-the-jwt-token-c12febae9f78"><em>Medium Blog</em></a><em>)</em></blockquote><h4>Project Overview</h4><p>We’ll cover:</p><ul><li>Secure API endpoints using JWT tokens</li><li>Implement a custom UserDetailsService</li><li>Add a JwtFilter to validate tokens</li><li>Disable default login form &amp; sessions</li></ul><p>after the generating Jwt token</p><h4>Security Configuration (UserConfiguration.java)</h4><p>The <strong>core security setup</strong> happens in the configuration class.<br> Here’s the final version of your security setup:</p><p>inside the securityFilterChain method</p><p>package com.example.fitnesstraining.configuration;</p><p><a href="http://twitter.com/Configuration">@Configuration</a><br><a href="http://twitter.com/EnableWebSecurity">@EnableWebSecurity</a><br>public class UserConfiguration {</p><p>private final JwtFilter jwtFilter;</p><p>public UserConfiguration(JwtFilter jwtFilter) {<br> this.jwtFilter = jwtFilter;<br> }</p><p><a href="http://twitter.com/Bean">@Bean</a><br> public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br> http.authorizeHttpRequests(auth -&gt; auth<br> .requestMatchers(“/home”).permitAll()<br> .requestMatchers(“/datas”).authenticated()<br> .anyRequest().permitAll()<br> )<br> // Disable default form-based login<br> //.formLogin(form -&gt; form.permitAll().defaultSuccessUrl(“/datas”))<br> .csrf(csrf -&gt; csrf.disable())<br> .sessionManagement(sess -&gt; sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))<br> .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);</p><p>return http.build();<br> }</p><p><a href="http://twitter.com/Bean">@Bean</a><br> public UserDetailsService userdetailsservice() {<br> return new CustomUserSetailService();<br> }</p><p><a href="http://twitter.com/Bean">@Bean</a><br> public DaoAuthenticationProvider authenticationProvider() {<br> DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();<br> authProvider.setUserDetailsService(userdetailsservice());<br> authProvider.setPasswordEncoder(passwordencoder());<br> return authProvider;<br> }</p><p><a href="http://twitter.com/Bean">@Bean</a><br> public PasswordEncoder passwordencoder() {<br> return new BCryptPasswordEncoder();<br> }<br>}</p><h4>What’s New Here</h4><ul><li><strong>sessionManagement(SessionCreationPolicy.STATELESS)</strong><br> → Makes the application stateless. No sessions are stored on the server. Every request must include a valid JWT token.</li><li><strong>addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)</strong><br> → Adds our custom JWT filter before Spring Security’s default authentication filter.</li><li><strong>Removed </strong><strong>.formLogin()</strong><br> → Disables the default login form since JWT is now handling authentication.</li></ul><h4>Custom User Authentication (CustomUserSetailService.java)</h4><p>This service fetches user details from your MySQL database and converts them into a format that Spring Security can use.</p><p>package com.example.fitnesstraining.databaseauthprovider;</p><p><a href="http://twitter.com/Component">@Component</a><br>public class CustomUserSetailService implements UserDetailsService {</p><p><a href="http://twitter.com/Autowired">@Autowired</a><br> private Repo repo;</p><p><a href="http://twitter.com/Override">@Override</a><br> public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {<br> UserEntity user = repo.findByEmail(email);<br> if (user == null) {<br> throw new UsernameNotFoundException(“User not found”);<br> }</p><p>return new User(<br> user.getEmail(),<br> user.getPassword(),<br> Collections.singletonList(<br> new SimpleGrantedAuthority(“ROLE_” + user.getRole().toUpperCase())<br> )<br> );<br> }<br>}</p><h4>JWT Utility Class (JwtUtill.java)</h4><p>This class is responsible for <strong>generating</strong> and <strong>validating</strong> JWT tokens.</p><p>package com.example.fitnesstraining.jwtutill;</p><p><a href="http://twitter.com/Component">@Component</a><br>public class JwtUtill {</p><p>private static final String SECRET_KEY_STRING = “VOgzT1NxAzvNHqCkYFxXLiS5AuCXwg1S”;<br> private final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(SECRET_KEY_STRING.getBytes());</p><p>// Generate JWT Token<br> public String generateToken(UserDetails userdetails) {<br> return Jwts.builder()<br> .subject(userdetails.getUsername())<br> .issuedAt(new Date())<br> .expiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) // 1 hour expiry<br> .signWith(SECRET_KEY, Jwts.SIG.HS256)<br> .compact();<br> }</p><p>// Validate JWT Token<br> public boolean ValidateToken(String token, UserDetails userDetails) {<br> return ExstractUserEmail(token).equals(userDetails.getUsername());<br> }</p><p>// Extract Username (Email) from JWT Token<br> public String ExstractUserEmail(String token) {<br> return Jwts.parser()<br> .verifyWith(SECRET_KEY)<br> .build()<br> .parseSignedClaims(token)<br> .getPayload()<br> .getSubject();<br> }<br>}</p><h4>Key Methods</h4><ul><li><strong>generateToken()</strong> — creates a signed JWT with the user’s email.</li><li><strong>ValidateToken()</strong> — checks if the provided token belongs to the same user.</li><li><strong>ExstractUserEmail()</strong> — retrieves the email (subject) from the token.</li></ul><h4>JWT Filter (JwtFilter.java)</h4><p>This filter intercepts each incoming request and:</p><ul><li>Checks for the <strong>Authorization header</strong></li><li>Validates the JWT token</li><li>Sets the authentication in the SecurityContext</li></ul><p>package com.example.fitnesstraining.jwtfilter;</p><p><a href="http://twitter.com/Component">@Component</a><br>public class JwtFilter extends OncePerRequestFilter {</p><p><a href="http://twitter.com/Autowired">@Autowired</a><br> private JwtUtill jwtUtill;</p><p><a href="http://twitter.com/Autowired">@Autowired</a><br> private CustomUserSetailService customUserSetailService;</p><p><a href="http://twitter.com/Override">@Override</a><br> protected void doFilterInternal(HttpServletRequest request,<br> HttpServletResponse response,<br> FilterChain filterChain)<br> throws ServletException, IOException {</p><p>String authHeader = request.getHeader(“Authorization”);</p><p>if (authHeader == null || !authHeader.startsWith(“Bearer “)) {<br> filterChain.doFilter(request, response);<br> return;<br> }</p><p>String token = authHeader.substring(7);</p><p>try {<br> String userEmail = jwtUtill.ExstractUserEmail(token);</p><p>if (userEmail != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {<br> UserDetails userDetails = customUserSetailService.loadUserByUsername(userEmail);</p><p>if (jwtUtill.ValidateToken(token, userDetails)) {<br> UsernamePasswordAuthenticationToken authenticationToken =<br> new UsernamePasswordAuthenticationToken(<br> userDetails.getUsername(),<br> userDetails.getPassword(),<br> userDetails.getAuthorities()<br> );<br> authenticationToken.setDetails(<br> new WebAuthenticationDetailsSource().buildDetails(request)<br> );<br> SecurityContextHolder.getContext().setAuthentication(authenticationToken);<br> }<br> }<br> } catch (Exception e) {<br> response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);<br> return;<br> }</p><p>filterChain.doFilter(request, response);<br> }<br>}</p><p>The JwtFilter is responsible for checking and validating JWT tokens on every incoming request.<br> It extends OncePerRequestFilter, ensuring it runs <strong>once per request</strong>.</p><p><strong>How it works:</strong></p><ol><li><strong>Checks the </strong><strong>Authorization header</strong> – looks for a token starting with &quot;Bearer &quot;.</li><li><strong>Extracts the token</strong> — removes the &quot;Bearer &quot; prefix.</li><li><strong>Decodes the token</strong> — retrieves the user’s email using JwtUtill.</li><li><strong>Loads user details</strong> — fetches the user from the database via CustomUserSetailService.</li><li><strong>Validates the token</strong> — ensures it’s valid and not expired.</li><li><strong>Sets authentication</strong> — adds the user details into Spring Security’s SecurityContext, allowing access to secured endpoints.</li></ol><p>If the token is invalid or missing, the request is rejected with a <strong>401 Unauthorized</strong> response.</p><h4>Summary</h4><p>In this tutorial, you’ve learned how to:</p><ul><li>Generate JWT tokens using jjwt 0.13.0</li><li>Configure Spring Security for <strong>stateless authentication</strong></li><li>Create a <strong>JwtFilter</strong> to validate tokens on every request</li><li>Disable form login and session storage</li></ul><p>Your Spring Boot app is now <strong>fully stateless and secured</strong> using JWT — a best-practice approach for modern REST APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f55f8e393e25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate the Jwt Token]]></title>
            <link>https://medium.com/@ebinazerselvaraj206/generate-the-jwt-token-c12febae9f78?source=rss-25e8d881b82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c12febae9f78</guid>
            <dc:creator><![CDATA[Ebinazerselvaraj]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 16:55:51 GMT</pubDate>
            <atom:updated>2025-10-08T16:59:46.627Z</atom:updated>
            <content:encoded><![CDATA[<p>Security is a critical part of every modern web application. Whether you’re building a web app or a mobile backend, you need a way to authenticate users and protect sensitive data.</p><p>In this tutorial, we’ll build a Spring Boot REST API and secure it using Spring Security and JWT (JSON Web Token) authentication.<br> User credentials will be stored in a MySQL database, and once authenticated, users will receive a JWT token for subsequent API calls.</p><h4>What You’ll Learn</h4><ul><li>How JWT works in Spring Security</li><li>How to generate JWT tokens on login</li><li>How to secure REST endpoints using JWT</li><li>How to handle authentication in a stateless way</li></ul><h4>Project Setup</h4><p>go to this URL -&gt; <a href="https://github.com/jwtk/jjwt">https://github.com/jwtk/jjwt</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*fj2cWoC8RWCdoJaTccawNA.png" /><figcaption>add this to your ponm.xml</figcaption></figure><h4>User Entity</h4><p>Let’s assume you already have a UserEntity with fields like name/email, password, and role:</p><p>package com.example.fitnesstraining.userentity;</p><p>import jakarta.persistence.Entity;<br>import jakarta.persistence.GeneratedValue;<br>import jakarta.persistence.GenerationType;<br>import jakarta.persistence.Id;<br>import lombok.Data;</p><p><a href="http://twitter.com/Entity">@Entity</a><br><a href="http://twitter.com/Data">@Data</a><br>public class UserEntity {<br> <a href="http://twitter.com/Id">@Id</a><br> <a href="http://twitter.com/GeneratedValue">@GeneratedValue</a>(strategy = GenerationType.IDENTITY)<br> private Long id;<br> private String email;<br> private String password;<br> private String role;<br>}</p><h4>Generating JWT Tokens</h4><p>The JwtUtil class handles JWT creation and signing.</p><h4>JwtUtill.java</h4><p>package com.example.fitnesstraining.jwtutill;</p><p><a href="http://twitter.com/Component">@Component</a><br>public class JwtUtill {</p><p>private static final String SECRET_KEY_STRING = “VOgzT1NxAzvNHqCkYFxXLiS5AuCXwg1S”;<br> private final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(SECRET_KEY_STRING.getBytes());</p><p>public String generateToken(UserDetails userdetails) {<br> return Jwts.builder()<br> .subject(userdetails.getUsername()) // Subject (username)<br> .issuedAt(new Date()) // Token issue time<br> .expiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) // 1 hour expiry<br> .signWith(SECRET_KEY, Jwts.SIG.HS256) // HMAC-SHA256 signature<br> .compact(); // Build token string<br> }<br>}</p><h4>How It Works</h4><ul><li><strong>Secret Key:</strong> Used to sign and verify the token (keep it private!)</li><li><strong>subject():</strong> Stores the username (acts as the token identity)</li><li><strong>issuedAt() / expiration():</strong> Defines token validity duration</li><li><strong>signWith():</strong> Specifies the signing algorithm and secret key</li></ul><h4>Creating the Authentication Controller</h4><p>The controller verifies user credentials and returns a signed JWT on successful login.</p><h4>AuthController.java</h4><p>package com.example.fitnesstraining.usercontroller;</p><p><a href="http://twitter.com/RestController">@RestController</a><br>public class AuthController {</p><p><a href="http://twitter.com/Autowired">@Autowired</a><br> private AuthenticationManager authenticationManager;</p><p><a href="http://twitter.com/Autowired">@Autowired</a><br> private JwtUtill jwtUtill;</p><p><a href="http://twitter.com/PostMapping">@PostMapping</a>(“/login”)<br> public ResponseEntity&lt;Map&lt;String, String&gt;&gt; login(<a href="http://twitter.com/RequestBody">@RequestBody</a> UserEntity user) {<br> try {</p><p>//<strong>import</strong> org.springframework.security.core.Authentication; Authentication from this package</p><p>Authentication authentication = authenticationManager.authenticate(<br> new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword()));</p><p>UserDetails userDetails = (UserDetails) authentication.getPrincipal();<br> String token = jwtUtill.generateToken(userDetails);</p><p>return ResponseEntity.ok(Map.of(“token”, token));</p><p>} catch (Exception e) {<br> return ResponseEntity.status(HttpStatus.UNAUTHORIZED)<br> .body(Map.of(“Error”, “Invalid username or password”));<br> }<br> }<br>}</p><h4>Explanation</h4><ul><li><strong>AuthenticationManager</strong><br> Spring Security’s built-in manager that verifies credentials against your database via your UserDetailsService.</li><li><strong>UsernamePasswordAuthenticationToken</strong><br> Used to wrap the username (email) and password for authentication.</li><li><strong>On Success:</strong><br> The authenticated user is retrieved, and a JWT is generated.</li><li><strong>On Failure:</strong><br> The API returns an HTTP 401 Unauthorized with a JSON error message.</li></ul><h4>Testing the API</h4><p>You can test your /login endpoint using <strong>Postman</strong> or <strong>cURL</strong>.</p><h4>Request</h4><p>POST <a href="http://localhost:8080/login">http://localhost:8080/login</a><br>Content-Type: application/json</p><p>{<br> “email”: “<a href="/service/mailto:john@example.com">john@example.com</a>”,<br> “password”: “123456”<br>}</p><h4>Response</h4><p>{<br> “token”: “eyJhbGciOiJIUzI1NiJ9…”<br>}</p><p>Now you can include this token in the Authorization header to access protected endpoints:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12febae9f78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Security]]></title>
            <link>https://medium.com/@ebinazerselvaraj206/spring-security-41e431a866c3?source=rss-25e8d881b82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/41e431a866c3</guid>
            <category><![CDATA[spring-security-basics]]></category>
            <dc:creator><![CDATA[Ebinazerselvaraj]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 17:03:16 GMT</pubDate>
            <atom:updated>2026-01-23T07:01:41.321Z</atom:updated>
            <content:encoded><![CDATA[<p>Security is one of the most essential parts of any modern web application.<br> Spring Security provides a powerful and flexible framework for securing Java applications — from simple form logins to complex JWT-based APIs.</p><p>In this tutorial, we’ll build a Spring Boot application and secure it using Spring Security with custom user authentication stored in a MySQL database.</p><blockquote><em>Prerequisite: Basic knowledge of Spring Boot.</em></blockquote><h4><strong><em>Project Setup</em></strong></h4><p>We’ll start by creating a new Spring Boot project.<br> You can use Spring Initializr or your favorite IDE to create it.</p><h4><strong>Required Dependencies</strong></h4><p>Add these dependencies to your pom.xml (or select them during project creation):</p><ul><li>Spring Web</li><li>Spring Security</li><li>Spring Data JPA</li><li>MySQL Driver</li><li>Spring Boot DevTools (optional, for faster development)</li></ul><h4><strong>Creating the User Entity and Repository</strong></h4><p>Before configuring security, we’ll need a database model and repository for users.</p><p>package com.example.fitnesstraining.userentity;</p><p><a href="http://twitter.com/Entity">@Entity</a><br>public class UserEntity {<br> <a href="http://twitter.com/Id">@Id</a><br> <a href="http://twitter.com/GeneratedValue">@GeneratedValue</a>(strategy = GenerationType.IDENTITY)<br> private Long id;</p><p>private String name<br> private String email;<br> private String password;<br> private String role;</p><p>// getters and setters<br>}</p><h4><strong>User Repository</strong></h4><p>package com.example.fitnesstraining.userrepo;</p><p>public interface Repo extends JpaRepository&lt;UserEntity, Long&gt; {</p><p>UserEntity findByEmail(String email);</p><p>UserEntity findByName(String name);<br>}</p><p>he findByEmail() findByName() methods lets us fetch users and Email from the database by their username — we’ll use it in our custom authentication logic.</p><p>***************import require packages*******</p><h4>Custom User Authentication with Spring Security</h4><p>Now let’s create a custom implementation of UserDetailsService that loads user data from the database.</p><p><strong>CustomUserDetailService.java</strong></p><p>package com.example.fitnesstraining.databaseauthprovider;</p><p>import java.util.Collections;</p><p><a href="http://twitter.com/Component">@Component</a><br>public class CustomUserSetailService implements UserDetailsService {<br> <br> <a href="http://twitter.com/Autowired">@Autowired</a><br> private Repo repo;</p><p><a href="http://twitter.com/Override">@Override</a><br> public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {</p><p>UserEntity user = repo.findByEmail(email);<br> return new User(user.getEmail(), user.getPassword(),<br> Collections.singletonList(new SimpleGrantedAuthority(“ROLE_” + user.getRole().toUpperCase())));<br> }<br>}</p><h4>Spring Security Configuration</h4><p>Next, we’ll configure Spring Security to use our custom user details service.</p><p><strong>UserConfiguration.java</strong></p><p>package com.example.fitnesstraining.configuration;</p><p><a href="http://twitter.com/Configuration">@Configuration</a><br><a href="http://twitter.com/EnableWebSecurity">@EnableWebSecurity</a><br>public class UserConfiguration {</p><p><a href="http://twitter.com/Bean">@Bean</a><br> public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br> http.authorizeHttpRequests(auth -&gt; auth<br> .requestMatchers(“/home”).permitAll()<br> .requestMatchers(“/datas”).authenticated()<br> .anyRequest().permitAll()<br> )<br> .formLogin(form -&gt; form<br> .permitAll()<br> .defaultSuccessUrl(“/datas”)<br> )<br> .csrf(csrf -&gt; csrf.disable());</p><p>return http.build();<br> }</p><p><a href="http://twitter.com/Bean">@Bean</a><br> public UserDetailsService userdetailsservice() {<br> return new CustomUserSetailService();<br> }</p><p><a href="http://twitter.com/Bean">@Bean</a><br> public DaoAuthenticationProvider authenticationProvider() {<br> DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();<br> authProvider.setUserDetailsService(userdetailsservice());<br> authProvider.setPasswordEncoder(passwordencoder());<br> return authProvider;<br> }</p><p><a href="http://twitter.com/Bean">@Bean</a><br> public PasswordEncoder passwordencoder() {<br> return new BCryptPasswordEncoder();<br> }<br>}</p><h4><strong>Explanation of Key Parts</strong></h4><p>hear using “SecurityFilterChain” method we give permission for the API’s in this i give permission for “/home” so without authentication we can access the home page. For “/datas” u need to give a authentication</p><p><strong>“formLogin(form -&gt; form.permitAll().defaultSuccessUrl(“/datas”))”</strong></p><p>Without this line , Spring Security will <strong>block all requests</strong> and you’ll get a 401 Unauthorized response instead of a login page (for see the login page use “.formLogin”)</p><p><strong>“.csrf(csrf -&gt; csrf.disable());”</strong></p><p>it disable for testing purpose;</p><ul><li>In REST APIs, we usually use <strong>JWT tokens</strong> or <strong>HTTP Basic Auth</strong> instead of cookies.</li><li>REST clients (like Postman or mobile apps) don’t handle CSRF tokens automatically.</li><li>So disabling CSRF makes testing and API calls easier.</li></ul><p>in “UserDetailsService” method</p><p>we return “CustomUserSetailService” class</p><p>“DaoAuthenticationProvider” method</p><p>It’s one of Spring Security’s <strong>core classes</strong> used to authenticate users with credentials stored in a <strong>database (DAO = Data Access Object)</strong>.</p><ol><li>A <strong>UserDetailsService</strong> — to load user info (username, password, roles)</li><li>A <strong>PasswordEncoder</strong> — to verify the password</li></ol><p>So it’s like the <em>bridge</em> between Spring Security and your database or user store.</p><p>in “PasswordEncoder” method</p><p>we encrypt the password using BCryptPasswordEncoder()</p><ul><li>spring security accept only encrypt password only*</li></ul><h4><strong>Testing the Setup</strong></h4><ol><li>Add a user record to your MySQL database (with an encrypted password).</li><li>Start the Spring Boot app.</li><li>Visit:</li></ol><ul><li>http://localhost:8080/home → accessible without login</li><li>http://localhost:8080/datas → redirects to login form</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41e431a866c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>