<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Aditya Singh Rajput</title>
    <description>The latest articles on DEV Community by Aditya Singh Rajput (@aditya_singh_rajput).</description>
    <link>https://dev.to/aditya_singh_rajput</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1755287%2F3b9c3e28-41b9-4504-b8ac-0cbb05624cb7.jpg</url>
      <title>DEV Community: Aditya Singh Rajput</title>
      <link>https://dev.to/aditya_singh_rajput</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/aditya_singh_rajput"/>
    <language>en</language>
    <item>
      <title>Blinking Fast Api's</title>
      <dc:creator>Aditya Singh Rajput</dc:creator>
      <pubDate>Fri, 20 Sep 2024 09:23:15 +0000</pubDate>
      <link>https://dev.to/aditya_singh_rajput/redis-cache-in-spring-boot-d2c</link>
      <guid>https://dev.to/aditya_singh_rajput/redis-cache-in-spring-boot-d2c</guid>
      <description>&lt;h2&gt;
  
  
  What is Redis?
&lt;/h2&gt;

&lt;p&gt;Remote Dictionary Server, aka Redis, an in-memory data store, is one of the many options for implementing caching in Spring Boot applications due to its speed, versatility, and simplicity of use. It is a versatile key-value store that supports several data structures, such as Strings, Sorted Sets, Hashes, Lists, Streams, Bitmaps, Sets, etc., because it is a NoSQL database and doesn’t need a predetermined schema.&lt;/p&gt;

&lt;p&gt;Redis can be used in various ways, including:&lt;/p&gt;

&lt;p&gt;1)** In-Memory Database: ** In today’s data-driven world, handling vast amounts of real-time data is a common challenge for businesses. A real-time database is a type of data repository designed to acquire, analyze, and/or augment an incoming stream of data points in real time, often immediately after the data is produced. Redis may be used to build data infrastructure for real-time applications that need high throughput and low latency.&lt;/p&gt;

&lt;p&gt;2) *&lt;em&gt;Cache: *&lt;/em&gt; Many applications struggle with the need to store and retrieve data quickly, especially in systems with high latency. Due to its speed, Redis is the ideal choice for caching API calls, session states, complex computations, and database queries.&lt;/p&gt;

&lt;p&gt;3) *&lt;em&gt;Message Broker (MQ): *&lt;/em&gt; It has always been difficult to stream data around the organization and make it accessible for various system components. Redis supports messaging, event sources, alerts, and high-speed data intake using its stream data type.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Does Redis Caching Work?
&lt;/h2&gt;

&lt;p&gt;Redis Cache effectively stores the results of database retrieval operations, allowing subsequent requests to retrieve the data directly from the cache. This significantly enhances application performance by reducing unnecessary database calls.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkujemubwzs80q5uf8a3b.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkujemubwzs80q5uf8a3b.jpg" alt="Image description" width="" height=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When a request is made, the service initially looks in the Redis cache for the desired data. When a cache hit occurs, the data is swiftly retrieved from the cache and promptly provided back to the service, avoiding the need to interact with the database.&lt;/p&gt;

&lt;p&gt;However, if the requested data is not found in the cache (cache miss), the service intelligently falls back to the database to retrieve the required information. Subsequently, the fetched data is stored in the Redis cache, enabling future requests for the same data to be served directly from the cache, thereby eliminating further database queries and speeding up overall response times.&lt;/p&gt;

&lt;p&gt;Redis can also be used for deleting and updating tasks, guaranteeing consistent and latest data in the cache and further boosting overall efficiency.&lt;/p&gt;

&lt;h2&gt;
  
  
  Let's Set up Our Spring Boot Application!
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Add Redis dependency&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
   &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
   &amp;lt;artifactId&amp;gt;spring-boot-starter-data-redis&amp;lt;/artifactId&amp;gt;
   &amp;lt;version&amp;gt;3.1.2&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Redis-related libraries are part of the Spring Data Package, which provides easy access to databases, relational and non-relational databases, map-reduce frameworks, and cloud-based data services. The spring-boot-starter-data-redis will have all the necessary dependencies prepared.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 2: Configure Redis using application.yml or you can use application.properties file as well.
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring:
  cache:
    type: redis
    host: localhost
    port: 6379
    redis:
      time-to-live: 60000
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/inventory
    username: root
    password: ****
  jpa:
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The PostgreSQL database is used, and the necessary database connection properties are introduced. In addition, we define Redis as our cache provider, along with its hostname and port.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Time To Live(TTL):&lt;/strong&gt; A good practice for caching is to ensure that excess and redundant data is not accumulated indefinitely, as this can result in stale or outdated data being served to users. To serve this, we can take advantage of the time-to-live property, which is an optional setting that allows us to set the expiration time for cached data. After the specified time has elapsed, the cached entry is automatically removed from the cache. This makes space for new data to be fetched and stored in the cache the next time it’s requested. If no value is assigned to the property, it becomes -1 by default, which means the data will stay in the cache indefinitely.&lt;/p&gt;

&lt;p&gt;We have set our time to live property to be 60000 ms in the example, which means that the data will be cleared from the cache after every minute.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 3: Creating entity and repository**
&lt;/h2&gt;

&lt;p&gt;Set up the entity and repository to perform CRUD operations like any other Spring Boot project. Since Redis is an in-memory database, we need to transform our object into a stream of bytes for storing as well as the other way around for retrieving data. Therefore, we need to serialize/deserialize our data by ensuring that the entity class implements the Serializable class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity
public class Product implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;
    private String code;
    private int quantity;
    private double price;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have an entity responsible for storing and fetching data, so we can create our repository by extending the JpaRepository interface. It will provide basic CRUD operations to work with, like save, find, and delete.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Repository
public interface ProductRepository extends JpaRepository&amp;lt;Product, Long&amp;gt; {
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 4: Enable caching in spring boot
&lt;/h2&gt;

&lt;p&gt;Add the annotation @EnableCaching to the starter class. It will trigger a post-processor that inspects every Spring bean for the presence of caching annotations on public methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@SpringBootApplication
@EnableCaching
public class RedisDemoApplication {

