Proxy Blocking Post в /API /аутентификат с 403 ЗапрещеноJAVA

Программисты JAVA общаются здесь
Anonymous
Proxy Blocking Post в /API /аутентификат с 403 Запрещено

Сообщение Anonymous »

Я сталкиваюсь с критической проблемой, в которой конечная точка входа моего приложения блокируется прокси-сервером fly.io (по крайней мере, так и выглядит).
Проблем /API /Authenticate, Proxy Fly.io возвращает запрещенную ошибку 403.
Мои журналы приложений (журналы мух) показывают, что запрос никогда не достигает моего сервера. Я попал сюда с кодом), который доказывает, что проблема заключается в прокси -слое Fly.io.
Я могу успешно войти в свою локальную машину Dev Env, что доказывает, что мое бэкэнд -приложение работает правильно. Блок происходит только с полным запросом от fly.io. < /P>
Спасибо за вашу помощь.@Configuration
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfiguration {

private static final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private final JHipsterProperties jHipsterProperties;

public SecurityConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
log.info("SECURITY CONFIG LOADED! Using robust MvcRequestMatcher for multi-chain routing. Version 13.");
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}

@Bean
MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) {
return new MvcRequestMatcher.Builder(introspector);
}

// =================================================================================
// CHAIN 1: STATELESS PUBLIC AUTH API - HIGHEST PRIORITY
// =================================================================================
@Bean
@Order(1)
// IMPORTANT: Add the MvcRequestMatcher.Builder mvc parameter back in
public SecurityFilterChain statelessPublicApiFilterChain(HttpSecurity http, MvcRequestMatcher.Builder mvc) throws Exception {
http
.securityMatcher(
new OrRequestMatcher(
// THIS IS THE FIX: Use the MvcRequestMatcher with the specific HTTP method.
mvc.pattern(HttpMethod.POST, "/api/authenticate"),
mvc.pattern(HttpMethod.POST, "/api/register"),
mvc.pattern(HttpMethod.GET, "/api/activate"), // This is likely a GET
mvc.pattern(HttpMethod.POST, "/api/account/reset-password/init"),
mvc.pattern(HttpMethod.POST, "/api/account/reset-password/finish")
)
)
.cors(withDefaults())
.csrf(AbstractHttpConfigurer::disable) // CSRF is disabled for this chain
.authorizeHttpRequests(authz -> authz.anyRequest().permitAll()) // All matched requests are permitted
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(exceptions ->
exceptions
.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
.accessDeniedHandler(new BearerTokenAccessDeniedHandler())
);
return http.build();
}

// =================================================================================
// CHAIN 2: DEFAULT APPLICATION SECURITY - LOWER PRIORITY
// =================================================================================
@Bean
@Order(2)
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http, MvcRequestMatcher.Builder mvc) throws Exception {
http
.cors(withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.headers(headers ->
headers
.contentSecurityPolicy(csp -> csp.policyDirectives(jHipsterProperties.getSecurity().getContentSecurityPolicy()))
.frameOptions(FrameOptionsConfig::sameOrigin)
.referrerPolicy(referrer -> referrer.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
.permissionsPolicyHeader(permissions ->
permissions.policy(
"camera=(), fullscreen=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), sync-xhr=()"
)
)
)
.authorizeHttpRequests(authz ->
authz
.requestMatchers(mvc.pattern("/"))
.permitAll()
.requestMatchers(
mvc.pattern("/index.html"),
mvc.pattern("/*.js"),
mvc.pattern("/*.txt"),
mvc.pattern("/*.json"),
mvc.pattern("/*.map"),
mvc.pattern("/*.css")
)
.permitAll()
.requestMatchers(mvc.pattern("/*.ico"), mvc.pattern("/*.png"), mvc.pattern("/*.svg"), mvc.pattern("/*.webapp"))
.permitAll()
.requestMatchers(
mvc.pattern("/app/**"),
mvc.pattern("/i18n/**"),
mvc.pattern("/content/**"),
mvc.pattern("/webfonts/**"),
mvc.pattern("/assets/**")
)
.permitAll()
.requestMatchers(mvc.pattern("/*.woff2"), mvc.pattern("/*.woff"), mvc.pattern("/*.ttf"), mvc.pattern("/*.eot"))
.permitAll()
.requestMatchers(mvc.pattern("/swagger-ui/**"), mvc.pattern("/v3/api-docs/**"))
.permitAll()
.requestMatchers(mvc.pattern(HttpMethod.POST, "/api/contact-messages"))
.permitAll()
.requestMatchers(mvc.pattern(HttpMethod.GET, "/api/blog-posts"), mvc.pattern(HttpMethod.GET, "/api/blog-posts/**"))
.permitAll()
.requestMatchers(
mvc.pattern(HttpMethod.GET, "/api/skills"),
mvc.pattern(HttpMethod.GET, "/api/projects"),
mvc.pattern(HttpMethod.GET, "/api/project-images"),
mvc.pattern(HttpMethod.GET, "/api/services")
)
.permitAll()
.requestMatchers(
mvc.pattern("/management/health"),
mvc.pattern("/management/health/**"),
mvc.pattern("/management/info"),
mvc.pattern("/management/prometheus")
)
.permitAll()
.requestMatchers(mvc.pattern("/api/admin/**"))
.hasAuthority(AuthoritiesConstants.ADMIN)
.requestMatchers(mvc.pattern("/management/**"))
.hasAuthority(AuthoritiesConstants.ADMIN)
.requestMatchers(mvc.pattern("/api/**"))
.authenticated()
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(exceptions ->
exceptions
.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
.accessDeniedHandler(new BearerTokenAccessDeniedHandler())
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()));
return http.build();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(
Arrays.asList("http://localhost:9000", "http://localhost:8080", "https://zoranstepanoski-prof-website.fly.dev")
);
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
< /code>
fly.toml
app = 'zoranstepanoski-prof-website'
primary_region = 'cdg'

[build]
dockerfile = "Dockerfile"

[[services]]
protocol = "tcp"
internal_port = 8080
processes = ["app"]

auto_stop_machines = true
auto_start_machines = true
min_machines_running = 1

[services.concurrency]
type = "connections"
hard_limit = 25
soft_limit = 20

[[services.ports]]
port = 80
handlers = ["http"]
force_https = true

[[services.ports]]
port = 443
handlers = ["tls", "http"]

[[services.http_checks]]
interval = "15s"
timeout = "5s"
grace_period = "90s"
method = "get"
path = "/management/health"
protocol = "http"

[[vm]]
memory = "2gb"
cpu_kind = "performance"
cpus = 1
< /code>
и так как я использую Docker
dockerfile: < /p>
# ------------------------
# Stage 1: Build with Maven
# ------------------------
FROM maven:3.9.9-eclipse-temurin-21 AS build
WORKDIR /app

# Copy everything (backend + frontend)
COPY . .

# Build backend + frontend (prod profile)
RUN ./mvnw -Pprod -DskipTests package

# ------------------------
# Stage 2: Run with JRE
# ------------------------
FROM eclipse-temurin:21-jre-jammy
WORKDIR /app

# Copy the built JAR from the build stage
COPY --from=build /app/target/*.jar app.jar

# Expose app port
EXPOSE 8080

# Run the app
ENTRYPOINT ["java", "-jar", "app.jar"]


Подробнее здесь: https://stackoverflow.com/questions/797 ... -forbidden

Вернуться в «JAVA»