<?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 Dinely Shanuka on Medium]]></title>
        <description><![CDATA[Stories by Dinely Shanuka on Medium]]></description>
        <link>https://medium.com/@dinelywh78?source=rss-8f96a7be42af------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Yod7OQBJ-4NJ6ysY</url>
            <title>Stories by Dinely Shanuka on Medium</title>
            <link>https://medium.com/@dinelywh78?source=rss-8f96a7be42af------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 13:28:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dinelywh78/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[RoboTwin 2.0]]></title>
            <link>https://medium.com/@dinelywh78/robotwin-2-0-2b7c56e7d483?source=rss-8f96a7be42af------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b7c56e7d483</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Dinely Shanuka]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 22:36:55 GMT</pubDate>
            <atom:updated>2026-08-16T22:36:55.709Z</atom:updated>
            <content:encoded><![CDATA[<h3>RoboTwin 2.0 A Scalable Data Generator and<br>Benchmark with Strong Domain Randomization for<br>Robust Bimanual Robotic Manipulation</h3><p>The paper introduces RoboTwin2.0, a simulation framework designed to generate large amounts of training data for bimanual robots, robots that manipulate objects using two arms.</p><p>The highlight is the combination of automated expert-data generation + aggressive environmental diversity + sim-to-real transfer.</p><p>The main limitations are:</p><ul><li>the lack of an efficient, scalable data generation method for novel tasks</li><li>oversimplified simulation environments that fail to capture real-world complexity.</li></ul><p>The problem is that the simulations are too clean and simple. A robot might learn perfectly with a white table and perfect lighting, but then fail whn you put it in a messy real room. The authors specifically idetify insufficient data diversity and unrealistic simulation environments as major problems.</p><ol><li>A large object library: RoboTwin-OD</li></ol><p>731 object instances -&gt; 147 categories</p><p>This doesn’t just provide a simulator, it provides a large, manipulation-aware object ecosystem for generating robot experiences.</p><p>2. MLLMs automatically generate roobot task code</p><p>This uses Multimodal Large Language Model(MLLM) to generate the task execution code automatically.</p><p>3. Simulation becomes the feedback mechanism</p><p>As LLM can produce incorrect robot behavior, this uses simulation-in-the-loop refinement. The generated program is executed multiple times in simulation. The system records failures such as incorrect grasps or incorrect object placement. A vision-language model also observes the execution and tries to locate the failure.</p><p><strong>Central Loop:</strong></p><p>MLLM generates code → Simulation executes → VLM observes → Errors are identified → Code is repaired → Try again</p><p>Instead of trusting AI-generated robot code immediately, RoboTwin 2.0 lets the simulation act as testing and feedback environment.</p><p>4. Domain randomization akes simulation more like the real world</p><p>RoboTwin changes 5 aspects of training environment</p><p><strong>Clutter | Lighting | Background | Table height | Language instructions</strong></p><p>Train on many variations → become less sensitive to any particular environment → generalize better to reality.</p><p>5. It supports different types of robots</p><p>This covers 50 dual-arm tasks across 5 robot embodiments.</p><p>This matters because different robots cannot necessarily perform the same manipulation in exactly the same way.</p><p>For example, the paper explains that a Franka arm may prefer a <strong>top-down grasp</strong>, while a lower-degree-of-freedom Piper robot may need a <strong>side grasp</strong>.</p><p><strong>Resources</strong></p><h4><strong>731 objects / 147 categories</strong><br> <strong>100,000+ trajectories</strong><br> <strong>50 dual-arm tasks</strong><br> <strong>5 robot platforms</strong><br> <strong>Standardized benchmark</strong></h4><p>Ultimate goal- Generate large amounts of diverse, high quality synthetic robot data that produces policies capable of generalizing to messy, unfamiliar real-world environments.</p><p>Task description-&gt; AI writes robot code-&gt; robot tires it in simulation-&gt; AI check mistakes-&gt; codes get improved-&gt; successful demonstrations are collected-&gt; train robot</p><h3><strong>2. Method</strong></h3><p>3 main ideas</p><ol><li>Automatically generate and repair expert robot code</li><li>Randomize the simulation environment</li><li>Adapt grasps to different robot bodies</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5kSluJONU26tZP0Ky2WCg.png" /></figure><p>2.1 Expert code generation</p><p>Two AI agents are involved: MLLM + simulation + VLM feedback.</p><ol><li>Code-generation agent</li></ol><p>“Given the robot task, write the program that performs it”</p><p>2. VLM observer</p><p>“Watch the robot execute the program and determine what went wrong”</p><p>feedback loop: an MLLM generates robot code, simulation tests it, a VLM diagnoses failures, and the code is required.</p><p>2.2 Domain Randomization</p><p>Many backgrounds + lighting conditions + clutter configurations + table heights + language variations</p><p>RoboTwin changes clutter, backgrounds, lighting, table heights and language. This is intended to improve sim-to-real generalization.</p><p>2.3 Embodiment-Aware Grasp Adaptation</p><p>RoboTwin doesn’t force every robot to grab an object in the same way. It gives each robot several possibilities and finds ones compatible with its body.</p><p>RoboTwin generates multiple manipulation candidates and adapts them to the robot’s physical capabilities.</p><p>Results</p><ul><li>Better automatic code generation- <strong>10.9% improvement in code-generation success rate</strong>.</li><li>Synthetic data + very little real data works well- ombined large-scale synthetic data with only <strong>10 real demonstrations</strong>. (Large amounts of synthetic experience may significantly reduce how much expensive real-world robot data we need.)</li></ul><p>3. RoboTwin-OD:: the object dataset</p><p>large library of 3D objects</p><p>It contains: 731 objects across 147 categories.</p><p>These are not just visual 3D models. Each object also contains information that helps a robot understand <strong>how to interact with it</strong>.</p><p>For example, an object can be annotated with:</p><ul><li><strong>grasp point</strong> → where the robot should grab it</li><li><strong>grasp axis</strong> → from which direction it should grasp</li><li><strong>functional point</strong> → the important usable part of the object</li><li><strong>placement point</strong> → where the object can be placed</li><li><strong>object axis</strong> → its orientation</li></ul><p>created:</p><p><strong>534 objects across 111 categories</strong> themselves using RGB-to-3D reconstruction.</p><p>They also included: 153 objects from Objaverse and 44 articulated objects from SAPIEN PartNet-Mobility.</p><p><strong>RoboTwin-OD</strong></p><p>→ 731 objects<br> → 147 categories<br> → manipulation annotations<br> → diverse language descriptions</p><p>↓</p><p><strong>RoboTwin Tasks</strong></p><p>→ 50+ dual-arm tasks<br> → 5 robot platforms</p><p>↓</p><p><strong>Large dataset</strong></p><p>→ 100,000+ expert trajectories</p><h3><strong>4. Experiment</strong></h3><p>Metrics</p><p><strong>ASR — </strong>How often the generated robot programs succeed overall.</p><p><strong>Top5-ASR- </strong>How good the best few generated programs are.</p><p><strong>CR-Iter- </strong>How many repair rounds are needed before stopping.</p><p><strong>Token- </strong>How long/expensive the generated code is.</p><p>So ideally: <strong>higher ASR + higher Top5-ASR + lower CR-Iter + fewer tokens.</strong></p><p>compare five robot policy methods:</p><p><strong>ACT, DP, RDT, Pi0, DP3 </strong>across all <strong>50 RoboTwin tasks</strong>.</p><h4>Experiment 1</h4><p><strong>Can AI automatically generate good robot code?</strong></p><p>✅ Yes.<br> MLLM + execution feedback + VLM feedback improves success.</p><p>↓</p><h4>Experiment 2</h4><p><strong>Does robot-specific grasping help?</strong></p><p>✅ Yes, especially for less flexible robots such as Piper.</p><p>↓</p><h4>Experiment 3</h4><p><strong>Does domain randomization improve robustness?</strong></p><p>✅ Yes.<br> Randomized training data generalizes better than clean simulation data.</p><p>↓</p><h4>Experiment 4</h4><p><strong>Can synthetic data help real robots?</strong></p><p>✅ Strongly.<br> 10 real demos + synthetic RoboTwin data performs much better than 10 real demos alone.</p><p>↓</p><h3>Experiment 5</h3><p><strong>Is RoboTwin a useful benchmark?</strong></p><p>✅ Yes.<br> It exposes how badly many current policies degrade under realistic environmental variation.</p><h3><strong>Four findings:</strong></h3><p><strong>1. The feedback loop works.</strong><br> RoboTwin 2.0’s multimodal feedback increases code-generation success and reduces refinement effort.</p><p><strong>2. Robot embodiment matters.</strong><br> Adaptive grasping especially helps less flexible robot arms, with Piper showing the largest gain.</p><p><strong>3. Diversity matters more than simply adding clean synthetic data.</strong><br> Domain-randomized training substantially improves robustness to unseen environmental conditions.</p><p><strong>4. Synthetic data can materially reduce the need for real robot demonstrations.</strong><br> Adding 1,000 synthetic trajectories to only 10 real demonstrations dramatically improves real-world performance, and even synthetic-only training achieves meaningful zero-shot transfer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b7c56e7d483" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Security with JPA Authentication]]></title>
            <link>https://medium.com/@dinelywh78/spring-security-with-jpa-authentication-75c199c3dbd4?source=rss-8f96a7be42af------2</link>
            <guid isPermaLink="false">https://medium.com/p/75c199c3dbd4</guid>
            <dc:creator><![CDATA[Dinely Shanuka]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 20:05:08 GMT</pubDate>
            <atom:updated>2024-08-09T20:05:08.944Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a common approach to securing a Spring Boot application using database-backend user authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*ggOi-qcrnBVBZWgFc_4_WQ.png" /></figure><p>You can find the boilerplate code for this project on <a href="https://github.com/DinelyWellehewage/spring-security-jpa">https://github.com/DinelyWellehewage/spring-security-jpa</a>.</p><p><strong>Step 1: Set up the Spring Boot Project</strong></p><p>First, create a Spring Boot project with the necessary dependencies such as ‘Spring Web’, ‘Spring Security’, ‘Data JPA’, and ‘MySQL Driver’.</p><p><strong>Step 2: Create the Application Controller</strong></p><p>Create a controller to manage access to different routes.</p><pre>@RestController<br>public class ApplicationController {<br><br>    @GetMapping(&quot;/&quot;)<br>    public String home(){<br>        return &quot;welcome&quot;;<br>    }<br><br>    @GetMapping(&quot;/admin&quot;)<br>    public String admin(){<br>        return &quot;welcome admin&quot;;<br>    }<br><br>    @GetMapping(&quot;/user&quot;)<br>    public String user(){<br>        return &quot;welcome user&quot;;<br>    }<br>}</pre><p><strong>Step 3: Configure Spring Security</strong></p><p>To configure Spring Security for custom authentication and authorization using JPA with MySQL, you’ll need to override the configure method provided by WebSecurityConfigurerAdapter. This method receives an AuthenticationManagerBuilder parameter, which you&#39;ll use to configure Spring Security to retrieve user details from a MySQL database via JPA. By auto-wiring a UserDetailsService implementation, you instruct Spring Security to invoke this service&#39;s loadUserByUsername method whenever an authentication attempt occurs. This method will fetch the user&#39;s details from the database, ensuring that the authentication process is fully integrated with your JPA-based user repository.</p><pre>@EnableWebSecurity<br>@Configuration<br>public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {<br>    @Autowired<br>    UserDetailsService userDetailsService;<br> <br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        auth.userDetailsService(userDetailsService);<br>    }<br>    @Bean<br>    public PasswordEncoder getPasswordEncoder() {<br>        return NoOpPasswordEncoder.getInstance();<br>    }<br><br>    @Override<br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.authorizeRequests()<br>                .antMatchers(&quot;/admin&quot;).hasRole(&quot;ADMIN&quot;)<br>                .antMatchers(&quot;/user&quot;).hasAnyRole(&quot;USER&quot;, &quot;ADMIN&quot;)<br>                .antMatchers(&quot;/&quot;).permitAll()<br>                .and().formLogin();<br>    }<br>}</pre><p><strong>Step 4: Implement UserDetailsService and UserDetails</strong></p><p>Next, create a hard-coded user details instance by defining the MyUserDetails class, which implements the UserDetails interface. This class will represent a user&#39;s details within the Spring Security framework. You&#39;ll override all the necessary methods. These methods will return predefined, hard-coded values, such as a specific username, password, and user roles. This setup allows you to test the authentication flow with a static user before integrating with a dynamic, database-driven solution.</p><pre>public class MyUserDetails implements UserDetails {<br>    private String userName;<br><br>    public MyUserDetails(String userName){<br>        this.userName = userName;<br>    }<br>    public MyUserDetails(){}<br>    @Override<br>    public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {<br>        return Arrays.asList(new SimpleGrantedAuthority(&quot;ROLE_USER&quot;));<br>    }<br><br>    @Override<br>    public String getPassword() {<br>        return &quot;pass&quot;;<br>    }<br><br>    @Override<br>    public String getUsername() {<br>        return userName;<br>    }<br><br>    @Override<br>    public boolean isAccountNonExpired() {<br>        return true;<br>    }<br><br>    @Override<br>    public boolean isAccountNonLocked() {<br>        return true;<br>    }<br><br>    @Override<br>    public boolean isCredentialsNonExpired() {<br>        return true;<br>    }<br><br>    @Override<br>    public boolean isEnabled() {<br>        return true;<br>    }<br>}</pre><p>Create MyUserDetailsService class which implements UserDetailService and override method loadUserByUsername to authenticate against it.</p><pre>@Service<br>public class MyUserDetailsService implements UserDetailsService {<br><br>    @Override<br>    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<br>        return new MyUserDetails(username);<br>    }<br>}</pre><p>In this method, Spring Security connects to a source of user information to retrieve user details based on the provided username, and then creates a corresponding UserDetails object to pass back to the security framework.</p><p>With a hard-coded user details object, you can configure Spring Security to rely on a UserDetailsService implementation that returns these static values. This setup allows you to test authentication with a predefined user. After implementing this configuration, running the application should enable access to the root endpoint (http://localhost:8080/) using the hard-coded credentials, demonstrating that the authentication flow is working as expected.</p><p>When using JPA, this approach involves calling a JPA repository API to fetch user information from a database for a given user ID.</p><p><strong>Step 5: Create the User Entity and Repository</strong></p><p>Create the User Entity.</p><pre>@Entity<br>@Table(name = &quot;User&quot;)<br>public class User {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.AUTO)<br>    private int id;<br>    private String username;<br>    private  String password;<br>    private  boolean active;<br>    private String roles;<br><br>    public int getId() {<br>        return id;<br>    }<br><br>    public void setId(int id) {<br>        this.id = id;<br>    }<br><br>    public String getUsername() {<br>        return username;<br>    }<br><br>    public void setUsername(String username) {<br>        this.username = username;<br>    }<br><br>    public String getPassword() {<br>        return password;<br>    }<br><br>    public void setPassword(String password) {<br>        this.password = password;<br>    }<br><br>    public boolean isActive() {<br>        return active;<br>    }<br><br>    public void setActive(boolean active) {<br>        this.active = active;<br>    }<br><br>    public String getRoles() {<br>        return roles;<br>    }<br><br>    public void setRoles(String roles) {<br>        this.roles = roles;<br>    }<br>}</pre><p>Create UserRepositoy interface which extends JPARepository.</p><pre>import com.example.spring_security_jpa.models.User;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import java.util.Optional;<br><br>public interface UserRepository extends JpaRepository&lt;User,Integer&gt; {<br>    Optional&lt;User&gt; findByUserName(String userName);<br>}</pre><p><strong>Step 6: Update </strong><strong>MyUserDetails to Use Dynamic Data Instead of Hard-Coded Values.</strong></p><p>To integrate dynamic user data with Spring Security, you’ll need to modify the MyUserDetails class to use real data from the database instead of hard-coded values. Begin by updating MyUserDetails to accept a User entity, which will be retrieved from the database.</p><pre>public class MyUserDetails implements UserDetails {<br>    private String userName;<br>    private String password;<br>    private boolean active;<br>    private List&lt;GrantedAuthority&gt; authorities;<br><br>    public MyUserDetails(User user){<br>        this.userName = user.getUsername();<br>        this.password=user.getPassword();<br>        this.active = user.isActive();<br>        this.authorities = Arrays.stream(user.getRoles().split(&quot;,&quot;)).map(SimpleGrantedAuthority::new).collect(Collectors.toList());<br>    }<br>    public MyUserDetails(){}<br>    @Override<br>    public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {//returns collection of granted authority instances<br>        return authorities;<br>    }<br><br>    @Override<br>    public String getPassword() {<br>        return password;<br>    }<br><br>    @Override<br>    public String getUsername() {<br>        return userName;<br>    }<br><br>    @Override<br>    public boolean isAccountNonExpired() {<br>        return true;<br>    }<br><br>    @Override<br>    public boolean isAccountNonLocked() {<br>        return true;<br>    }<br><br>    @Override<br>    public boolean isCredentialsNonExpired() {<br>        return true;<br>    }<br><br>    @Override<br>    public boolean isEnabled() {<br>        return active;<br>    }<br>}</pre><p><strong>Step 7: Update </strong><strong>MyUserDetailsService to Fetch User from the Database</strong></p><p>Modify the MyUserDetailsService to use the UserRepository to find the user by username. Convert the retrieved User entity into a MyUserDetails object.</p><pre>@Service<br>public class MyUserDetailsService implements UserDetailsService {<br>    @Autowired<br>    UserRepository userRepository;<br><br>    @Override<br>    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<br>        Optional&lt;User&gt; user = userRepository.findByUserName(username);<br>        user.orElseThrow(()-&gt;new UsernameNotFoundException(&quot;Not Found: &quot;+ username));<br>        return user.map(MyUserDetails::new).get();<br>    }<br>}</pre><p>By making these changes, your application will no longer rely on hard-coded user details. Instead, it will dynamically retrieve user information from the database, making it more adaptable and realistic for production environments.</p><p><strong>Step 8: Enable JPA in the Spring Boot Application</strong></p><p>Configure your Spring Boot application to use JPA by enabling repository scanning. To achieve this, add the @EnableJpaRepositories annotation to your main application class. This annotation instructs Spring Boot to scan for JPA repository interfaces and automatically generate the necessary implementations, enabling seamless interaction with the database through JPA.</p><pre>@SpringBootApplication()<br>@EnableJpaRepositories(basePackageClasses = UserRepository.class)<br>public class SpringSecurityJpaApplication {<br>    public static void main(String[] args) {<br>       SpringApplication.run(SpringSecurityJpaApplication.class, args);<br>    }<br>}</pre><p><strong>Step 9: Configure the database in application.properties.</strong></p><pre>spring.datasource.url=jdbc:mysql://localhost:3306/springsecurity<br>spring.datasource.username=root<br>spring.datasource.password=password<br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy</pre><p><strong>Step 10: Run the Application</strong></p><p>Create a MySQL database named springsecurity and a table named user with a user record (username: user, password: pass).</p><p>Start the Spring Boot application and access the / endpoint at <a href="http://localhost:8080/">http://localhost:8080/.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75c199c3dbd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Security with JDBC Authentication]]></title>
            <link>https://medium.com/@dinelywh78/jdbc-authentication-with-spring-security-4d133193ca2f?source=rss-8f96a7be42af------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d133193ca2f</guid>
            <dc:creator><![CDATA[Dinely Shanuka]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 19:24:03 GMT</pubDate>
            <atom:updated>2024-08-09T20:06:45.333Z</atom:updated>
            <content:encoded><![CDATA[<p>JDBC stands for Java Database Connectivity which is a Java API for connecting and executing queries to the database. It provides a standard abstraction (API or protocol) for Java applications to communicate with various databases.</p><p>You can find the boilerplate code for this project on <a href="https://github.com/DinelyWellehewage/spring-security-jdbc">https://github.com/DinelyWellehewage/spring-security-jdbc</a>.</p><p><strong>Step 1: Set up the Spring Boot Project</strong></p><p>Let’s create a basic Spring web application using <a href="https://start.spring.io/">https://start.spring.io/</a> and generate a template project with dependencies such as ‘Spring Web’, ‘Spring Security’, ‘H2’, and ‘JDBC API’.</p><p><strong>Step 2: Set Up the Application Controller</strong></p><p>Create a REST controller to handle different endpoints:</p><pre>@RestController<br>public class ApplicationController {<br><br>    @GetMapping(&quot;/&quot;)<br>    public String home(){<br>        return &quot;welcome&quot;;<br>    }<br><br>    @GetMapping(&quot;/admin&quot;)<br>    public String admin(){<br>        return &quot;welcome admin&quot;;<br>    }<br><br>    @GetMapping(&quot;/user&quot;)<br>    public String user(){<br>        return &quot;welcome user&quot;;<br>    }<br>}</pre><p><strong>Step 3: Configure Spring Security with JDBC Authentication</strong></p><p>You can configure Spring Security by extending WebSecurityConfigurerAdapter.</p><p>3.1 Basic Configuration with Default Schema</p><p>To configure JDBC authentication in a Spring Boot application, you start by setting up a data source bean that manages the database connection. This involves creating an instance of the DataSource and defining it as a bean within a configuration class. Once the DataSource is configured, it can be wired into the security configuration. In the security configuration class, you use the AuthenticationManagerBuilder to set up JDBC authentication by passing the DataSource into the jdbcAuthentication() method. This method tells Spring Security to use the database for user authentication. Additionally, the HttpSecurity configuration is used to define access rules for different endpoints, ensuring that requests are authorized based on the user&#39;s roles, with specific URLs being restricted to users with certain roles, and others being open to all users. This setup integrates database-driven authentication into the security framework of your Spring Boot application.</p><pre>@EnableWebSecurity<br>@Configuration<br>public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {<br><br>    @Autowired<br>    DataSource dataSource;<br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        auth.jdbcAuthentication().dataSource(dataSource)<br>                .withDefaultSchema()<br>                .withUser(User.withUsername(&quot;user&quot;).password(&quot;pass&quot;).roles(&quot;USER&quot;))<br>                .withUser(User.withUsername(&quot;admin&quot;).password(&quot;pass&quot;).roles(&quot;ADMIN&quot;));<br>    }<br>    @Bean<br>    public PasswordEncoder getPasswordEncoder() {<br>        return NoOpPasswordEncoder.getInstance();<br>    }<br><br>    @Override<br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.authorizeRequests()<br>                .antMatchers(&quot;/admin&quot;).hasRole(&quot;ADMIN&quot;)<br>                .antMatchers(&quot;/user&quot;).hasAnyRole(&quot;USER&quot;, &quot;ADMIN&quot;)<br>                .antMatchers(&quot;/&quot;).permitAll()<br>                .and().formLogin();<br>    }<br>}</pre><p>3.2 Custom Schema Configuration</p><p>To use a custom schema, create schema.sql and data.sql in the src/main/resources folder.</p><pre>@EnableWebSecurity<br>@Configuration<br>public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {<br><br>    @Autowired<br>    DataSource dataSource;<br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        auth.jdbcAuthentication().dataSource(dataSource);<br>    }<br>    @Bean<br>    public PasswordEncoder getPasswordEncoder() {<br>        return NoOpPasswordEncoder.getInstance();<br>    }<br><br>    @Override<br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.authorizeRequests()<br>                .antMatchers(&quot;/admin&quot;).hasRole(&quot;ADMIN&quot;)<br>                .antMatchers(&quot;/user&quot;).hasAnyRole(&quot;USER&quot;, &quot;ADMIN&quot;)<br>                .antMatchers(&quot;/&quot;).permitAll()<br>                .and().formLogin();<br>    }<br>}</pre><p>To set up schema, create schema.sql.</p><pre>create table users(<br> username varchar_ignorecase(50) not null primary key,<br> password varchar_ignorecase(50) not null ,<br> enabled boolean not null);<br><br> create table authorities(<br>  username varchar_ignorecase(50) not null ,<br>  authority varchar_ignorecase(50) not null ,<br>  constraint fk_authorities_users foreign key(username) references users(username));<br><br>  create unique index ix_auth_username on authorities(username,authority);</pre><p>To enter data into a schema, create data.sql.</p><pre>INSERT INTO users(username,password,enabled)<br>values(&#39;user&#39;,&#39;pass&#39;,true);<br><br>INSERT INTO users(username,password,enabled)<br>values(&#39;admin&#39;,&#39;pass&#39;,true);<br><br>INSERT INTO authorities(username,authority)<br>values(&#39;user&#39;,&#39;ROLE_USER&#39;);<br><br>INSERT INTO authorities(username,authority)<br>values(&#39;admin&#39;,&#39;ROLE_ADMIN&#39;);</pre><p>Ensure database initialization by adding this to application.properties. It may drop and recreate your schema.</p><pre>spring.datasource.initialization-mode=never</pre><p>3.3 Custom Queries for Different Database Schema</p><p>If your database schema differs, use custom queries:</p><pre>@EnableWebSecurity<br>@Configuration<br>public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {<br><br>    @Autowired<br>    DataSource dataSource;<br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery(&quot;select username,password,enabled from users where username=?&quot;)<br>                .authoritiesByUsernameQuery(&quot;select username,authority from authorities where username=?&quot;);<br>    }<br>    @Bean<br>    public PasswordEncoder getPasswordEncoder() {<br>        return NoOpPasswordEncoder.getInstance();<br>    }<br><br>    @Override<br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.authorizeRequests()<br>                .antMatchers(&quot;/admin&quot;).hasRole(&quot;ADMIN&quot;)<br>                .antMatchers(&quot;/user&quot;).hasAnyRole(&quot;USER&quot;, &quot;ADMIN&quot;)<br>                .antMatchers(&quot;/&quot;).permitAll()<br>                .and().formLogin();<br>    }<br>}</pre><p><strong>Step 4: Configure the Data Source</strong></p><p>In application.properties, configure your data source connection:</p><pre>spring.datasource.url=jdbc:h2:mem:testdb<br>spring.datasource.driverClassName=org.h2.Driver<br>spring.datasource.username=sa<br>spring.datasource.password=password</pre><p><strong>Step 5: Run the Application</strong></p><p>Run the application, and Spring Boot will automatically handle the schema creation and data insertion based on your SQL scripts. You can now access the /admin, /user, and / endpoints, which are protected based on the roles defined in your database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d133193ca2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Security with Basic Authentication]]></title>
            <link>https://medium.com/@dinelywh78/spring-security-with-basic-authentication-5a0b7b270aca?source=rss-8f96a7be42af------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a0b7b270aca</guid>
            <dc:creator><![CDATA[Dinely Shanuka]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 18:56:37 GMT</pubDate>
            <atom:updated>2024-08-09T19:04:29.159Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Security is a powerful and highly customizable authentication and access-control framework that is the fact standard for securing Spring-based applications. Below is an overview of what Spring Security can do.</p><ul><li>User name/password authentication.</li><li>SSO/ Okta / LDAP</li><li>App-level authentication</li><li>Intra-authorization like OAuth</li><li>Microservice Security (using tokens, JWT)</li><li>Method level security</li></ul><p>Five core concepts in Spring Security</p><ul><li>Authentication — who are you?</li><li>Authorization — are they allowed to do this?</li><li>Principal — currently logged in user</li><li>Granted Authority — how does authorization happen?</li><li>Roles — group of authoroties</li></ul><p><strong>Adding Spring Security to New Spring Boot Project</strong></p><p>Adding spring security to a spring boot project is done by using a dependency called spring-boot-starter-security. It’s a maven dependency that pulls all necessary spring security dependencies and makes them available.</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*S3eVApm9rzfJveOqPmH8Rw.png" /><figcaption>sign-in page</figcaption></figure><p>Servlet — Web app has bunch of servlets. When the user requests a URL, a particular sublet does the functionality and responds to that request. It picks the right server to do the job and then executes a method on that servlet.</p><p>Filter — Filters are like cross-cutting concerns that stand right in the middle and intercept every request, allowing doing something with every request. They are like cross-cutting functionality that you can use to log every request.</p><p>So while servlets are mapped to URLs, filters can be applied to all URLs. This filter needs to intercept all URLs and have that filter allow or deny based on the request itself. Spring Security is putting in a filter there and examining all requests to allow or deny requests as per what should be done.</p><p><strong><em>Spring Security default behavior</em></strong></p><ul><li>Adds mandatory authentication for URLs.</li><li>Adds login form</li><li>Handles login error</li><li>Creates a user and sets a default password.</li></ul><p>To use Spring Boot default security we need to mention the username and password in the application.properties file.</p><pre>spring.security.user.name=john<br>spring.security.user.password=password</pre><p>Here’s a demonstrate of Basic Authentication using In-Memory Authentication.</p><p><strong>How to configure Spring Security Authentication</strong></p><p>AuthenticationManager — Manages authentication in the spring boot application. Use AuthenticationManagerBuilder to configure what the authentication should do.</p><p>To enable security add EnableWebSecurity annotation.</p><ol><li>Get hold of AuthenticationMangerBuilder</li><li>Set the configuration on it</li></ol><p>When the configured authentication manager builder is with properties, a new authentication manager is created with your desired values.</p><p>In the spring security app, there is a class with a method called configure, which takes in as an argument the authentication manager builder. Spring security framework calls that configure method and passes in the authentication manager builder.</p><p>Create a class SpringSecurityConfig and extend WebSecurityConfigurerAdapter which has configure methods. Get a method that has AuthenticationMangerBuilder as an argument.</p><p>Build in-memory authentication and configure it to be in-memory authentication when need to pass user, password, and role of user need. Let’s configure one user that follows the method chaining pattern to configure all these things.</p><p>Tt was created in memory authentication configuration with user, password, and role.</p><p>EnableWebSecurity annotation tells Spring Security that this is a web security configuration that handles web requests and authenticates.</p><pre>@EnableWebSecurity<br>@Configuration<br>public class SpringSecurityConfig  extends WebSecurityConfigurerAdapter {<br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        //set configuration on auth object<br>        auth.inMemoryAuthentication()<br>                .withUser(&quot;blah&quot;)<br>                .password(&quot;blah&quot;)<br>                .roles(&quot;USER&quot;);<br><br>    }<br>}</pre><p>When storing passwords it is required to do password encoding. For that, create a bean of type password encoder and expose it to spring security. To set a password encoder, expose a Bean of type PasswordEncoder.</p><pre>@Bean<br>    public PasswordEncoder getPasswordEncoder(){<br>        return NoOpPasswordEncoder.getInstance();<br>    }</pre><p>Through this class, we handle the authentication manager builder and set a couple of properties that put it to in-memory authentication. Here’s the created user ‘john’ and password ‘password’ with the role of USER. This is how configured authentication is.</p><p><em>SpringSecurityConfig.class</em></p><pre>@EnableWebSecurity<br>@Configuration<br>public class SpringSecurityConfig  extends WebSecurityConfigurerAdapter {<br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        //set configuration on auth object<br>        auth.inMemoryAuthentication()<br>                .withUser(&quot;john&quot;)<br>                .password(&quot;password&quot;)<br>                .roles(&quot;USER&quot;);<br>    }<br>    @Bean<br>    public PasswordEncoder getPasswordEncoder(){<br>        return NoOpPasswordEncoder.getInstance();<br>    }<br>}</pre><p>To configure more users, as this is a builder pattern and method chaining is in effect can use and() which returns the same state as what in-memory authentication returns.</p><p><em>SpringSecurityConfig.class</em></p><pre>@EnableWebSecurity<br>@Configuration<br>public class SpringSecurityConfig  extends WebSecurityConfigurerAdapter {<br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        //set configuration on auth object<br>        auth.inMemoryAuthentication()<br>                .withUser(&quot;blah&quot;)<br>                .password(&quot;blah&quot;)<br>                .roles(&quot;USER&quot;)<br>                .and()<br>                .withUser(&quot;foo&quot;)<br>                .password(&quot;foo&quot;)<br>                .roles(&quot;ADMIN&quot;);<br>    }<br>    @Bean<br>    public PasswordEncoder getPasswordEncoder(){<br>        return NoOpPasswordEncoder.getInstance();<br>    }<br>}</pre><p><strong>How to configure Spring Security Authorization</strong></p><p>Check if a request has the authority to perform what it needs to do.</p><p>Here are different APIs created.</p><p><em>ApplicationController.class</em></p><pre>@RestController<br>public class ApplicationController {<br><br>    @GetMapping(&quot;/&quot;)<br>    public String home(){<br>        return &quot;welcome&quot;;<br>    }<br><br>    @GetMapping(&quot;/admin&quot;)<br>    public String admin(){<br>        return &quot;welcome admin&quot;;<br>    }<br><br>    @GetMapping(&quot;/user&quot;)<br>    public String user(){<br>        return &quot;welcome user&quot;;<br>    }<br>}</pre><p>We use HTTPSecurity which lets you configure the paths and the access restrictions for those paths. The class extends WebSecurotyConfigurerAdapter which gets to override some of the methods. These methods are hooks that Spring Security provides when you implement overridden methods you get access to certain key objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*3qfo1n72Cp0b8JESHXAizg.png" /></figure><pre>@Override<br>protected void configure(HttpSecurity http) throws Exception {<br>    http.authorizeRequests()<br>            .antMatchers(&quot;/admin&quot;).hasRole(&quot;ADMIN&quot;)<br>            .antMatchers(&quot;/user&quot;).hasRole(&quot;USER&quot;)<br>            .antMatchers(&quot;/&quot;).permitAll()<br>            .and().formLogin();<br>}</pre><p>Here’s <em>SpringSrcurityConfig.class</em></p><pre>@EnableWebSecurity<br>@Configuration<br>public class SpringSecurityConfig  extends WebSecurityConfigurerAdapter {<br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        auth.inMemoryAuthentication()<br>                .withUser(&quot;blah&quot;)<br>                .password(&quot;blah&quot;)<br>                .roles(&quot;USER&quot;)<br>                .and()<br>                .withUser(&quot;foo&quot;)<br>                .password(&quot;foo&quot;)<br>                .roles(&quot;ADMIN&quot;);<br>    }<br>    @Bean<br>    public PasswordEncoder getPasswordEncoder(){<br>        return NoOpPasswordEncoder.getInstance();<br>    }<br><br>    @Override<br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.authorizeRequests()<br>                .antMatchers(&quot;/admin&quot;).hasRole(&quot;ADMIN&quot;)<br>                .antMatchers(&quot;/user&quot;).hasAnyRole(&quot;USER&quot;,&quot;ADMIN&quot;)<br>                .antMatchers(&quot;/&quot;).permitAll()<br>                .and().formLogin();<br>    }<br>}</pre><p>You can find the boilerplate code for this project on <a href="https://github.com/DinelyWellehewage/spring-basic-security">https://github.com/DinelyWellehewage/spring-basic-security</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a0b7b270aca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Security Authentication with LDAP]]></title>
            <link>https://medium.com/@dinelywh78/spring-security-authentication-with-ldap-215dcc0aecf3?source=rss-8f96a7be42af------2</link>
            <guid isPermaLink="false">https://medium.com/p/215dcc0aecf3</guid>
            <dc:creator><![CDATA[Dinely Shanuka]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 10:30:44 GMT</pubDate>
            <atom:updated>2024-08-09T11:08:52.176Z</atom:updated>
            <content:encoded><![CDATA[<p>LDAP stands for Lightweight Directory Access Protocol, which is used to access and maintain distributed directory information services over an internet protocol. You can find the boilerplate code for this project on my <a href="https://github.com/DinelyWellehewage/spring-secuirty-ldap">https://github.com/DinelyWellehewage/spring-secuirty-ldap</a>.</p><p>LDAP is designed to maintain and access “directory services” within a network. It is like a directory service as a phonebook for different network resources like files, printers, users, devices, and servers. It uses a small amount of code. LDAP’s primary use is enabling users to find data about organizations, persons, and more by storing data in the LDAP directory and authenticating users to access the directory.</p><p>Popular applications that LDAP support LDAP authentication are OpenVPN, Docker, Jenkins, Kubernetes, and Linux Samba Servers.</p><p>Here’s the authentication process.</p><ul><li>The client requests access to information stored in an LDAP database.</li><li>The client provides their LDAP server user credentials for authentication.</li><li>The LDAP server validates the submitted credentials by comparing them with the core user identity data stored in its LDAP database.</li><li>If the credentials provided by the client match the stored core user identity, the client is granted access to the requested information.</li></ul><p><strong>Step 1: Set up the Spring Boot Project</strong></p><p>Let’s create a basic Spring web application using <a href="https://start.spring.io/">https://start.spring.io/</a> and generate a template project with dependencies such as ‘Spring Web’ and ‘Spring Security’.</p><p><strong>Step 2: Add LDAP dependencies</strong></p><p>In your pom.xml, add the following dependencies:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.unboundid&lt;/groupId&gt;<br>    &lt;artifactId&gt;unboundid-ldapsdk&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.ldap&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-ldap-core&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-security-ldap&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><strong>Step 3: Configure </strong><strong>application.properties</strong></p><p>Add the following LDAP configuration to application.properties file. This configuration sets up the embedded LDAP server on port 8389 and loads the initial data from the ldap-data.ldif file.</p><pre>spring.ldap.embedded.port=8389<br>spring.ldap.embedded.ldif=classpath:ldap-data.ldif<br>spring.ldap.embedded.base-dn=dc=springframework,dc=org</pre><p><strong>Step 3: Create </strong><strong>ldap-data.ldif in the Resources Folder</strong></p><p>Create a file named ldap-data.ldif under src/main/resources with the following content:</p><pre>dn: dc=springframework,dc=org<br>objectclass: top<br>objectclass: domain<br>objectclass: extensibleObject<br>dc: springframework<br><br>dn: ou=groups,dc=springframework,dc=org<br>objectclass: top<br>objectclass: organizationalUnit<br>ou: groups<br><br>dn: ou=subgroups,ou=groups,dc=springframework,dc=org<br>objectclass: top<br>objectclass: organizationalUnit<br>ou: subgroups<br><br>dn: ou=people,dc=springframework,dc=org<br>objectclass: top<br>objectclass: organizationalUnit<br>ou: people<br><br>dn: ou=space cadets,dc=springframework,dc=org<br>objectclass: top<br>objectclass: organizationalUnit<br>ou: space cadets<br><br>dn: ou=\&quot;quoted people\&quot;,dc=springframework,dc=org<br>objectclass: top<br>objectclass: organizationalUnit<br>ou: &quot;quoted people&quot;<br><br>dn: ou=otherpeople,dc=springframework,dc=org<br>objectclass: top<br>objectclass: organizationalUnit<br>ou: otherpeople<br><br>dn: uid=ben,ou=people,dc=springframework,dc=org<br>objectclass: top<br>objectclass: person<br>objectclass: organizationalPerson<br>objectclass: inetOrgPerson<br>cn: Ben Alex<br>sn: Alex<br>uid: ben<br>userPassword: $2a$10$c6bSeWPhg06xB1lvmaWNNe4NROmZiSpYhlocU/98HNr2MhIOiSt36<br><br>dn: uid=bob,ou=people,dc=springframework,dc=org<br>objectclass: top<br>objectclass: person<br>objectclass: organizationalPerson<br>objectclass: inetOrgPerson<br>cn: Bob Hamilton<br>sn: Hamilton<br>uid: bob<br>userPassword: bobspassword<br><br>dn: uid=joe,ou=otherpeople,dc=springframework,dc=org<br>objectclass: top<br>objectclass: person<br>objectclass: organizationalPerson<br>objectclass: inetOrgPerson<br>cn: Joe Smeth<br>sn: Smeth<br>uid: joe<br>userPassword: joespassword<br><br>dn: cn=mouse\, jerry,ou=people,dc=springframework,dc=org<br>objectclass: top<br>objectclass: person<br>objectclass: organizationalPerson<br>objectclass: inetOrgPerson<br>cn: Mouse, Jerry<br>sn: Mouse<br>uid: jerry<br>userPassword: jerryspassword<br><br>dn: cn=slash/guy,ou=people,dc=springframework,dc=org<br>objectclass: top<br>objectclass: person<br>objectclass: organizationalPerson<br>objectclass: inetOrgPerson<br>cn: slash/guy<br>sn: Slash<br>uid: slashguy<br>userPassword: slashguyspassword<br><br>dn: cn=quote\&quot;guy,ou=\&quot;quoted people\&quot;,dc=springframework,dc=org<br>objectclass: top<br>objectclass: person<br>objectclass: organizationalPerson<br>objectclass: inetOrgPerson<br>cn: quote\&quot;guy<br>sn: Quote<br>uid: quoteguy<br>userPassword: quoteguyspassword<br><br>dn: uid=space cadet,ou=space cadets,dc=springframework,dc=org<br>objectclass: top<br>objectclass: person<br>objectclass: organizationalPerson<br>objectclass: inetOrgPerson<br>cn: Space Cadet<br>sn: Cadet<br>uid: space cadet<br>userPassword: spacecadetspassword<br><br><br><br>dn: cn=developers,ou=groups,dc=springframework,dc=org<br>objectclass: top<br>objectclass: groupOfUniqueNames<br>cn: developers<br>ou: developer<br>uniqueMember: uid=ben,ou=people,dc=springframework,dc=org<br>uniqueMember: uid=bob,ou=people,dc=springframework,dc=org<br><br>dn: cn=managers,ou=groups,dc=springframework,dc=org<br>objectclass: top<br>objectclass: groupOfUniqueNames<br>cn: managers<br>ou: manager<br>uniqueMember: uid=ben,ou=people,dc=springframework,dc=org<br>uniqueMember: cn=mouse\, jerry,ou=people,dc=springframework,dc=org<br><br>dn: cn=submanagers,ou=subgroups,ou=groups,dc=springframework,dc=org<br>objectclass: top<br>objectclass: groupOfUniqueNames<br>cn: submanagers<br>ou: submanager<br>uniqueMember: uid=ben,ou=people,dc=springframework,dc=org</pre><p><strong>Step 4: Create an API Controller</strong></p><p>Create a simple controller to test the application:</p><pre>@RestController<br>public class ApplicationController {<br>    @GetMapping(&quot;/&quot;)<br>    public String home(){<br>        return &quot;welcome&quot;;<br>    }<br>}</pre><p><strong>Step 5: Configure Spring Security for LDAP</strong></p><p>Create a configuration class to integrate Spring Security with LDAP:</p><pre>@EnableWebSecurity<br>public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {<br>    @Autowired<br>    UserDetailsService userDetailsService;<br><br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        auth.ldapAuthentication()<br>                .userDnPatterns(&quot;uid={0},ou=people&quot;)<br>                .groupSearchBase(&quot;ou=groups&quot;)<br>                .contextSource()<br>                .url(https://medium.com/&quot;ldap://localhost:8389/dc=springframework,dc=org&quot;)<br>                .and()<br>                .passwordCompare()<br>                .passwordEncoder(new LdapShaPasswordEncoder())<br>                .passwordAttribute(&quot;userPassword&quot;);<br>    }<br><br>    @Override<br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.authorizeRequests()<br>                .anyRequest().fullyAuthenticated()<br>                .and()<br>                .formLogin();<br>    }<br>}</pre><p><strong>Step 6: Run the Application</strong></p><p>With everything set up, you can now run your Spring Boot application. Once it’s running, you should be able to access the / endpoint at http://localhost:8080/, which will prompt for authentication. You can use any of the users defined in the ldap-data.ldif file (e.g., ben, bob, etc.) to log in.</p><p>This setup integrates an embedded LDAP server into your Spring Boot application, allowing you to authenticate against it using Spring Security.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=215dcc0aecf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Authentication with JWT]]></title>
            <link>https://medium.com/@dinelywh78/spring-boot-authentication-with-jwt-d2a4dc838c0d?source=rss-8f96a7be42af------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2a4dc838c0d</guid>
            <dc:creator><![CDATA[Dinely Shanuka]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 08:54:38 GMT</pubDate>
            <atom:updated>2024-08-09T10:33:08.711Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is JWT?</strong></h3><p>Jason Web Tokens(JWT) is a very popular way to do user authorization in web apps today. JWTs are value tokens that contain claims encoded as a JSON object, used as the payload of a JSON Web Signature (JWS) structure.</p><p>You can find the boilerplate code for this project on my <a href="https://github.com/DinelyWellehewage/spring-security-jwt">https://github.com/DinelyWellehewage/spring-security-jwt</a>.</p><p>There are different types of tokens in the context of web authentication and state management.</p><ul><li><strong>Session token — Reference token — Reference to state</strong></li></ul><p>This token is typically stored on the server side. The server keeps track of this token and uses it to manage a user’s session. It often refers to a session record on the server.</p><ul><li><strong>JSON web token — Value token- Contains value</strong></li></ul><p>The claims in JWT are encoded as a JSON object that is used as the payload of a JSON web signature structure. It contains actual data (or value) within the token itself.</p><p>Let’s look through the process of how JWTs work in the context of client-server communication.</p><h4><strong>JWT in Client-Server Communication</strong></h4><ol><li>Client Authentication</li></ol><ul><li>When a user logs in, the server authenticates their credentials (username and password).</li><li>After successful authentication, the server generates a JWT.</li></ul><p>2. JWT Issuance</p><ul><li>The JWT contains claims as data about the user and relevant information such as roles or permissions, and the expiration time of the token.</li></ul><p>3. Subsequent Request</p><ul><li>For each subsequent request to the server, the client includes the JWT, usually in the Authorization header (eg: “Authorization: Bearer &lt;JWT&gt;”).</li><li>The server receives the JWT and extracts it from the request.</li></ul><p>4. Signature Verification</p><ul><li>The server verifies the signature of the JWT using the same secret key.</li><li>If the signature is valid, the server knows that the token has not been tampered with and that it can trust the information contained within it.</li></ul><p>5. Token Decoding</p><ul><li>The server decodes the JWT and retrieves the claims, which include the user’s identity, roles, and permissions.</li><li>The server processes requests to check if the user has permission to access a specific resource.</li></ul><p>6. Request Processing.</p><ul><li>If the token is valid and the user has the required permissions, the server processes the request and sends back the appropriate response.</li></ul><p>7. Token Expiry</p><ul><li>If the JWT is expired or the signature is invalid, the server rejects the request sending 401 Unauthorized.</li></ul><p><strong>Structure of a JWT</strong></p><p>A JWT consists of three parts.</p><ol><li>Header — Contains the token type (JWT) and signing algorithm (eg: HS256).</li><li>Payload — Contains the claims, such as user information and expiration time.</li><li>Signature — Used to verify the token’s integrity.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*G4ZQAlHdEAyAmh-L5kpePQ.png" /></figure><p>The point of creating JWT is the ability to send some value from the server to the client so that the client can send it back on subsequent requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZiuyXN5jqtcY32-_b_tzA.png" /></figure><p>When the user sends the user ID and password, the server authenticates the user and then creates a JWT token for future authorization purposes and sends it to the client. When the client gets JWT it can either hold on to it in local storage or it can hold on to it in a cookie. It has to pass it on every subsequent request using the HTTP header. HTTP headers are key-value pairs hence key for passing this according to the JWT standard is called authorization and the value is the word Bearer followed by a space followed by JWT. Client on every subsequent request puts JWT in the header and sends it to the server. Then the server examines the request and checks the value in the header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*mFYtPiLBihFeTXTTJVKlOQ.png" /></figure><p>JWT has no confidential/sensitive information in a JWT. It only has enough information for the server to know who the user is. The client can set up expiration on JWT. Also, the server can blacklist JWTs.</p><p><strong>Step 1: Set up the Spring Boot Project</strong></p><p>Let’s create a basic Spring web application using <a href="https://start.spring.io/">https://start.spring.io/</a> and generate a template project with dependencies such as ‘Spring Web’, ‘Spring Security’, and ‘jjwt’.</p><p><strong>Step 2: JWT Utility Class</strong></p><p>Here’s the JwtUtil.class which handles the token generation, validation, and extraction.</p><pre>import io.jsonwebtoken.Claims;<br>import io.jsonwebtoken.Jwts;<br>import io.jsonwebtoken.SignatureAlgorithm;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.stereotype.Service;<br><br>import java.util.Date;<br>import java.util.HashMap;<br>import java.util.Map;<br>import java.util.function.Function;<br><br>@Service<br>public class JwtUtil {<br><br>    private String SECRET_KEY = &quot;secret&quot;;<br><br>    public String extractUsername(String token) {<br>        return extractClaim(token, Claims::getSubject);<br>    }<br><br>    public Date extractExpiration(String token) {<br>        return extractClaim(token, Claims::getExpiration);<br>    }<br><br>    public &lt;T&gt; T extractClaim(String token, Function&lt;Claims, T&gt; claimsResolver) {<br>        final Claims claims = extractAllClaims(token);<br>        return claimsResolver.apply(claims);<br>    }<br>    private Claims extractAllClaims(String token) {<br>        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();<br>    }<br><br>    private Boolean isTokenExpired(String token) {<br>        return extractExpiration(token).before(new Date());<br>    }<br><br>    public String generateToken(UserDetails userDetails) {<br>        Map&lt;String, Object&gt; claims = new HashMap&lt;&gt;();<br>        return createToken(claims, userDetails.getUsername());<br>    }<br><br>    private String createToken(Map&lt;String, Object&gt; claims, String subject) {<br><br>        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))<br>                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))<br>                .signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();<br>    }<br><br>    public Boolean validateToken(String token, UserDetails userDetails) {<br>        final String username = extractUsername(token);<br>        return (username.equals(userDetails.getUsername()) &amp;&amp; !isTokenExpired(token));<br>    }<br>}</pre><p><strong>Step 3: Authentication Models</strong></p><p>Define models for authentication requests and responses.</p><ul><li>Accepts userId and password</li><li>Returns JWT as a response</li></ul><p>Let’s create AuthenticationRequest.class as the input structure for the authentication method which takes in username and password in post request.</p><pre>public class AuthenticationRequest {<br><br>    private String username;<br>    private String password;<br><br>    public AuthenticationRequest() {<br>    }<br><br>    public AuthenticationRequest(String username, String password) {<br>        this.username = username;<br>        this.password = password;<br>    }<br><br>    public String getUsername() {<br>        return username;<br>    }<br><br>    public void setUsername(String username) {<br>        this.username = username;<br>    }<br><br>    public String getPassword() {<br>        return password;<br>    }<br><br>    public void setPassword(String password) {<br>        this.password = password;<br>    }<br>}</pre><p>Next, Let’s create the AuthenticationResponse.class as output structure for the authentication method which is a property called jwt and response with actual jwt value.</p><pre>public class AuthenticationResponse {<br>    private final String jwt;<br><br>    public AuthenticationResponse(String jwt) {<br>        this.jwt = jwt;<br>    }<br><br>    public String getJwt() {<br>        return jwt;<br>    }<br>}</pre><p><strong>Step 4: User Details Service</strong></p><p>The MyUserDetailsService.class provides user details for authentication.</p><pre>import org.springframework.security.core.userdetails.User;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.security.core.userdetails.UserDetailsService;<br>import org.springframework.security.core.userdetails.UsernameNotFoundException;<br>import org.springframework.stereotype.Service;<br><br>import java.util.ArrayList;<br>@Service<br>public class MyUserDetailsService implements UserDetailsService {<br>    @Override<br>    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<br>        return new User(&quot;foo&quot;,&quot;foo&quot;,new ArrayList&lt;&gt;());<br>    }<br>}</pre><p><strong>Step 5: Security Configuration</strong></p><p>Let’s configure Spring Security to authenticate users in SpringSecurityConfig.class.</p><pre>import com.example.spring_security_jwt.services.MyUserDetailsService;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.security.authentication.AuthenticationManager;<br>import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;<br>import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;<br>import org.springframework.security.crypto.password.NoOpPasswordEncoder;<br>import org.springframework.security.crypto.password.PasswordEncoder;<br><br>@EnableWebSecurity<br>public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {<br>    @Autowired<br>    private MyUserDetailsService userDetailsService;<br><br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        auth.userDetailsService(userDetailsService);<br>    }<br>    @Bean<br>    public PasswordEncoder getPasswordEncoder() {<br>        return NoOpPasswordEncoder.getInstance();<br>    }<br><br>    @Override<br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.csrf().disable()<br>                .authorizeRequests().antMatchers(&quot;/authenticate&quot;).permitAll().anyRequest().authenticated();<br>    }<br><br>    @Override<br>    @Bean<br>    protected AuthenticationManager authenticationManager() throws Exception {<br>        return super.authenticationManager();<br>    }<br>}</pre><p><strong>Step 6: Authentication Controller</strong></p><p>Let’s create a controller class for the subsequent endpoint and authentication endpoint.</p><pre>import com.example.spring_security_jwt.models.AuthenticationRequest;<br>import com.example.spring_security_jwt.models.AuthenticationResponse;<br>import com.example.spring_security_jwt.services.MyUserDetailsService;<br>import com.example.spring_security_jwt.util.JwtUtil;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.security.authentication.AuthenticationManager;<br>import org.springframework.security.authentication.BadCredentialsException;<br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.web.bind.annotation.*;<br><br>@RestController<br>public class ApplicationController {<br>    @Autowired<br>    private AuthenticationManager authenticationManager;<br>    @Autowired<br>    private MyUserDetailsService userDetailsService;<br>    @Autowired<br>    private JwtUtil jwtUtil;<br>    @RequestMapping({&quot;/hello&quot;})<br>    public String home(){<br>        return &quot;welcome&quot;;<br>    }<br>    @RequestMapping(value = &quot;/authenticate&quot;,method = RequestMethod.POST)<br>    public ResponseEntity&lt;?&gt; createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest) throws Exception{<br>        try {<br>            authenticationManager.authenticate(<br>                    new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(),authenticationRequest.getPassword())<br>            );<br>        }catch (BadCredentialsException e){<br>            throw new Exception(&quot;Incorrect username or password&quot;,e);<br>        }<br>        final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());<br>        final String jwt = jwtUtil.generateToken(userDetails);<br>        return ResponseEntity.ok(new AuthenticationResponse(jwt));<br>    }<br>}</pre><p>Then the postman response for the token generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hBOD9FrqIqmo0UW98HywtQ.png" /></figure><p>Then pass this token to subsequent requests.</p><p><strong>Step 7: Intercept all incoming requests</strong></p><ul><li>extract JWT from the header</li><li>validate and set in the execution context</li></ul><p>So for that let’s implement a filter to intercept requests and validate JWTs.</p><pre>import com.example.spring_security_jwt.services.MyUserDetailsService;<br>import com.example.spring_security_jwt.util.JwtUtil;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.context.SecurityContextHolder;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.filter.OncePerRequestFilter;<br>import javax.servlet.FilterChain;<br>import javax.servlet.ServletException;<br>import javax.servlet.http.HttpServletRequest;<br>import javax.servlet.http.HttpServletResponse;<br>import java.io.IOException;<br><br>@Component<br>public class JwtRequestFilter extends OncePerRequestFilter {<br>    @Autowired<br>    private MyUserDetailsService userDetailsService;<br>    @Autowired<br>    private JwtUtil jwtUtil;<br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {<br>        final String authorizationHeader = request.getHeader(&quot;Authorization&quot;);<br>        String username = null;<br>        String jwt = null;<br><br>        if(authorizationHeader!=null &amp;&amp; authorizationHeader.startsWith(&quot;Bearer &quot;)){<br>            jwt = authorizationHeader.substring(7);<br>            username = jwtUtil.extractUsername(jwt);<br>        }<br>        if(username!=null &amp;&amp; SecurityContextHolder.getContext().getAuthentication()==null){<br>            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);<br>            if(jwtUtil.validateToken(jwt,userDetails)){<br>                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(<br>                        userDetails,null,userDetails.getAuthorities()<br>                );<br>                usernamePasswordAuthenticationToken.setDetails((new WebAuthenticationDetailsSource().buildDetails(request)));<br>                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);<br>            }<br>        }<br>        filterChain.doFilter(request,response);<br>    }<br>}</pre><p>Then pass the filter to the security configuration for authentication. Here’s the SpringSecurityConfig.class after applying JWT filters.</p><pre>import com.example.spring_security_jwt.filters.JwtRequestFilter;<br>import com.example.spring_security_jwt.services.MyUserDetailsService;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.security.authentication.AuthenticationManager;<br>import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;<br>import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;<br>import org.springframework.security.config.http.SessionCreationPolicy;<br>import org.springframework.security.crypto.password.NoOpPasswordEncoder;<br>import org.springframework.security.crypto.password.PasswordEncoder;<br>import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;<br><br>@EnableWebSecurity<br>public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {<br>    @Autowired<br>    private MyUserDetailsService userDetailsService;<br><br>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        auth.userDetailsService(userDetailsService);<br>    }<br>    @Autowired<br>    private JwtRequestFilter jwtRequestFilter;<br>    @Bean<br>    public PasswordEncoder getPasswordEncoder() {<br>        return NoOpPasswordEncoder.getInstance();<br>    }<br><br>    @Override<br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.csrf().disable()<br>                .authorizeRequests().antMatchers(&quot;/authenticate&quot;).permitAll()<br>                .anyRequest().authenticated()<br>                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);<br>        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);<br>    }<br><br>    @Override<br>    @Bean<br>    protected AuthenticationManager authenticationManager() throws Exception {<br>        return super.authenticationManager();<br>    }<br>}</pre><p><strong>Step 9: Testing with Postman</strong></p><p>Here’s the final response to the request authorizing the JWT token after using the JWT in the Authorization header to access the secured endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_NKwlq2CJx7UKU2pXUAhQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2a4dc838c0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>