  public static void main(String[] args) {
  SpringApplication.run(RedisDemoApplication.class, args);
 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 5: Annotation-based caching on the controller layer
&lt;/h2&gt;

&lt;p&gt;Use caching annotations in the controller layer to enable caching for specific methods:&lt;/p&gt;

&lt;p&gt;@Cacheable is employed to fetch data from the database, storing it in the cache. Upon future invocations, the method retrieves the cached value directly, eliminating the need to execute the method again.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@GetMapping("/product/{id}")  
@Cacheable(value = "product", key = "#id")
public Product getProductById(@PathVariable long id) {...}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The value attribute establishes a cache with a specific name, while the key attribute permits the use of Spring Expression Language to compute the key dynamically. Consequently, the method result is stored in the ‘product’ cache, where respective ‘product_id’ serves as the unique key. This approach optimizes caching by associating each result with a distinct key.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;@CachePut is used to update data in the cache when there is any update in the source database.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@PutMapping("/product/{id}")
@CachePut(cacheNames = "product", key = "#id")
public Product editProduct(@PathVariable long id, @RequestBody Product product) {...}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The cacheNames attribute is an alias for value, and can be used in a similar manner.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;@CacheEvict is used for removing stale or unused data from the cache.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@DeleteMapping("/product/{id}")
@CacheEvict(cacheNames = "product", key = "#id", beforeInvocation = true)
public String removeProductById(@PathVariable long id) {...}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We use cacheName and key to remove specific data from the cache. The beforeInvocation attribute allows us to control the eviction process, enabling us to choose whether the eviction should occur before or after the method execution.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@DeleteMapping("/product/{id}")
 @CacheEvict(cacheNames = "product", allEntries = true)
 public String removeProductById(@PathVariable long id) {...}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alternatively, all the data can also be removed for a given cache by using the allEntries attribute as true. The annotation allows us to clear data for multiple caches as well by providing multiple values as cacheName.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;@Caching is used for multiple nested caching on the same method.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@PutMapping("/{id}")
@Caching(
     evict = {@CacheEvict(value = "productList", allEntries = true)},
     put = {@CachePut(value = "product", key = "#id")}
)
public Product editProduct(@PathVariable long id, @RequestBody Product product) {...}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As Java doesn’t allow multiple annotations of the same type to be declared for a method, doing so will generate a compilation error. We can group different annotations into Caching, as shown above.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;@CacheConfig is used for centralized configuration.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@CacheConfig(cacheNames = "product")
public class ProductController {...}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Used as a class-level annotation, Cache config allows centralizing some of the configurations to avoid specifying it at each step. For the example above, we need not write cacheName for all methods, instead, specify the cache name at the class level.&lt;/p&gt;

&lt;p&gt;Using keyGenerator attribute:&lt;/p&gt;

&lt;p&gt;This is responsible for generating every key for each data item in the cache, which would be used to look up the data item on retrieval. The default implementation here is the SimpleKeyGenerator — which uses the method parameters provided to generate a key, as shown earlier. However, we may want to provide a more customized approach to generate the cache key based on specific criteria. To achieve this, we can use the keyGenerator attribute.&lt;/p&gt;

&lt;p&gt;To give a different custom key generator, we need to implement the org.springframework.cache.interceptor.KeyGenerator interface. The class needs to implement a single method as shown:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CustomKeyGenerator implements KeyGenerator {
  @Override
  public Object generate(Object target, Method method, Object... params) {
      return target.getClass().getSimpleName() + "_"
        + method.getName() + "_"
        + StringUtils.arrayToDelimitedString(params, "_");
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can now use the customeKeyGenerator as a value to keyGenerator attribute and provide a customized key generator for the given method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@GetMapping("/product/{id}")  
@Cacheable(value = "product", keyGenerator = "customKeyGenerator")
public Product getProductById(@PathVariable long id) {...}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Conditional caching:&lt;/p&gt;

&lt;p&gt;Conditional caching allows us to cache specific data using the unless and conditional attributes. The unlessattribute allows us to filter data after the method has been called. By using the Spring Expression Language, we can choose not to cache the data if a certain condition evaluates to true. In the given example, we have allowed caching only for products priced less than 1000. This way, we cache selectively based on the defined condition.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@GetMapping("/product/{id}")  
@Cacheable(value = "product", key = "#id" , unless = "#result.price &amp;gt; 1000")
public Product getProductById(@PathVariable long id) {...}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The conditional attribute, however, works quite the opposite. If the condition happens to be true, then the resulting data is cached in our cache. For the given example, only products named fridge will be stored in the cache.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@PutMapping("/{id}")
@Caching( value = "product", condition = "#product.name == "Fridge""))
public Product editProduct(@PathVariable long id, @RequestBody Product product) {...}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Wrapping Up
&lt;/h2&gt;

&lt;p&gt;In this post, we discussed the basics of using Spring caching in your application. Remember to fine-tune your caching configuration based on your application’s specific needs.&lt;/p&gt;

&lt;p&gt;Integrating Redis cache into your Spring Boot applications can significantly enhance their performance and scalability. Redis’s in-memory storage and blazing-fast read/write operations make it an excellent choice for caching frequently accessed data. By intelligently using caching strategies and leveraging Redis’ distributed architecture, you can create responsive and efficient applications that deliver an exceptional user experience.&lt;/p&gt;

</description>
      <category>java</category>
      <category>api</category>
      <category>microservices</category>
      <category>springboot</category>
    </item>
    <item>
      <title>OAuth2.0 Spring Boot</title>
      <dc:creator>Aditya Singh Rajput</dc:creator>
      <pubDate>Thu, 19 Sep 2024 22:12:04 +0000</pubDate>
      <link>https://dev.to/aditya_singh_rajput/oauth20-spring-boot-367</link>
      <guid>https://dev.to/aditya_singh_rajput/oauth20-spring-boot-367</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;OAuth 2.0 is an authorization framework that enables third-party applications to access protected resources on behalf of a user without requiring the user’s credentials. This is achieved through the use of access tokens, which are issued by an OAuth provider and used by third-party applications to access the user’s resources.&lt;/p&gt;

&lt;p&gt;Spring Boot is a popular framework for building web applications in Java. It provides a powerful set of tools for building secure and scalable web applications and is well-suited for implementing OAuth 2.0.&lt;/p&gt;

&lt;p&gt;In this blog post, we will go through the steps required to implement OAuth 2.0 using Spring Boot. We will use the Spring Security OAuth 2.0 framework to implement OAuth 2.0 authorization and authentication.&lt;/p&gt;

&lt;p&gt;Before we start, let’s first go through the OAuth 2.0 flow to get a better understanding of how it works.&lt;/p&gt;

&lt;h2&gt;
  
  
  Overview of OAuth 2.0
&lt;/h2&gt;

&lt;p&gt;OAuth 2.0 is an authorization protocol that allows third-party applications to access resources on behalf of a user. It uses access tokens to provide access to resources, which are obtained after successful authentication. There are four roles in OAuth 2.0: Resource Owner, Client, Authorization Server, and Resource Server.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Resource Owner: The user who owns the resource that is being accessed by the client.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;2.Client: The application that is requesting access to the resource on behalf of the user.&lt;/p&gt;

&lt;p&gt;3.Authorization Server: The server that issues access tokens to the client after successful authentication of the user.&lt;/p&gt;

&lt;p&gt;4.Resource Server: The server that holds the resource that is being accessed by the client.&lt;/p&gt;

&lt;h2&gt;
  
  
  OAuth 2.0 Flow
&lt;/h2&gt;

&lt;p&gt;The OAuth 2.0 flow involves the following steps:&lt;/p&gt;

&lt;p&gt;User requests access to a protected resource from a third-party application.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;The third-party application redirects the user to an OAuth provider to obtain an access token.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The user logs in to the OAuth provider and grants permission to the third-party application to access the protected resource.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The OAuth provider issues an access token to the third-party application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The third-party application uses the access token to access the protected resource on behalf of the user.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now that we have an understanding of the OAuth 2.0 flow, let’s move on to implementing it using Spring Boot.&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementing OAuth 2.0 using Spring Boot
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Add dependencies&lt;/strong&gt;&lt;br&gt;
First, add the necessary dependencies to your Spring Boot project. You can do this by adding the following dependencies to your pom.xml file:&lt;/p&gt;

&lt;p&gt;`&lt;br&gt;
    org.springframework.boot&lt;br&gt;
    spring-boot-starter-oauth2-client&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;br&gt;
    org.springframework.security&lt;br&gt;
    spring-security-oauth2-jose&lt;br&gt;
`&lt;/p&gt;

&lt;h2&gt;
  
  
  Configure OAuth 2.0
&lt;/h2&gt;

&lt;p&gt;Next, configure OAuth 2.0 by creating a class that extends WebSecurityConfigurerAdapter. Here's an example:&lt;/p&gt;

&lt;p&gt;`@Configuration&lt;br&gt;
@EnableWebSecurity&lt;br&gt;
public class SecurityConfig extends WebSecurityConfigurerAdapter {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/oauth2/**", "/login/**", "/logout/**")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
        .oauth2Login()
            .loginPage("/login")
            .defaultSuccessURL("/home")
            .and()
        .logout()
            .logoutSuccessUrl("/")
            .logoutUrl("/logout")
            .and()
        .csrf().disable();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;This configuration allows anyone to access the /oauth2/&lt;strong&gt;, /login/&lt;/strong&gt;, and /logout/** endpoints. All other endpoints require authentication. When a user logs in via OAuth 2.0, they will be redirected to the /home endpoint. When they log out, they will be redirected to the / endpoint.&lt;/p&gt;

&lt;h2&gt;
  
  
  Generate a Token
&lt;/h2&gt;

&lt;p&gt;To generate a token, you can use the JwtBuilder class from the spring-security-oauth2-jose dependency. Here's an example:&lt;/p&gt;

&lt;p&gt;`import org.springframework.security.oauth2.jwt.Jwt;&lt;br&gt;
import org.springframework.security.oauth2.jwt.JwtBuilder;&lt;br&gt;
import org.springframework.security.oauth2.jwt.Jwts;&lt;br&gt;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;&lt;/p&gt;

&lt;p&gt;import java.security.KeyPair;&lt;br&gt;
import java.security.KeyPairGenerator;&lt;br&gt;
import java.security.NoSuchAlgorithmException;&lt;br&gt;
import java.time.Instant;&lt;br&gt;
import java.util.Date;&lt;/p&gt;

&lt;p&gt;public class TokenGenerator {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void main(String[] args) throws NoSuchAlgorithmException {
    // Generate a key pair
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    // Build the JWT
    JwtBuilder jwtBuilder = Jwts.builder()
            .setIssuer("https://example.com")
            .setAudience("https://example.com/resources")
            .setId("123")
            .setSubject("user@example.com")
            .setExpiration(Date.from(Instant.now().plusSeconds(3600)))
            .setIssuedAt(new Date())
            .signWith(new NimbusJwtEncoder(keyPair.getPrivate()));

    Jwt jwt = jwtBuilder.build();
    System.out.println(jwt.getTokenValue());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;This code generates a key pair, builds a JWT with the necessary claims, and signs it with the private key. The resulting token is printed to the console.&lt;/p&gt;

&lt;p&gt;Note that this is just an example of how to generate a token. In practice, you would want to store the private key securely and use a different method of generating the expiration time.&lt;/p&gt;

&lt;h2&gt;
  
  
  Configure OAuth 2.0 Client
&lt;/h2&gt;

&lt;p&gt;To use OAuth 2.0 in your application, you’ll need to configure a client. In Spring Boot, you can do this by adding properties to your application.properties file. Here's an example:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;spring.security.oauth2.client.registration.example.client-id=client-id&lt;br&gt;
spring.security.oauth2.client.registration.example.client-secret=client-secret&lt;br&gt;
spring.security.oauth2.client.registration.example.scope=read,write&lt;br&gt;
spring.security.oauth2.client.registration.example.redirect-uri=http://localhost:8080/login/oauth2/code/example&lt;br&gt;
spring.security.oauth2.client.provider.example.authorization-uri=https://example.com/oauth2/authorize&lt;br&gt;
spring.security.oauth2.client.provider.example.token-uri=https://example.com/oauth2/token&lt;br&gt;
spring.security.oauth2.client.provider.example.user-info-uri=https://example.com/userinfo&lt;br&gt;
spring.security.oauth2.client.provider.example.user-name-attribute=name&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This configuration sets up an OAuth 2.0 client with the client ID and client secret provided by the example registration. It also sets the desired scope, redirect URI, and authorization, token, and user info URIs for the provider. Finally, it specifies that the user's name should be retrieved from the name attribute in the user info response.&lt;/p&gt;

&lt;h2&gt;
  
  
  Use the Token
&lt;/h2&gt;

&lt;p&gt;Once you have a token, you can use it to access protected resources. For example, you can make an authenticated request to a resource server using the RestTemplate class. Here's an example:&lt;/p&gt;

&lt;p&gt;`import org.springframework.http.HttpEntity;&lt;br&gt;
import org.springframework.http.HttpHeaders;&lt;br&gt;
import org.springframework.http.HttpMethod;&lt;br&gt;
import org.springframework.http.ResponseEntity;&lt;br&gt;
import org.springframework.web.client.RestTemplate;&lt;/p&gt;

&lt;p&gt;public class ResourceClient {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void main(String[] args) {
    // Create a RestTemplate
    RestTemplate restTemplate = new RestTemplate();

    // Set the authorization header
    HttpHeaders headers = new HttpHeaders();
    headers.setBearerAuth("token");

    // Make the request
    HttpEntity&amp;lt;String&amp;gt; entity = new HttpEntity&amp;lt;&amp;gt;(headers);
    ResponseEntity&amp;lt;String&amp;gt; response = restTemplate.exchange(
            "https://example.com/resource",
            HttpMethod.GET,
            entity,
            String.class
    );

    // Print the response body
    System.out.println(response.getBody());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;This code sets the authorization header to the JWT token and makes a GET request to the /resource endpoint on the resource server. The response body is printed to the console.&lt;/p&gt;

&lt;h2&gt;
  
  
  Protect Endpoints
&lt;/h2&gt;

&lt;p&gt;To protect endpoints in your Spring Boot application, you can use annotations provided by Spring Security. For example, you can use the @PreAuthorize annotation to ensure that a user has a specific role before they can access an endpoint. Here's an example:&lt;/p&gt;

&lt;p&gt;`import org.springframework.security.access.prepost.PreAuthorize;&lt;br&gt;
import org.springframework.web.bind.annotation.GetMapping;&lt;br&gt;
import org.springframework.web.bind.annotation.RestController;&lt;/p&gt;

&lt;p&gt;@RestController&lt;br&gt;
public class MyController {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@GetMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public String adminEndpoint() {
    return "Hello, admin!";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;This code defines a controller with an endpoint that requires the user to have the ADMIN role in order to access it. If the user does not have the required role, they will receive a 403 Forbidden error.&lt;/p&gt;

&lt;p&gt;Test the OAuth 2.0 flow&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Start the application First, start the Spring Boot application that you’ve configured to use OAuth 2.0. You can do this by running the main() method in your application's main class.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Navigate to the login endpoint Next, navigate to the /login endpoint in your browser. For example, if your application is running on localhost:8080, you would go to &lt;a href="http://localhost:8080/login" rel="noopener noreferrer"&gt;http://localhost:8080/login&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Authenticate with the authorization server When you navigate to the login endpoint, your application will redirect you to the authorization server to authenticate. Depending on the authorization server, you may be prompted to enter your username and password, or you may be presented with a login button to authenticate with a third-party provider (such as Google or Facebook).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Grant access After you authenticate, you will be prompted to grant access to the scopes requested by the client. For example, if the client requested the read and write scopes, you may be prompted to grant access to read and write the user's data.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Receive the token Once you grant access, you will be redirected back to your application with an OAuth 2.0 token. This token can then be used to access protected resources.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;For example, if you protected an endpoint with the @PreAuthorize annotation as described in the previous example, you could navigate to that endpoint and test whether or not you have access. If you have the required role, you will see the response from the endpoint. If you do not have the required role, you will receive a 403 Forbidden error.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>springboot</category>
      <category>springsecurity</category>
      <category>java</category>
      <category>productivity</category>
    </item>
    <item>
      <title>The Art of Mastering Data Structures and Algorithms</title>
      <dc:creator>Aditya Singh Rajput</dc:creator>
      <pubDate>Sat, 03 Aug 2024 05:05:14 +0000</pubDate>
      <link>https://dev.to/aditya_singh_rajput/the-art-of-mastering-data-structures-and-algorithms-40e</link>
      <guid>https://dev.to/aditya_singh_rajput/the-art-of-mastering-data-structures-and-algorithms-40e</guid>
      <description>&lt;p&gt;**DSA (Data Structures and Algorithms) is often perceived as difficult, but it can be manageable if approached correctly.&lt;/p&gt;

&lt;p&gt;DSA consists of two parts: data structures and algorithms.&lt;/p&gt;

&lt;p&gt;Learning data structures is something you can do on your own with practice and understanding. However, algorithms can be more challenging and are often the reason people give up on DSA. If you don't find algorithms challenging, it might mean you're not fully engaging with DSA.**&lt;/p&gt;

&lt;h3&gt;
  
  
  In this journey with me, I will guide you on how to master data structures easily without going off track. Here are some key steps:
&lt;/h3&gt;

&lt;h2&gt;
  
  
  Understand the Basics:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Start with simple data structures like arrays, linked lists, stacks, and queues.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Build a strong foundation by understanding their properties and operations.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Use Visual Aids:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Utilize diagrams and visual tools to grasp the structure and behavior of data structures.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Explore interactive platforms to manipulate data structures and see real-time results.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Implement from Scratch:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Practice implementing each data structure in your preferred programming language.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Solve simple problems to reinforce your understanding and gradually increase complexity.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Leverage OOP Principles:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Use classes and objects to encapsulate data and methods for modular and manageable code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Utilize inheritance and polymorphism for flexible and reusable data structures.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Practice Regularly:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Dedicate consistent time to practice data structures daily or weekly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Challenge yourself with problems on platforms like LeetCode and HackerRank.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Learn the Applications:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Understand real-world use cases of each data structure for practical learning.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Integrate data structures with algorithms to solve complex problems efficiently.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Study from Multiple Sources:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Use a variety of resources like textbooks, online courses, and tutorials for diverse perspectives.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Join online communities and study groups for insights and motivation.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>dsa</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
