Skip to content

Add OAuth2 Resource Server with JWT and Docker support #1

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

Merged

Conversation

maxiplux
Copy link
Owner

@maxiplux maxiplux commented Apr 7, 2025

Description

This pull request introduces OAuth2-based security for a Spring Boot application, with JWT validation capabilities. Key additions include:

  • Configuration of a resource server and security filter chain.
  • Detailed exception handling with problem detail responses.
  • Swagger API documentation for enhanced usability.
  • Docker support with multi-stage builds and docker-compose for deployment.

These changes enhance security, improve developer productivity, and simplify deployment workflows

Introduced OAuth2-based security with JWT validation in a Spring Boot app, including comprehensive exception handling and Swagger API docs. Added Docker support with multi-stage builds and docker-compose for deployment. Configured a resource server, implemented a security filter chain, and provided detailed problem detail responses.
@maxiplux maxiplux self-assigned this Apr 7, 2025
@maxiplux maxiplux added the enhancement New feature or request label Apr 7, 2025
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Hello @maxiplux, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

Summary of Changes

This pull request introduces OAuth2-based security for a Spring Boot application, utilizing JWT for authentication and Docker for deployment. I've added configurations for a resource server, security filter chain, and exception handling, along with Swagger API documentation and Docker support with multi-stage builds.

Highlights

  • OAuth2 Resource Server Configuration: Configured a Spring Security OAuth2 resource server with JWT validation, securing API endpoints and allowing public access to Swagger UI.
  • Comprehensive Exception Handling: Implemented detailed exception handling for OAuth2 and JWT related issues, returning standardized Problem Detail responses as per RFC 7807.
  • Docker Support: Added a multi-stage Dockerfile for efficient container builds and a docker-compose configuration for running the application with an authorization server.

Changelog

Click here to see the changelog
  • .dockerignore
    • Added common IDE and build artifacts to the .dockerignore file to reduce the size of the Docker image.
  • Dockerfile
    • Created a multi-stage Dockerfile to build and package the Spring Boot application.
    • The first stage uses Gradle to build the application, and the second stage creates a runtime image with OpenJDK 17.
  • README.md
    • Created a comprehensive README file explaining the project overview, technical stack, component architecture, key implementation details, authentication flow, security best practices, and instructions for running the application.
  • build.gradle
    • Added dependencies for Spring Security, OAuth2 Resource Server, and SpringDoc OpenAPI for API documentation.
    • Updated the dependencies block to include the necessary libraries for OAuth2 and JWT support, as well as API documentation generation.
  • docker-compose.yml
    • Created a docker-compose file to orchestrate the application and an authorization server.
    • The docker-compose file defines two services: api and auth-server, and sets up a network for them to communicate.
  • src/main/java/app/quantun/simpleapi/config/SecurityConfig.java
    • Configured the security filter chain to secure API endpoints using JWT validation.
    • The configuration allows public access to Swagger UI and requires authentication for all /api/** endpoints.
  • src/main/java/app/quantun/simpleapi/controller/HomeController.java
    • Added a basic HomeController with API endpoints for testing the security configuration.
    • The controller includes GET, POST, and PUT endpoints under the /api/home path, all secured by the OAuth2 configuration.
  • src/main/java/app/quantun/simpleapi/exeption/SecurityExceptionHandler.java
    • Implemented a global exception handler for OAuth2 and JWT related exceptions, returning ProblemDetail responses.
    • The handler covers InvalidBearerTokenException, AuthenticationException, JwtValidationException, JwtException, and AccessDeniedException.
  • src/main/resources/application.properties
    • Configured the application properties, including the JWT issuer URI, server port, and timeouts.
    • The properties also enable Problem Details for error responses and configure logging for OAuth2.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.


A token's flight,
Secured with JWT's might,
Guards API's gate.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces OAuth2-based security with JWT validation, Swagger API documentation, and Docker support to a Spring Boot application. The changes look good overall, but there are a few areas that could be improved for better security and maintainability.

Summary of Findings

  • Exception Handling Specificity: The SecurityExceptionHandler provides comprehensive exception handling, but some exception handlers could benefit from more specific error categorization and messages to aid in debugging and provide more informative responses to clients.
  • Docker Compose Environment Variables: The docker-compose.yml file uses environment variables to set the active Spring profile. It would be beneficial to externalize other configuration parameters, such as port numbers or JWT issuer URIs, to allow for easier customization without rebuilding the Docker images.
  • README.md Updates: The README.md file contains a code snippet for SecurityConfig.java that does not match the current implementation. It should be updated to reflect the changes made in this pull request.

Merge Readiness

The pull request is almost ready for merging. Addressing the comments regarding exception handling specificity and updating the README.md file will improve the overall quality and maintainability of the code. I am unable to directly approve this pull request, and recommend that others review and approve this code before merging. At a minimum, the high severity issues should be addressed before merging.

Comment on lines +45 to +55
.authorizeHttpRequests(requests -> requests
// Public endpoints for API documentation
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
// Secure all API endpoints
.requestMatchers("/api/**").authenticated()
.anyRequest().permitAll()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt());
return http.build();
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The code snippet for SecurityConfig.java in the README is outdated. It should be updated to reflect the current implementation, including the handling of Swagger UI paths and the authenticationEntryPoint.

@Configuration
@EnableWebSecurity
public class SecurityConfig  {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(requests -> requests
                        // Swagger UI paths
                        .requestMatchers("/swagger-ui/**",
                                "/v3/api-docs/**",
                                "/swagger-ui.html",
                                "/webjars/**")
                        .permitAll()
                        // Secure your API endpoints as needed
                        .requestMatchers("/api/**").authenticated()
                        // Other endpoints
                        .anyRequest().permitAll()
                )
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(jwt -> {
                        }).authenticationEntryPoint(
                                (request, response, authException) -> {
                                    // Handle authentication entry point

                                    String message = authException.getMessage() != null ?
                                            authException.getMessage() :
                                            "Authentication failed: Invalid credentials";
                                    response.sendError(401, message);
                                }
                        )
                );
        return http.build();
    }


}

Comment on lines +11 to +12
environment:
- SPRING_PROFILES_ACTIVE=docker
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Consider externalizing the port numbers and JWT issuer URI as environment variables in docker-compose.yml. This allows for easier customization without needing to rebuild the Docker images. For example, you could define API_PORT and AUTH_SERVER_PORT and use them in the ports section.

    ports:
      - "${API_PORT:-8080}:8080"
    environment:
      - SPRING_PROFILES_ACTIVE=docker
      - SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_ISSUER_URI=${JWT_ISSUER_URI:-http://localhost:9000}

@maxiplux maxiplux requested a review from Copilot April 7, 2025 00:31

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
ok

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot reviewed 6 out of 9 changed files in this pull request and generated 1 comment.

Files not reviewed (3)
  • .dockerignore: Language not supported
  • Dockerfile: Language not supported
  • src/main/resources/application.properties: Language not supported
Comments suppressed due to low confidence (1)

src/main/java/app/quantun/simpleapi/exeption/SecurityExceptionHandler.java:1

  • The package name 'exeption' appears to be misspelled. Consider renaming it to 'exception' to maintain clarity and consistency.
package app.quantun.simpleapi.exeption;

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
Co-authored-by: Copilot <[email protected]>
@maxiplux maxiplux merged commit 7ad0471 into master Apr 7, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant