jav spring boot mastery

Security with Spring Boot (Basic Auth, JWT, OAuth2) [Java Spring Boot Mastery Series – Part 10]

Spring Security provides a robust authentication and authorization framework for securing Spring Boot applications.

1️⃣ Basic Authentication

Basic Auth is the simplest way to protect endpoints using HTTP headers.

✅ Dependencies

Already included in spring-boot-starter-security:

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

🔐 Security Configuration (Spring Boot 3+)

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeHttpRequests()
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            .and()
            .httpBasic();
        return http.build();
    }
}

🔍 Explanation:

  • permitAll() allows public access to specific endpoints.
  • httpBasic() enables Basic Auth.

2️⃣ JWT (JSON Web Tokens)

JWT is ideal for stateless, token-based authentication in REST APIs.

🔐 Filter-Based JWT Authentication Example

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = JwtUtil.extractUsername(jwt);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userService.loadUserByUsername(username);
                if (JwtUtil.validateToken(jwt, userDetails)) {
                    UsernamePasswordAuthenticationToken auth =
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}

🔑 JwtUtil Helper

Use io.jsonwebtoken or jjwt for token operations

public class JwtUtil {
    private static final String SECRET = "mysecretkey";

    public static String extractUsername(String token) {
        return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody().getSubject();
    }

    public static boolean validateToken(String token, UserDetails userDetails) {
        return extractUsername(token).equals(userDetails.getUsername());
    }
}

3️⃣ OAuth2 (Google Login Example)

✅ Add Dependency

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

⚙️ application.yml Example:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: your-google-client-id
            client-secret: your-google-secret
            redirect-uri: "{baseUrl}/login/oauth2/code/google"
            scope:
              - profile
              - email
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/v2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo

🌐 Auto Login URL:

http://localhost:8080/oauth2/authorization/google

🧪 Test Endpoint with Role Restriction

@RestController
@RequestMapping("/secure")
public class SecureController {

    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public String adminAccess() {
        return "Welcome Admin";
    }

    @GetMapping("/user")
    @PreAuthorize("hasRole('USER')")
    public String userAccess() {
        return "Welcome User";
    }
}

➡️ Next Up: Part 11 – Logging and Monitoring in Spring Boot

Similar Posts