Topic 6: – 5 steps of Spring Boot Security

image 2

Play Store Application link – Spring Boot in 13 steps – App on Google Play


Github project link – https://github.com/kuldeep101990/Spring-Boot-Security

Step 1: Setting Up a Spring Boot Project

Using Spring Initializr

  1. Go to https://start.spring.io/.
  2. Fill in the details:
    • Project: Maven
    • Language: Java
    • Spring Boot: 3.x.x
    • Dependencies: Spring Web, Spring Security
  3. Click Generate, and extract the downloaded ZIP file.

Import into IDE

  • Open your IDE (e.g., IntelliJ or Eclipse).
  • Import the extracted project as a Maven project.

Step 2: Configuring Basic Authentication

Spring Boot makes it simple to enable basic authentication with properties.

Add Basic Authentication in application.properties

spring.security.user.name=admin
spring.security.user.password=admin123

Create a REST Controller

package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SecurityController {
    @GetMapping("/public")
    public String publicEndpoint() {
        return "This is a public endpoint";
    }
    @GetMapping("/secured")
    public String securedEndpoint() {
        return "This is a secured endpoint";
    }
}

When accessing /secured, the browser will prompt for the username and password configured in application.properties.


Step 3: Role-Based Access Control

Configure Custom Roles

Add the following in SecurityConfig:

package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public").permitAll()
                .requestMatchers("/secured").hasRole("USER")
                .anyRequest().authenticated()
            )
            .httpBasic();
        return http.build();
    }
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("user123")
            .roles("USER")
            .build();
        UserDetails admin = User.withDefaultPasswordEncoder()
            .username("admin")
            .password("admin123")
            .roles("ADMIN")
            .build();
        return new InMemoryUserDetailsManager(user, admin);
    }
}

Test Role-Based Access

  • /public: Accessible by anyone.
  • /secured: Accessible only by users with the USER role.

Step 4: Securing REST APIs with JWT

Add Dependencies

Include the following in pom.xml:

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.11.5</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.11.5</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>0.11.5</version>
</dependency>

Create a JWT Utility Class

package com.example.demo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class JwtUtil {
    private static final String SECRET_KEY = "mysecretkey";
    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }
    public String validateToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }
}

Add a Login Endpoint

package com.example.demo;
import org.springframework.web.bind.annotation.*;
@RestController
public class JwtController {
    private final JwtUtil jwtUtil = new JwtUtil();
    @PostMapping("/login")
    public String login(@RequestParam String username) {
        return jwtUtil.generateToken(username);
    }
}


Step 5: Advanced Security with OAuth2

Add OAuth2 Dependency

Include the following in pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

Configure OAuth2 Login

Add the following in application.properties:

spring.security.oauth2.client.registration.google.client-id=<your-client-id>
spring.security.oauth2.client.registration.google.client-secret=<your-client-secret>
spring.security.oauth2.client.registration.google.scope=profile,email
spring.security.oauth2.client.registration.google.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}


Conclusion

In this guide, we:

  1. Configured basic authentication with Spring Boot.
  2. Implemented role-based access control.
  3. Secured REST APIs using JWT.
  4. Explored advanced security with OAuth2.

5 comments

  1. Undeniably believe that which you said. Your favorite justification seemed to be on the net the easiest thing to be aware of. I say to you, I certainly get annoyed while people consider worries that they plainly don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people could take a signal. Will likely be back to get more. Thanks

  2. This is very interesting, You’re a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your fantastic post. Also, I’ve shared your web site in my social networks!

  3. Hello are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you require any html coding expertise to make your own blog? Any help would be really appreciated!

  4. Another issue is that video games are usually serious naturally with the main focus on knowing things rather than leisure. Although, we have an entertainment element to keep the kids engaged, just about every game is usually designed to develop a specific skill set or programs, such as math concepts or science. Thanks for your post.

  5. Do you mind if I quote a few of your posts as long as I provide credit and sources back to your weblog? My blog is in the exact same area of interest as yours and my users would truly benefit from some of the information you provide here. Please let me know if this ok with you. Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *