Однако после того, как я упаковал приложение в JAR-файл с помощью mvn clean install и запустил его с помощью java -jar my-app.jar, я получаю следующее поведение:
- Вход через Postman или Insomnia по-прежнему работает (POST-запрос к /login возвращает токен, как и ожидалось).
- Вход в систему через интерфейс Angular (в браузере) завершается с ошибкой 403 Forbidden.
HttpRequestMethodNotSupportedException: метод запроса GET не поддерживается
Что я проверил:
- Конфигурация CORS в SecurityConfiguration допускает http://localhost:4200 и включает метод POST.
Код: Выделить всё
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.cors(cors -> cors.configurationSource(request -> {
var corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedOriginPatterns(List.of("http://localhost:4200"));
corsConfiguration.setAllowedMethods(List.of("GET","PATCH", "POST", "PUT", "DELETE", "OPTIONS"));
corsConfiguration.setAllowedHeaders(List.of("Authorization", "Content-Type"));
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}))
.authorizeHttpRequests(request -> request
.requestMatchers("/","/login","/join").permitAll()
.requestMatchers("/users").hasRole("ADMIN")
.requestMatchers("/uploads/**").permitAll()
.anyRequest().authenticated())
.sessionManagement(manager -> manager.sessionCreationPolicy(STATELESS))
.authenticationProvider(authenticationProvider())
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
- Angular отправляет запрос POST на /login.
Код: Выделить всё
login(loginRequest: LoginRequest): Observable {
this.dataService.log(true);
return this.http.post(`${environment.baseURL}/login`, loginRequest
)
.pipe(
tap((response: AuthResponse) => {
if (response.token) {
localStorage.setItem('jwtToken', response.token);
}
}),
catchError(error => {
console.error('Login error:', error);
return throwError(() => new Error(error.error?.message || 'Login failed. Please try again.'));
})
);
}
- Перехватчик Angular:
Код: Выделить всё
export const headerInterceptor: HttpInterceptorFn = (req: HttpRequest,
next: HttpHandlerFn
): Observable => {
const Authorization = localStorage.getItem('jwtToken') ? `Bearer ${localStorage.getItem('jwtToken')}` : '';
if(!req.url.includes('login') && !req.url.includes('join'))
return next(req.clone({ setHeaders: { Authorization } }));
else
return next(req);
};
- environment.prod.ts:
Код: Выделить всё
export const environment = {
production: true,
baseURL: "http://localhost:8080",
eventsURL: "http://localhost:8080/events",
homeURL: "http://localhost:8080/home",
citiesURL: "http://localhost:8080/cities",
commentsURL: "http://localhost:8080/comments",
usersURL: "http://localhost:8080/users"
};
- и в angular.json:
Код: Выделить всё
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
- в application.yml:
Код: Выделить всё
profiles:
active: prod
- запустите .jar с помощью
Код: Выделить всё
java -jar my-app.jar --spring.profiles.active=prod
- Отлично работает в IDE.
- Сбой только после запуска из JAR.
Вопрос:
Что может привести к тому, что Spring Boot ведет себя по-другому (особенно для запросов на вход через браузер) при запуске из JAR, а не из IDE?
Подробнее здесь: https://stackoverflow.com/questions/796 ... -but-works
Мобильная версия