Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jwt implementation #35

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open

jwt implementation #35

wants to merge 5 commits into from

Conversation

indraniBan
Copy link
Contributor

@indraniBan indraniBan commented Dec 14, 2024

πŸ“‹ Description

JIRA ID:

Please provide a summary of the change and the motivation behind it. Include relevant context and details.


βœ… Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • πŸ”₯ Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • πŸ›  Refactor (change that is neither a fix nor a new feature)
  • βš™οΈ Config change (configuration file or build script updates)
  • πŸ“š Documentation (updates to docs or readme)
  • πŸ§ͺ Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • πŸš€ Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.

Summary by CodeRabbit

  • New Features

    • Added support for JSON Web Tokens (JWT) with new dependencies for JWT handling.
    • Introduced a utility class for cookie operations to enhance cookie management.
    • Implemented JWT authentication utility to validate tokens and manage user IDs.
    • Added a servlet filter for JWT user ID validation on incoming requests.
  • Configuration Changes

    • New configuration entries for JWT secret management added across multiple properties files.
  • Bug Fixes

    • Improved error handling and logging during JWT validation processes.

Copy link
Contributor

coderabbitai bot commented Dec 14, 2024

Warning

Rate limit exceeded

@indraniBan has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 45 seconds before requesting another review.

βŒ› How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between fa0c5c9 and ccb4c30.

πŸ“’ Files selected for processing (4)
  • src/main/java/com/iemr/helpline104/App.java (3 hunks)
  • src/main/java/com/iemr/helpline104/config/RedisConfig.java (1 hunks)
  • src/main/java/com/iemr/helpline104/data/users/M_User.java (2 hunks)
  • src/main/java/com/iemr/helpline104/utils/JwtAuthenticationUtil.java (1 hunks)

Walkthrough

This pull request introduces a comprehensive JWT (JSON Web Token) authentication mechanism for the Helpline 104 application. The changes include adding JWT dependencies to the project, configuring JWT secret keys across different environments, and implementing utility classes for token generation, validation, and cookie management. The modifications enhance the application's security by providing a structured approach to user authentication and token handling.

Changes

