0% found this document useful (0 votes)
29 views11 pages

JWT & OAuth

This document provides a comprehensive guide on JWT (JSON Web Token) and OAuth 2.0 authentication, detailing their structures, flows, and implementation steps. It explains the JWT structure, authentication flow, and contrasts it with OAuth 2.0's authorization process, including various grant types and security measures. Additionally, it includes practical implementation steps for both JWT and OAuth 2.0 in a Spring Boot application.

Uploaded by

ankitagorde4386
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views11 pages

JWT & OAuth

This document provides a comprehensive guide on JWT (JSON Web Token) and OAuth 2.0 authentication, detailing their structures, flows, and implementation steps. It explains the JWT structure, authentication flow, and contrasts it with OAuth 2.0's authorization process, including various grant types and security measures. Additionally, it includes practical implementation steps for both JWT and OAuth 2.0 in a Spring Boot application.

Uploaded by

ankitagorde4386
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Step-by-Step Explanation of JWT and OAuth 2.

0 Authentication

1. Introduction

 JWT (JSON Web Token): A token format used to securely transmit


information between parties as a JSON object. It is compact, self-
contained, and can be signed and optionally encrypted.

 OAuth 2.0: An open-standard framework for authorization. It allows


third-party applications to access resources without exposing user
credentials.

JWT Authentication

Step 1: Understanding JWT Structure

A JWT has three parts, separated by dots (.):

1. Header: Contains the type of token (JWT) and the hashing algorithm
(e.g., HS256 or RS256).

2. { "alg": "HS256", "typ": "JWT" }

3. Payload: Contains the claims (data about the user or token).

4. { "sub": "1234567890", "name": "John Doe", "admin": true }

5. Signature: Ensures the token has not been tampered with. It is


generated by encoding the header and payload and signing it with a
secret key.

6. HMACSHA256(base64UrlEncode(header) + "." +
base64UrlEncode(payload), secret)

A full JWT looks like:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmF
tZSI6IkpvaG4gRG9lIiw

iYWRtaW4iOnRydWV9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Step 2: Authentication Flow with JWT

1. User Login:

o The user sends their credentials (e.g., username and


password) to the authentication server.

2. Token Issuance:
o If credentials are valid, the server creates a JWT containing
user claims (e.g., user ID, roles) and signs it with a secret key.

o The JWT is returned to the client.

3. Token Storage:

o The client stores the JWT securely, typically in:

 Local Storage: Easy to access, but vulnerable to XSS


attacks.

 HTTP-only Cookies: More secure as it prevents XSS


attacks.

4. Authenticated Requests:

o The client includes the JWT in the Authorization header of


HTTP requests:

o Authorization: Bearer <JWT>

5. Server Validation:

o The server verifies the JWT by:

 Decoding it.

 Validating the signature using the secret key.

 Checking claims (e.g., expiration, issuer).

o If valid, the server processes the request.

6. Token Expiry:

o JWTs often include an expiration time (exp claim).

o Once expired, the user must reauthenticate or obtain a new


token using a refresh mechanism.

OAuth 2.0 Authentication

Step 1: Key Concepts

 Resource Owner: The user granting access to their data.

 Client: The application requesting access to the user's data.

 Authorization Server: Issues access tokens after user consent.

 Resource Server: The API or service holding the protected data.


Step 2: OAuth 2.0 Grant Types

OAuth defines different "flows" or grant types depending on use cases:

1. Authorization Code Grant (Most Secure)

1. User Authentication:

o The client redirects the user to the authorization server's login


page.

2. Authorization Code:

o After login, the server redirects back to the client with an


authorization code.

3. Exchange Code for Token:

o The client sends the authorization code to the authorization


server.

o The server verifies the code and returns an access token


(and optionally a refresh token).

4. Resource Access:

o The client includes the access token in the Authorization


header when making API requests.

2. Client Credentials Grant

 Used for server-to-server communication (no user involvement).

 The client directly sends its credentials to the authorization server to


obtain an access token.

3. Password Grant (Deprecated)

 The client collects the user's username and password and sends
them to the authorization server to get a token.

 Risky: Not recommended as it exposes user credentials.

4. Implicit Grant (Deprecated)

 The access token is issued directly to the client (typically a browser)


without a backend server.

Step 3: OAuth 2.0 Authentication Flow

With Authorization Code Grant:

1. Authorization Request:
o The client redirects the user to the authorization server:

o GET /authorize?
response_type=code&client_id=CLIENT_ID&redirect_uri=CALL
BACK_URL&scope=read

o Parameters:

 response_type: Indicates the expected response (e.g.,


code).

 client_id: The client application's identifier.

 redirect_uri: Where to send the user after login.

 scope: Permissions being requested.

2. User Consent:

o The user logs in and grants permission.

3. Authorization Code:

o The authorization server redirects back to the client with an


authorization code:

o https://client.com/callback?code=AUTH_CODE

4. Exchange Code for Token:

o The client sends the authorization code and client secret to


the authorization server:

o POST /token

o Content-Type: application/x-www-form-urlencoded

o client_id=CLIENT_ID&client_secret=CLIENT_SECRET&code=AU
TH_CODE&grant_type=authorization_code

o The server responds with an access token (and optionally a


refresh token).

5. Access Resources:

o The client uses the token to access the resource server:

o Authorization: Bearer <ACCESS_TOKEN>

6. Token Expiry and Refresh:

o If the access token expires, the client uses the refresh token to
obtain a new access token without requiring user interaction:
o POST /token

o Content-Type: application/x-www-form-urlencoded

o client_id=CLIENT_ID&client_secret=CLIENT_SECRET&refresh_t
oken=REFRESH_TOKEN&grant_type=refresh_token

Comparison of JWT and OAuth 2.0

Feature JWT OAuth 2.0

Token format for Framework for secure


Purpose
authentication/authorization authorization

Access/Refresh tokens (not


Token Type Self-contained JWT
necessarily JWTs)

API authentication, user Delegated access for third-


Use Case
sessions party applications

Token Done on the server (no DB call Requires token introspection


Validation required) for validation

Relies on secure key Token revocation and


Security
management dynamic scopes available

Let me know if you need more clarity or examples!

Here’s a step-by-step guide to implementing JWT and OAuth 2.0


authentication.

1. JWT Implementation

Step 1: Setup Your Project

1. Initialize the Project:

o Use a build tool like Maven or Gradle for Java.

o Include dependencies:

o <!-- Maven Dependencies -->

o <dependency>

o <groupId>io.jsonwebtoken</groupId>

o <artifactId>jjwt</artifactId>
o <version>0.9.1</version>

o </dependency>

o <dependency>

o <groupId>org.springframework.boot</groupId>

o <artifactId>spring-boot-starter-security</artifactId>

o </dependency>

2. Basic Spring Boot Configuration:

o Create a Spring Boot project if not already done.

Step 2: Generate JWT

1. Write a Token Generation Utility:

2. import io.jsonwebtoken.Jwts;

3. import io.jsonwebtoken.SignatureAlgorithm;

4.

5. import java.util.Date;

6.

7. public class JwtUtil {

8. private static final String SECRET_KEY = "your-secret-key";

9.

10. public static String generateToken(String username) {

11. return Jwts.builder()

12. .setSubject(username)

13. .setIssuedAt(new Date())

14. .setExpiration(new Date(System.currentTimeMillis() +


1000 * 60 * 60)) // 1 hour

15. .signWith(SignatureAlgorithm.HS256, SECRET_KEY)

16. .compact();

17. }

18. }
19. Use the Utility in Your Controller:

20. @RestController

21. public class AuthController {

22. @PostMapping("/login")

23. public ResponseEntity<String> login(@RequestBody


AuthRequest request) {

24. // Replace with actual authentication logic

25. if ("user".equals(request.getUsername()) &&


"password".equals(request.getPassword())) {

26. String token =


JwtUtil.generateToken(request.getUsername());

27. return ResponseEntity.ok(token);

28. }

29. return
ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();

30. }

31. }

32.

33. class AuthRequest {

34. private String username;

35. private String password;

36. // Getters and Setters

37. }

Step 3: Validate JWT

1. Write a Validation Utility:

2. import io.jsonwebtoken.Claims;

3. import io.jsonwebtoken.Jwts;

4.

5. public class JwtUtil {


6. // Existing methods...

7.

8. public static Claims validateToken(String token) {

9. return Jwts.parser()

10. .setSigningKey(SECRET_KEY)

11. .parseClaimsJws(token)

12. .getBody();

13. }

14. }

15. Add a Filter to Validate Tokens:

16. import javax.servlet.FilterChain;

17. import javax.servlet.ServletException;

18. import javax.servlet.http.HttpServletRequest;

19. import javax.servlet.http.HttpServletResponse;

20.

21. import io.jsonwebtoken.Claims;

22. import org.springframework.web.filter.OncePerRequestFilter;

23.

24. import java.io.IOException;

25.

26. public class JwtFilter extends OncePerRequestFilter {

27. @Override

28. protected void doFilterInternal(HttpServletRequest request,


HttpServletResponse response, FilterChain chain)

29. throws ServletException, IOException {

30. String header = request.getHeader("Authorization");

31. if (header != null && header.startsWith("Bearer ")) {

32. String token = header.substring(7);

33. Claims claims = JwtUtil.validateToken(token);


34. if (claims == null) {

35.
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

36. return;

37. }

38. // Attach claims or user info to the security context if


needed

39. }

40. chain.doFilter(request, response);

41. }

42. }

43. Register the Filter:

44. @Configuration

45. public class SecurityConfig extends


WebSecurityConfigurerAdapter {

46. @Override

47. protected void configure(HttpSecurity http) throws


Exception {

48. http.addFilterBefore(new JwtFilter(),


UsernamePasswordAuthenticationFilter.class);

49. }

50. }

2. OAuth 2.0 Implementation

Step 1: Setup the Authorization Server

1. Include Dependencies:

2. <dependency>

3. <groupId>org.springframework.boot</groupId>

4.
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>

5. </dependency>
6. <dependency>

7. <groupId>org.springframework.boot</groupId>

8. <artifactId>spring-boot-starter-oauth2-client</artifactId>

9. </dependency>

10. Configure the Authorization Server:

o For this example, let’s use a pre-configured server like


Keycloak or Okta.

Step 2: Configure Spring Boot as a Resource Server

1. Application Properties:

2. spring.security.oauth2.resourceserver.jwt.issuer-uri=https://
issuer.example.com

3. Enable Resource Server:

4. @Configuration

5. public class SecurityConfig extends WebSecurityConfigurerAdapter {

6. @Override

7. protected void configure(HttpSecurity http) throws Exception {

8. http.authorizeRequests()

9. .antMatchers("/public/**").permitAll()

10. .anyRequest().authenticated()

11. .and()

12. .oauth2ResourceServer()

13. .jwt();

14. }

15. }

Step 3: Secure Endpoints with Scopes

1. Add Scope Validation:

2. import org.springframework.security.access.prepost.PreAuthorize;

3.
4. @RestController

5. public class ResourceController {

6. @GetMapping("/protected")

7. @PreAuthorize("hasAuthority('SCOPE_read')")

8. public String protectedEndpoint() {

9. return "Protected Data";

10. }

11. }

Step 4: Test OAuth Flow

1. Authorization Code Flow:

o Register your application with the authorization server.

o Use Postman or a similar tool to simulate login and token


exchange.

o Include the Authorization: Bearer <access_token> header in


API requests.

Summary Table for Implementation

Feature JWT OAuth 2.0

Server Generate and validate Use an authorization server like


Setup tokens manually Keycloak

Token
Client-side Managed by the client application
Storage

Validation Self-contained Delegated to the resource server

Requires careful secret More robust due to dynamic token


Security
management introspection

Let me know which step you’d like detailed further!

You might also like