๐Ÿ” Securing Your Spring Boot Application: JWT, OAuth 1.0, OAuth 2.0, and OpenID Connect Explained with Code

๐Ÿ“˜ Table of Contents

Why Authentication Matters
JWT (JSON Web Token)
OAuth 1.0
OAuth 2.0
OpenID Connect
When to Use What?
Final Thoughts

โœ… Why Authentication Matters

Modern web applications often expose APIs that must be prot…


This content originally appeared on DEV Community and was authored by Dev Cookies

๐Ÿ“˜ Table of Contents

  1. Why Authentication Matters
  2. JWT (JSON Web Token)
  3. OAuth 1.0
  4. OAuth 2.0
  5. OpenID Connect
  6. When to Use What?
  7. Final Thoughts

โœ… Why Authentication Matters

Modern web applications often expose APIs that must be protected from unauthorized access. Whether itโ€™s login, social login, or federated identity, understanding these mechanisms is crucial for building secure apps.

๐Ÿ” JWT (JSON Web Token)

๐Ÿ’ก What is JWT?

JWT is a stateless token format where the server issues a token (usually after login) and the client sends it in each request's header.

๐Ÿงฐ Dependencies (Maven)

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

๐Ÿ”ง JWT Utility Class

@Component
public class JwtUtil {
    private final String SECRET = "secret_key";

    public String generateToken(String username) {
        return Jwts.builder()
            .setSubject(username)
            .setIssuedAt(new Date())
            .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 1 day
            .signWith(SignatureAlgorithm.HS256, SECRET)
            .compact();
    }

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

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

๐Ÿ” JWT Request Filter

public class JwtRequestFilter extends OncePerRequestFilter {
    @Autowired private JwtUtil jwtUtil;
    @Autowired private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        final String authHeader = request.getHeader("Authorization");

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String jwt = authHeader.substring(7);
            String username = jwtUtil.extractUsername(jwt);

            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                if (jwtUtil.validateToken(jwt, userDetails)) {
                    UsernamePasswordAuthenticationToken authToken =
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authToken);
                }
            }
        }
        chain.doFilter(request, response);
    }
}

๐Ÿ” Security Configuration

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired private JwtRequestFilter jwtRequestFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests().antMatchers("/auth/**").permitAll()
            .anyRequest().authenticated();

        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

๐Ÿ” OAuth 1.0

๐Ÿ“Œ What is OAuth 1.0?

OAuth 1.0 is a legacy authentication mechanism where the client signs each request. Still used by Twitter and a few legacy APIs.

โœ… Using ScribeJava for OAuth 1.0

๐Ÿ“ฆ Dependency

<dependency>
    <groupId>com.github.scribejava</groupId>
    <artifactId>scribejava-apis</artifactId>
    <version>8.3.1</version>
</dependency>

๐Ÿ”„ Code Example

OAuth10aService service = new ServiceBuilder("your_consumer_key")
    .apiSecret("your_consumer_secret")
    .callback("http://localhost:8080/callback")
    .build(TwitterApi.instance());

OAuth1RequestToken requestToken = service.getRequestToken();
System.out.println("Authorize at: " + service.getAuthorizationUrl(requestToken));

Scanner scanner = new Scanner(System.in);
System.out.print("Enter the PIN: ");
String oauthVerifier = scanner.nextLine();

OAuth1AccessToken accessToken = service.getAccessToken(requestToken, oauthVerifier);
System.out.println("Access Token: " + accessToken.getToken());

๐Ÿ” OAuth 2.0

๐Ÿ“Œ What is OAuth 2.0?

OAuth 2.0 is a widely used authorization framework that allows third-party apps to access a user's resources without exposing credentials.

๐Ÿงฐ Dependencies

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

โš™๏ธ application.yml

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: your-client-id
            client-secret: your-client-secret
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            scope: profile, email

๐Ÿ”’ Security Config

@Configuration
@EnableWebSecurity
public class OAuth2LoginSecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests(authz -> authz
                .anyRequest().authenticated())
            .oauth2Login();
        return http.build();
    }
}

๐Ÿ” OpenID Connect

๐Ÿ“Œ What is OpenID Connect?

OIDC is built on top of OAuth 2.0 and adds an identity layer. Itโ€™s used for login and identity verification.

If you want login + profile info from Google, OIDC is the way.

โœ… Configuration (Same as OAuth 2.0)

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            scope: openid, profile, email

๐Ÿง‘โ€๐Ÿ’ผ Accessing User Info

@Controller
public class UserController {
    @GetMapping("/user")
    @ResponseBody
    public Map<String, Object> user(@AuthenticationPrincipal OidcUser principal) {
        return Map.of(
            "email", principal.getEmail(),
            "name", principal.getFullName()
        );
    }
}

โš–๏ธ When to Use What?

Use Case Recommended Approach
Stateless APIs JWT
Social Login OAuth 2.0
Federated Identity OpenID Connect
Legacy APIs (e.g. Twitter) OAuth 1.0

๐Ÿ’ฌ Final Thoughts

Securing your application is not optional. The choice between JWT, OAuth, and OpenID depends on your specific needsโ€”whether itโ€™s identity, access, or both.

๐Ÿ“Œ Pro Tip: Always validate and expire tokens properly. Never expose client secrets or tokens in frontend code.


This content originally appeared on DEV Community and was authored by Dev Cookies


Print Share Comment Cite Upload Translate Updates
APA

Dev Cookies | Sciencx (2025-04-05T08:53:15+00:00) ๐Ÿ” Securing Your Spring Boot Application: JWT, OAuth 1.0, OAuth 2.0, and OpenID Connect Explained with Code. Retrieved from https://www.scien.cx/2025/04/05/%f0%9f%94%90-securing-your-spring-boot-application-jwt-oauth-1-0-oauth-2-0-and-openid-connect-explained-with-code/

MLA
" » ๐Ÿ” Securing Your Spring Boot Application: JWT, OAuth 1.0, OAuth 2.0, and OpenID Connect Explained with Code." Dev Cookies | Sciencx - Saturday April 5, 2025, https://www.scien.cx/2025/04/05/%f0%9f%94%90-securing-your-spring-boot-application-jwt-oauth-1-0-oauth-2-0-and-openid-connect-explained-with-code/
HARVARD
Dev Cookies | Sciencx Saturday April 5, 2025 » ๐Ÿ” Securing Your Spring Boot Application: JWT, OAuth 1.0, OAuth 2.0, and OpenID Connect Explained with Code., viewed ,<https://www.scien.cx/2025/04/05/%f0%9f%94%90-securing-your-spring-boot-application-jwt-oauth-1-0-oauth-2-0-and-openid-connect-explained-with-code/>
VANCOUVER
Dev Cookies | Sciencx - » ๐Ÿ” Securing Your Spring Boot Application: JWT, OAuth 1.0, OAuth 2.0, and OpenID Connect Explained with Code. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/04/05/%f0%9f%94%90-securing-your-spring-boot-application-jwt-oauth-1-0-oauth-2-0-and-openid-connect-explained-with-code/
CHICAGO
" » ๐Ÿ” Securing Your Spring Boot Application: JWT, OAuth 1.0, OAuth 2.0, and OpenID Connect Explained with Code." Dev Cookies | Sciencx - Accessed . https://www.scien.cx/2025/04/05/%f0%9f%94%90-securing-your-spring-boot-application-jwt-oauth-1-0-oauth-2-0-and-openid-connect-explained-with-code/
IEEE
" » ๐Ÿ” Securing Your Spring Boot Application: JWT, OAuth 1.0, OAuth 2.0, and OpenID Connect Explained with Code." Dev Cookies | Sciencx [Online]. Available: https://www.scien.cx/2025/04/05/%f0%9f%94%90-securing-your-spring-boot-application-jwt-oauth-1-0-oauth-2-0-and-openid-connect-explained-with-code/. [Accessed: ]
rf:citation
» ๐Ÿ” Securing Your Spring Boot Application: JWT, OAuth 1.0, OAuth 2.0, and OpenID Connect Explained with Code | Dev Cookies | Sciencx | https://www.scien.cx/2025/04/05/%f0%9f%94%90-securing-your-spring-boot-application-jwt-oauth-1-0-oauth-2-0-and-openid-connect-explained-with-code/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.