File Change Summary
pom.xml Added JWT dependencies: jjwt-api, jjwt-impl, and jjwt-jackson
src/main/environment/*.properties Added jwt.secret configuration across CI, dev, example, test, and UAT environments
src/main/java/com/iemr/helpline104/repository/users/IEMRUserRepositoryCustom.java Added getUserByUserID(Long userID) method
src/main/java/com/iemr/helpline104/utils/ Added new utility classes:
- CookieUtil.java: Cookie handling methods
- FilterConfig.java: JWT filter registration
- JwtAuthenticationUtil.java: JWT authentication validation
- JwtUserIdValidationFilter.java: JWT token and user ID validation filter
- JwtUtil.java: JWT token generation and validation utilities

Sequence Diagram

sequenceDiagram
    participant Client
    participant JwtUserIdValidationFilter
    participant JwtAuthenticationUtil
    participant JwtUtil
    participant UserRepository

    Client->>JwtUserIdValidationFilter: HTTP Request
    JwtUserIdValidationFilter->>JwtAuthenticationUtil: Validate JWT Token
    JwtAuthenticationUtil->>JwtUtil: Extract and Validate Token
    JwtUtil-->>JwtAuthenticationUtil: Token Claims
    JwtAuthenticationUtil->>UserRepository: Find User by ID
    UserRepository-->>JwtAuthenticationUtil: User Details
    JwtAuthenticationUtil-->>JwtUserIdValidationFilter: Validation Result
    JwtUserIdValidationFilter-->>Client: Authorized/Unauthorized Response
Loading

Poem

🐰 A Rabbit's JWT Ballad πŸ”

In the realm of tokens and keys so bright,
JWT dances with security's might.
Cookies crumble, filters stand tall,
Authentication answers the call!

Hop hop hooray for safe API! πŸš€


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❀️ Share
πŸͺ§ Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 13

🧹 Outside diff range and nitpick comments (8)
src/main/java/com/iemr/helpline104/utils/JwtAuthenticationUtil.java (1)

80-83: Avoid Catching General Exception; Catch Specific Exceptions

Catching the general Exception can obscure unexpected errors and make debugging difficult. It's better to catch specific exceptions that might be thrown during token validation, such as IEMRException, JwtException, or NumberFormatException.

Apply this diff to catch specific exceptions:

-    } catch (Exception e) {
+    } catch (JwtException | NumberFormatException | IEMRException e) {
         logger.error("Validation failed: " + e.getMessage(), e);
         throw new IEMRException("Validation error: " + e.getMessage(), e);
     }
src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java (1)

87-90: Avoid Catching General Exception; Catch Specific Exceptions

Similar to best practices in other parts of the code, catching the general Exception can make debugging harder and hide issues. It's advisable to catch specific exceptions that are expected during the filtering process.

Apply this diff to catch specific exceptions:

-    } catch (Exception e) {
+    } catch (IEMRException e) {
         logger.error("Authorization error: ", e);
         response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization error: " + e.getMessage());
     }

You might also consider handling other specific exceptions that could arise during JWT processing.

src/main/environment/104_example.properties (1)

19-19: Provide Guidance for Setting jwt.secret

The jwt.secret property is currently empty. To ensure proper configuration and security, consider adding a placeholder or instructions to guide users in setting a strong secret key.

Apply this diff to add guidance:

 jwt.secret=
+ # Please set a strong secret key for JWT signing, e.g., a long random string
+ jwt.secret=your_jwt_secret_key_here
src/main/environment/104_test.properties (2)

Line range hint 20-35: Remove unnecessary empty lines

The file contains multiple empty lines at the end which affects maintainability.

Remove the trailing empty lines to improve file consistency.


20-22: Implement comprehensive JWT security strategy

The current JWT configuration across environments needs a more structured approach:

  1. Secret Management:

    • Use a secure secret management service (e.g., HashiCorp Vault, AWS Secrets Manager)
    • Implement automatic secret rotation
    • Define minimum security requirements for secrets
  2. Configuration:

    • Standardize JWT configuration across environments
    • Add validation for token expiration and signing algorithms
    • Configure proper CORS and cookie settings
  3. Documentation:

    • Document JWT implementation details
    • Provide setup guides for each environment
    • Include security best practices

Would you like assistance in implementing any of these recommendations?

src/main/java/com/iemr/helpline104/utils/FilterConfig.java (1)

1-19: Consider additional security measures for JWT implementation

To enhance the security of the JWT implementation, consider adding:

  1. Rate limiting to prevent brute force attacks
  2. Token revocation mechanism using Redis/database blacklist
  3. Refresh token implementation for better security
  4. Request logging for security audit

Example implementation for token revocation:

@Service
public class TokenBlacklistService {
    private final RedisTemplate<String, String> redisTemplate;
    
    public void blacklistToken(String jti) {
        redisTemplate.opsForValue().set("blacklist:" + jti, "", 24, TimeUnit.HOURS);
    }
    
    public boolean isBlacklisted(String jti) {
        return Boolean.TRUE.equals(redisTemplate.hasKey("blacklist:" + jti));
    }
}
src/main/java/com/iemr/helpline104/repository/users/IEMRUserRepositoryCustom.java (1)

62-62: Follow Java naming conventions for parameters

The parameter name UserID should be in camelCase as per Java conventions.

-M_User findByUserID(Long UserID);
+M_User findByUserID(Long userId);
pom.xml (1)

Line range hint 220-230: Align Jackson library versions

There's a potential version conflict between JWT's Jackson dependencies and the existing Jackson dependencies:

  • jackson-databind: 2.17.0-rc1
  • jackson-core: 2.17.0-rc1
  • jjwt-jackson: 0.12.6 (which might bring its own Jackson version)

Consider aligning all Jackson versions to avoid potential compatibility issues.

 <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
-    <version>2.17.0-rc1</version>
+    <version>2.15.3</version>
 </dependency>

 <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-core</artifactId>
-    <version>2.17.0-rc1</version>
+    <version>2.15.3</version>
 </dependency>

Also applies to: 232-251

πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 9fa9ba3 and d4b26da.

πŸ“’ Files selected for processing (12)
  • pom.xml (7 hunks)
  • src/main/environment/104_ci.properties (1 hunks)
  • src/main/environment/104_dev.properties (1 hunks)
  • src/main/environment/104_example.properties (1 hunks)
  • src/main/environment/104_test.properties (1 hunks)
  • src/main/environment/104_uat.properties (1 hunks)
  • src/main/java/com/iemr/helpline104/repository/users/IEMRUserRepositoryCustom.java (1 hunks)
  • src/main/java/com/iemr/helpline104/utils/CookieUtil.java (1 hunks)
  • src/main/java/com/iemr/helpline104/utils/FilterConfig.java (1 hunks)
  • src/main/java/com/iemr/helpline104/utils/JwtAuthenticationUtil.java (1 hunks)
  • src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java (1 hunks)
  • src/main/java/com/iemr/helpline104/utils/JwtUtil.java (1 hunks)
πŸ”‡ Additional comments (3)
src/main/java/com/iemr/helpline104/repository/users/IEMRUserRepositoryCustom.java (1)

62-62: Consider adding access control checks

Since this method provides direct user lookup capability and will be used in JWT validation, ensure proper access control checks are implemented in the service layer to prevent unauthorized user data access.

βœ… Verification successful

Let me search for more context about how this repository method is used and any potential security measures.


Let me check for JWT filter configurations and authentication setup to understand the security context better.


Access control is already implemented appropriately

The codebase shows proper security implementation:

  • The findByUserID method is used within JwtAuthenticationUtil for JWT token validation
  • A global JwtUserIdValidationFilter is configured to intercept all requests ("/*")
  • The filter performs JWT token validation and user existence checks before allowing access
  • Invalid tokens or non-existent users result in 401 Unauthorized responses
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for access control implementations in service layer
# Look for service classes that might use this repository method
rg -l "findByUserID.*UserID" --type java

Length of output: 124


Script:

#!/bin/bash
# Search for implementations and usages of findByUserID
rg -A 5 "findByUserID" --type java

# Look for security related annotations and checks
rg -A 3 "@(Secured|PreAuthorize|RolesAllowed|PostAuthorize)" --type java

# Search for JWT related security configurations
rg -A 5 "WebSecurityConfigurerAdapter|SecurityFilterChain|JwtAuthenticationFilter" --type java

Length of output: 1105


Script:

#!/bin/bash
# Look for JWT filter and security configurations
rg -A 10 "JwtAuthenticationUtil|SecurityConfig|WebSecurity|@Configuration.*security" --type java

# Check for authentication filter chains or interceptors
rg -A 5 "Filter|Interceptor|addFilterBefore|configure.*HttpSecurity" --type java

# Look for the M_User class to understand user model security
ast-grep --pattern 'class M_User {
  $$$
}'

Length of output: 17202

pom.xml (2)

232-251: LGTM on JWT dependencies configuration!

The JWT dependencies are correctly configured with appropriate scopes and using the latest stable version.


Line range hint 195-204: Verify Redis session compatibility with JWT implementation

The presence of both Redis session management and JWT authentication might lead to redundant session handling. Ensure that the implementation clearly defines which mechanism is responsible for session management.

βœ… Verification successful

Let me check the implementation details to understand how Redis and JWT are being used together.


Let me check the application properties to understand how Redis and JWT are configured.


Based on the analysis of the codebase, I can now provide a final response:

Redis and JWT serve different purposes in the application - no conflict detected

Redis is being used for server-side session storage (configured via spring.session.store-type=redis) while JWT is used for authentication. The implementation shows:

  • Redis handles session data storage through RedisStorage class
  • JWT handles authentication tokens via JwtUtil and JwtAuthenticationUtil
  • No redundant session handling as they serve complementary purposes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential session handling conflicts
# Look for session configuration files and JWT configuration
rg -l "session|jwt" --type java

Length of output: 1291


Script:

#!/bin/bash
# Check Redis configuration and usage
rg -A 10 "RedisStorage|@EnableRedisHttpSession" --type java

# Check JWT implementation
rg -A 10 "class JwtUtil|class JwtAuthenticationUtil" --type java

# Check session object usage
rg -A 10 "class SessionObject" --type java

Length of output: 16768


Script:

#!/bin/bash
# Check application properties for Redis and JWT configuration
rg -A 5 "redis|jwt|session" src/main/resources/application.properties src/main/environment/104_*.properties

# Check if there's any Redis session configuration class
ast-grep --pattern 'class $_ implements $_ { $$$ @EnableRedisHttpSession $$$ }'

Length of output: 2372

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants