-
Notifications
You must be signed in to change notification settings - Fork 10
Add new spring boot example to playground #129
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
base: main
Are you sure you want to change the base?
Conversation
WalkthroughA new Spring Boot example project, Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant SpringBootApp
participant SecurityConfig
participant OAuth2ResourceServer
participant GreetController
Client->>SpringBootApp: HTTP GET /greet/{name} with JWT
SpringBootApp->>SecurityConfig: Apply security filter (JWT validation)
SecurityConfig->>OAuth2ResourceServer: Validate JWT with Kinde issuer
OAuth2ResourceServer-->>SecurityConfig: JWT valid/invalid
SecurityConfig-->>SpringBootApp: Allow or deny request
SpringBootApp->>GreetController: Invoke greet(name) if authenticated
GreetController-->>SpringBootApp: Return {"data": "Hello {name}"}
SpringBootApp-->>Client: JSON response
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Suggested reviewers
Note 🔌 MCP (Model Context Protocol) integration is now available in Early Access!Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 7
🧹 Nitpick comments (7)
playground/kinde-springboot-jwt-example/.gitignore (1)
1-26: Looks good. Consider ignoring local env/IDE files as well.Optional: add common local-only files to avoid accidental commits.
Apply this diff at the end:
# --------------------------------------------------------------------- # Add specific rules here… + +# Local dev +.vscode/ +.env +*.env.localplayground/kinde-springboot-jwt-example/src/main/resources/application.properties (1)
1-1: Nit: align application name with project name.For consistency with the module name, consider:
-spring.application.name=kinde-springboot-servlet +spring.application.name=kinde-springboot-jwt-exampleplayground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/KindeSpringbootServletApplication.java (1)
1-13: Naming consistency nit: consider aligning class/package with project nameThe package/class include “kindespringbootservlet” while the project is “springboot-jwt-example.” Consider
com.kinde.springboot.jwtandKindeSpringBootJwtApplicationfor clarity.playground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/controller/GreetController.java (1)
11-16: Refine request mapping for readability and explicit JSON responseMove the path variable to the method mapping and (optionally) declare the media type.
-@RequestMapping("/greet/{name}") +@RequestMapping("/greet") public class GreetController { - @GetMapping - public Map<String, String> greet(@PathVariable String name) { + @GetMapping(path = "/{name}", produces = "application/json") + public Map<String, String> greet(@PathVariable String name) { return Map.of("data", "Hello " + name); } }playground/kinde-springboot-jwt-example/README.md (3)
10-12: Add language to fenced code block (markdownlint MD040)Annotate the properties block for better formatting and lint compliance.
-``` +```properties spring.security.oauth2.resourceserver.jwt.issuer-uri=https://<your-kinde-domain>.kinde.com--- `14-14`: **Fix example domain placeholder** Using `myapp.kinde` would render `https://myapp.kinde.kinde.com`. Example should be just the subdomain. ```diff -Replace `<your-kinde-domain>` with your actual Kinde domain (e.g., `myapp.kinde`). +Replace `<your-kinde-domain>` with your actual Kinde subdomain (e.g., `myapp`).
3-5: Grammar nit“A OAuth2 Provider” → “an OAuth2 provider.”
-with Spring Boot. Kinde is used as a OAuth2 Provider +with Spring Boot. Kinde is used as an OAuth2 provider
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
playground/kinde-springboot-jwt-example/pom.xmlis excluded by!**/*.xml
📒 Files selected for processing (11)
playground/README.md(1 hunks)playground/kinde-springboot-jwt-example/.gitignore(1 hunks)playground/kinde-springboot-jwt-example/README.md(1 hunks)playground/kinde-springboot-jwt-example/mvnw(1 hunks)playground/kinde-springboot-jwt-example/mvnw.cmd(1 hunks)playground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/KindeSpringbootServletApplication.java(1 hunks)playground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/config/SecurityConfig.java(1 hunks)playground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/config/WebConfig.java(1 hunks)playground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/controller/GreetController.java(1 hunks)playground/kinde-springboot-jwt-example/src/main/resources/application.properties(1 hunks)playground/kinde-springboot-jwt-example/src/test/java/com/kinde/springboot/kindespringbootservlet/KindeSpringbootServletApplicationTests.java(1 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: brettchaldecott
PR: kinde-oss/kinde-java-sdk#29
File: playground/kinde-management-example/.env:6-6
Timestamp: 2024-10-02T10:49:48.190Z
Learning: In the codebase, the `playground/kinde-management-example` project is separate, and changes in its `.env` file do not affect other projects. The removal of the `openid` scope from `KINDE_SCOPES` in this project is valid.
Learnt from: brettchaldecott
PR: kinde-oss/kinde-java-sdk#29
File: playground/kinde-management-example/.env:6-6
Timestamp: 2024-10-08T23:57:58.113Z
Learning: In the codebase, the `playground/kinde-management-example` project is separate, and changes in its `.env` file do not affect other projects. The removal of the `openid` scope from `KINDE_SCOPES` in this project is valid.
Learnt from: brettchaldecott
PR: kinde-oss/kinde-java-sdk#21
File: playground/kinde-core-example/src/test/java/com/kinde/AppTest.java:39-39
Timestamp: 2024-10-08T23:57:58.113Z
Learning: The `AppTest` class in the `playground/kinde-core-example` is intended for experimentation and not part of the main development process, justifying the use of the `Ignore` annotation.
Learnt from: brettchaldecott
PR: kinde-oss/kinde-java-sdk#21
File: playground/kinde-core-example/src/test/java/com/kinde/AppTest.java:39-39
Timestamp: 2024-08-19T07:08:02.362Z
Learning: The `AppTest` class in the `playground/kinde-core-example` is intended for experimentation and not part of the main development process, justifying the use of the `Ignore` annotation.
📚 Learning: 2024-10-02T10:49:48.190Z
Learnt from: brettchaldecott
PR: kinde-oss/kinde-java-sdk#29
File: playground/kinde-management-example/.env:6-6
Timestamp: 2024-10-02T10:49:48.190Z
Learning: In the codebase, the `playground/kinde-management-example` project is separate, and changes in its `.env` file do not affect other projects. The removal of the `openid` scope from `KINDE_SCOPES` in this project is valid.
Applied to files:
playground/kinde-springboot-jwt-example/src/main/resources/application.propertiesplayground/README.mdplayground/kinde-springboot-jwt-example/.gitignoreplayground/kinde-springboot-jwt-example/src/test/java/com/kinde/springboot/kindespringbootservlet/KindeSpringbootServletApplicationTests.javaplayground/kinde-springboot-jwt-example/README.md
📚 Learning: 2024-10-08T23:57:58.113Z
Learnt from: brettchaldecott
PR: kinde-oss/kinde-java-sdk#21
File: playground/kinde-core-example/src/test/java/com/kinde/AppTest.java:39-39
Timestamp: 2024-10-08T23:57:58.113Z
Learning: The `AppTest` class in the `playground/kinde-core-example` is intended for experimentation and not part of the main development process, justifying the use of the `Ignore` annotation.
Applied to files:
playground/kinde-springboot-jwt-example/src/main/resources/application.propertiesplayground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/KindeSpringbootServletApplication.javaplayground/README.mdplayground/kinde-springboot-jwt-example/.gitignoreplayground/kinde-springboot-jwt-example/src/test/java/com/kinde/springboot/kindespringbootservlet/KindeSpringbootServletApplicationTests.java
📚 Learning: 2024-10-08T23:57:58.113Z
Learnt from: brettchaldecott
PR: kinde-oss/kinde-java-sdk#29
File: kinde-management/src/main/java/com/kinde/admin/KindeAdminSessionImpl.java:38-39
Timestamp: 2024-10-08T23:57:58.113Z
Learning: In `KindeAdminSessionImpl.java`, it's safe to use `kindeClient.oidcMetaData().getOpMetadata().getTokenEndpointURI()` without additional null checks because it has already been used in a sub call.
Applied to files:
playground/kinde-springboot-jwt-example/src/main/resources/application.properties
🧬 Code Graph Analysis (2)
playground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/config/WebConfig.java (1)
playground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/config/SecurityConfig.java (1)
Configuration(10-23)
playground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/config/SecurityConfig.java (1)
playground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/config/WebConfig.java (1)
Configuration(7-13)
🪛 markdownlint-cli2 (0.17.2)
playground/kinde-springboot-jwt-example/README.md
10-10: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🔇 Additional comments (12)
playground/README.md (1)
17-17: LGTM — entry is correct and the link resolves relative to playground.playground/kinde-springboot-jwt-example/mvnw.cmd (1)
1-150: LGTM: standard Maven Wrapper scriptScript looks standard (v3.3.2), with checksum validation support and credentials handling.
playground/kinde-springboot-jwt-example/mvnw (10)
1-21: Standard Maven Wrapper script added — LGTMHeader, license, and shebang look correct for Maven Wrapper 3.3.2.
32-43: Enable strict mode — good choice for reliabilityset -euf and optional debugging are appropriate for robust CI usage.
44-79: Java detection and fallbacks look correctJAVA_HOME and PATH discovery, including AIX special cases and validation, are handled properly.
117-135: Wrapper distribution URL handling is correctPlatform selection and URL normalization follow upstream wrapper behavior.
136-148: Local cache location (MAVEN_HOME) and exec logic are soundHashing and per-URL cache dir avoid collisions; exec_maven unsets sensitive env vars — good.
155-159: Validating distributionUrl format — good guardrailRejecting non-bin archives is a useful safety check.
170-180: Graceful unzip/tar fallback is correctSwitching to .tar.gz when unzip is unavailable is standard and reliable.
249-257: Extraction and atomic move — OKUnpack to temp and mv to MAVEN_HOME with fallback check prevents partial installs.
1-260: Maven Wrapper duplication check: no root‐level wrapper found
Only the project‐specificmvnw/mvnw.cmdinplayground/kinde-springboot-jwt-exampleexists—no changes needed.
222-247: EnsuredistributionSha256Sumis committed for supply-chain integrityChecksum validation only runs when
distributionSha256Sumis set. Before merging, please:
- Verify that
.mvn/wrapper/maven-wrapper.propertiesexists inplayground/kinde-springboot-jwt-example.- Confirm it defines both
distributionUrland a matchingdistributionSha256Sum.- If the file or property is missing, generate (or regenerate) the Maven wrapper and compute the SHA-256 of the downloaded distribution (e.g. via
sha256sum) to add underdistributionSha256Sum.
| @@ -0,0 +1,259 @@ | |||
| #!/bin/sh | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Ensure the script is executable in git
The shebang is correct, but the exec bit must be set so CI and users can run ./mvnw.
Run:
🏁 Script executed:
#!/bin/bash
set -euo pipefail
git ls-files --stage playground/kinde-springboot-jwt-example/mvnw | awk '{print $1,$2,$3,$4}'
# Expect mode 100755. If not, set:
# git update-index --chmod=+x playground/kinde-springboot-jwt-example/mvnwLength of output: 210
Add execute permission to the Maven wrapper script
The playground/kinde-springboot-jwt-example/mvnw file currently has mode 100644 and won’t run as ./mvnw. Please set its executable bit so CI and users can invoke it directly.
• File needing fix:
playground/kinde-springboot-jwt-example/mvnw(mode 100644 → 100755)
To apply the change:
# Locally make it executable and stage the change
chmod +x playground/kinde-springboot-jwt-example/mvnw
git add playground/kinde-springboot-jwt-example/mvnw
# Or update index only
git update-index --chmod=+x playground/kinde-springboot-jwt-example/mvnw🤖 Prompt for AI Agents
In playground/kinde-springboot-jwt-example/mvnw at line 1, the Maven wrapper
script lacks execute permission, preventing it from running directly. Fix this
by setting the executable bit on the file using chmod +x
playground/kinde-springboot-jwt-example/mvnw and then stage the change with git
add or update the index with git update-index --chmod=+x to ensure it can be
executed in CI and by users.
| # parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties | ||
| while IFS="=" read -r key value; do | ||
| case "${key-}" in | ||
| distributionUrl) distributionUrl=$(trim "${value-}") ;; | ||
| distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; | ||
| esac | ||
| done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" | ||
| [ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Ensure wrapper metadata is committed (.mvn/wrapper/maven-wrapper.properties required)
This script depends on .mvn/wrapper/maven-wrapper.properties. Please confirm it’s included in the PR.
Run:
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Verify required wrapper files exist
required=(
".mvn/wrapper/maven-wrapper.properties"
".mvn/wrapper/maven-wrapper.jar"
)
for f in "${required[@]}"; do
if [ -f "$f" ]; then
echo "FOUND: $f"
else
echo "MISSING: $f"
fi
doneLength of output: 448
Add missing Maven Wrapper metadata files
The Maven Wrapper properties and JAR are required for the mvnw script to function correctly but are not present in the PR. Please commit the following files under .mvn/wrapper/:
.mvn/wrapper/maven-wrapper.properties.mvn/wrapper/maven-wrapper.jar
🤖 Prompt for AI Agents
In playground/kinde-springboot-jwt-example/mvnw around lines 108 to 116, the
script depends on Maven Wrapper metadata files that are missing. Add and commit
the required files .mvn/wrapper/maven-wrapper.properties and
.mvn/wrapper/maven-wrapper.jar to the repository to ensure the mvnw script
functions correctly.
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.security.config.Customizer; | ||
| import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
| import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||
| import org.springframework.security.web.SecurityFilterChain; | ||
|
|
||
| @Configuration | ||
| @EnableWebSecurity | ||
| public class SecurityConfig { | ||
|
|
||
| @Bean | ||
| public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { | ||
| http.authorizeHttpRequests(auth -> auth | ||
| .anyRequest().authenticated()) | ||
| .oauth2ResourceServer( | ||
| oauth2 -> oauth2.jwt(Customizer.withDefaults())); | ||
|
|
||
| return http.build(); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
❓ Verification inconclusive
Enable CORS at the security layer, disable CSRF, and use stateless sessions to avoid blocked preflights/401s
WebMvc CORS (WebConfig) isn’t applied unless http.cors(...) is enabled. For a JWT resource server, CSRF should be disabled and sessions stateless. Also permit OPTIONS preflight.
package com.kinde.springboot.kindespringbootservlet.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
+import org.springframework.http.HttpMethod;
+import org.springframework.security.config.http.SessionCreationPolicy;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
- http.authorizeHttpRequests(auth -> auth
- .anyRequest().authenticated())
- .oauth2ResourceServer(
- oauth2 -> oauth2.jwt(Customizer.withDefaults()));
+ http
+ .cors(Customizer.withDefaults())
+ .csrf(csrf -> csrf.disable())
+ .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
+ .authorizeHttpRequests(auth -> auth
+ .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
+ .anyRequest().authenticated())
+ .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
}Run to check presence of required settings:
🏁 Script executed:
#!/bin/bash
rg -n $'http\\.cors\\(|csrf\\(|SessionCreationPolicy\\.STATELESS|requestMatchers\\(HttpMethod\\.OPTIONS' playground/kinde-springboot-jwt-example/src/main/javaLength of output: 153
Add CORS support, disable CSRF, and enforce stateless sessions
For a JWT-based resource server, you need to:
- Enable CORS at the Spring Security layer (
http.cors()) so yourWebMvcCORS settings are applied. - Disable CSRF protection.
- Configure session management to be stateless.
- Permit all
OPTIONS /**requests to allow preflight checks.
Please update playground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/config/SecurityConfig.java as follows:
package com.kinde.springboot.kindespringbootservlet.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
+import org.springframework.http.HttpMethod;
+import org.springframework.security.config.http.SessionCreationPolicy;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
- http.authorizeHttpRequests(auth -> auth
- .anyRequest().authenticated())
- .oauth2ResourceServer(
- oauth2 -> oauth2.jwt(Customizer.withDefaults()));
+ http
+ .cors(Customizer.withDefaults())
+ .csrf(csrf -> csrf.disable())
+ .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
+ .authorizeHttpRequests(auth -> auth
+ .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
+ .anyRequest().authenticated())
+ .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import org.springframework.context.annotation.Bean; | |
| import org.springframework.context.annotation.Configuration; | |
| import org.springframework.security.config.Customizer; | |
| import org.springframework.security.config.annotation.web.builders.HttpSecurity; | |
| import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | |
| import org.springframework.security.web.SecurityFilterChain; | |
| @Configuration | |
| @EnableWebSecurity | |
| public class SecurityConfig { | |
| @Bean | |
| public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { | |
| http.authorizeHttpRequests(auth -> auth | |
| .anyRequest().authenticated()) | |
| .oauth2ResourceServer( | |
| oauth2 -> oauth2.jwt(Customizer.withDefaults())); | |
| return http.build(); | |
| } | |
| package com.kinde.springboot.kindespringbootservlet.config; | |
| import org.springframework.context.annotation.Bean; | |
| import org.springframework.context.annotation.Configuration; | |
| import org.springframework.security.config.Customizer; | |
| import org.springframework.security.config.annotation.web.builders.HttpSecurity; | |
| import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | |
| import org.springframework.security.web.SecurityFilterChain; | |
| import org.springframework.http.HttpMethod; | |
| import org.springframework.security.config.http.SessionCreationPolicy; | |
| @Configuration | |
| @EnableWebSecurity | |
| public class SecurityConfig { | |
| @Bean | |
| public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { | |
| http | |
| .cors(Customizer.withDefaults()) | |
| .csrf(csrf -> csrf.disable()) | |
| .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) | |
| .authorizeHttpRequests(auth -> auth | |
| .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() | |
| .anyRequest().authenticated()) | |
| .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())); | |
| return http.build(); | |
| } | |
| } |
🤖 Prompt for AI Agents
In
playground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/config/SecurityConfig.java
around lines 3 to 22, update the SecurityFilterChain bean to enable CORS by
calling http.cors(), disable CSRF protection with http.csrf().disable(),
configure session management to be stateless using
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS),
and permit all OPTIONS requests by adding an authorization rule to allow OPTIONS
/** without authentication. This ensures proper handling of CORS, disables
unnecessary CSRF protection for JWT, enforces stateless sessions, and allows
preflight requests.
| public void addCorsMappings(CorsRegistry registry) { | ||
| registry.addMapping("/**"); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
CORS is not actually opened; specify origins/methods and enable CORS in SecurityConfig.
As-is, addMapping("/**") doesn’t permit any cross-origin origin by default. Also, Spring Security will block CORS unless http.cors() is enabled.
Apply this diff to make the CORS intent explicit:
@Override
public void addCorsMappings(CorsRegistry registry) {
- registry.addMapping("/**");
+ registry.addMapping("/**")
+ // For playground/dev; restrict to your frontend origins in prod
+ .allowedOriginPatterns("*")
+ .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
+ .allowedHeaders("*")
+ .exposedHeaders("WWW-Authenticate")
+ .allowCredentials(false)
+ .maxAge(3600);
}And in SecurityConfig, ensure CORS is honored by the security filter chain:
// in SecurityConfig.filterChain(HttpSecurity http)
http
.cors(Customizer.withDefaults())
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));To verify CORS is enabled in SecurityConfig:
🏁 Script executed:
#!/bin/bash
# Check if http.cors is configured in the Spring Security config
rg -n "http\\s*\\.\\s*cors\\s*\\(" -A2 -B2 playground/kinde-springboot-jwt-example/src/main/javaLength of output: 93
🏁 Script executed:
#!/bin/bash
set -eo pipefail
echo "1) Locating SecurityConfig.java files:"
fd SecurityConfig.java playground/kinde-springboot-jwt-example/src/main/java || true
echo -e "\n2) Searching for filterChain definitions:"
rg -n "filterChain" -A10 -B5 playground/kinde-springboot-jwt-example/src/main/java || true
echo -e "\n3) Searching for any .cors( usages:"
rg -n "\.cors\s*\(" -A2 -B2 playground/kinde-springboot-jwt-example/src/main/java || trueLength of output: 2885
Enable full CORS configuration in MVC and Spring Security
To actually open CORS you must both specify allowed origins/methods in your WebConfig and enable CORS support in your security filter chain.
• In WebConfig.java – update addCorsMappings to include origins, methods, headers, etc.:
@Override
public void addCorsMappings(CorsRegistry registry) {
- registry.addMapping("/**");
+ registry.addMapping("/**")
+ // For playground/dev; restrict to your frontend origins in prod
+ .allowedOriginPatterns("*")
+ .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
+ .allowedHeaders("*")
+ .exposedHeaders("WWW-Authenticate")
+ .allowCredentials(false)
+ .maxAge(3600);
}• In SecurityConfig.java – enable Spring Security’s CORS support by calling .cors() on the HttpSecurity before authorization:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors(Customizer.withDefaults()) // <— add this line
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 ->
oauth2.jwt(Customizer.withDefaults()));
return http.build();
}🤖 Prompt for AI Agents
In
playground/kinde-springboot-jwt-example/src/main/java/com/kinde/springboot/kindespringbootservlet/config/WebConfig.java
around lines 10 to 12, the addCorsMappings method only adds a basic mapping
without specifying allowed origins, methods, or headers. Update this method to
explicitly set allowed origins, HTTP methods, and headers to fully configure
CORS. Additionally, in SecurityConfig.java, ensure that Spring Security's CORS
support is enabled by adding .cors(Customizer.withDefaults()) to the
HttpSecurity configuration before authorization rules.
playground/kinde-springboot-jwt-example/src/main/resources/application.properties
Show resolved
Hide resolved
| @SpringBootTest | ||
| class KindeSpringbootServletApplicationTests { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Prevent network calls during context load in tests.
Context boot can fail if issuer-uri triggers OIDC discovery. Point tests to a dummy JWKS URI so the decoder is configured without discovery.
Apply this diff:
-@SpringBootTest
+@SpringBootTest(properties = "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://example.com/.well-known/jwks.json")
class KindeSpringbootServletApplicationTests {Alternative (if you prefer a stubbed decoder over properties):
// inside this test class
@org.springframework.boot.test.context.TestConfiguration
static class TestJwtConfig {
@org.springframework.context.annotation.Bean
org.springframework.security.oauth2.jwt.JwtDecoder jwtDecoder() {
return token -> org.springframework.security.oauth2.jwt.Jwt.withTokenValue(token)
.header("alg", "none")
.claim("sub", "test")
.issuedAt(java.time.Instant.now())
.expiresAt(java.time.Instant.now().plusSeconds(60))
.build();
}
}🤖 Prompt for AI Agents
In
playground/kinde-springboot-jwt-example/src/test/java/com/kinde/springboot/kindespringbootservlet/KindeSpringbootServletApplicationTests.java
around lines 6 to 7, the test context may trigger network calls due to OIDC
discovery from the issuer-uri property. To prevent this, either configure the
test properties to point to a dummy JWKS URI or add a static inner test
configuration class that defines a JwtDecoder bean returning a stubbed Jwt
without network calls. Implement the provided TestJwtConfig class inside the
test class to stub the JwtDecoder and avoid external calls during tests.
No description provided.