Я использую клиент Python для отправки запроса на публикацию на сервер приложений Spring Boot. Вместо выполнения метода контроллера, сопоставленного с URL-адресом, сервер перенаправляет запрос (статус 302) на страницу входа. Веб-безопасность на сервере настроена на разрешение доступа к этому URL-адресу без необходимости входа в систему. В чем может быть причина? Очень благодарен за любую помощь.
Мой клиентский код выглядит следующим образом.
import requests
import logging
import http.client as http_client
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
data = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4',
'key5': 'value5',
'key6': 'value6'
}
print("Sending headers and body =============\n")
print(f"Data: {data}")
print(f"Headers: {headers}")
print("end headers and body =============\n\n\n\n")
http_client.HTTPConnection.debuglevel = 1
logging.basicConfig(level=logging.DEBUG)
logging.getLogger().setLevel(logging.DEBUG)
response = requests.post("http://localhost:8080/myApp/v1/type/service", data=data,
headers=headers)
print("Request processed =============\n\n\n\n")
print("Start response fields =============\n")
print(f"Request URL: {response.request.url}")
print(f"Request Headers: {response.request.headers}")
print(f"Request Body: {response.request.body}")
print(f"Response Status Code: {response.status_code}")
print(f"Response Body: {response.text}")
print("End response fields =============\n\n\n\n")
Конфигурация безопасности следующая.
@Configuration
public class WebSecurityConfig {
@Bean
public UserDetailsService userDetailsService() {
return new LoginCredentialsDetailsJpaManager();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((requests) -> requests
.requestMatchers("/myApp/v1/accounts/login",
"/myApp/v1/type/service").permitAll()
.anyRequest().authenticated()
)
.formLogin((form) -> form
.loginPage("/myApp/v1/accounts/login")
.permitAll()
)
.logout((logout) ->
logout.deleteCookies("remove")
.invalidateHttpSession(true)
.logoutUrl("/logout")
.logoutSuccessUrl("/logout.done")
.permitAll()
);
return http.build();
}
}
Метод контроллера определяется следующим образом.
@Controller
public class TestController {
@PostMapping"/myApp/v1/type/service")
public String populateObjects(@ModelAttribute TestObj testObj) {
// Populate objects
return "homePage";
}
}
TestObj определяется следующим образом:
public class TestObj {
private String key1;
private String key2;
private String key3;
private String key4;
private String key5;
private String key6;
// Getters and setters...
}
Выполнение тестового клиента должно было привести к вызову метода контроллера, который возвращает домашнюю страницу (на данный момент заполнитель). Вместо этого мы получаем следующий результат.
Sending headers and body =============
Data: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4', 'key5': 'value5', 'key6': 'value6'}
Headers: {'Content-Type': 'application/json', 'Accept': 'application/json'}
end headers and body =============
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): localhost:8080
send: b'POST /myApp/v1/type/service HTTP/1.1\r\nHost: localhost:8080\r\nUser-Agent: python-requests/2.32.3\r\nAccept-Encoding: gzip, deflate\r\nAccept: application/json\r\nConnection: keep-alive\r\nContent-Type: application/json\r\nContent-Length: 71\r\n\r\n'
send: b'key1=value1&key2=value2&key3=value3&key4=value4&key5=value5&key6=value6'
reply: 'HTTP/1.1 302 \r\n'
header: Vary: Origin
header: Vary: Access-Control-Request-Method
header: Vary: Access-Control-Request-Headers
header: Set-Cookie: JSESSIONID=8C43E31342E7B70CF2621763CD763004; Path=/; HttpOnly
header: X-Content-Type-Options: nosniff
header: X-XSS-Protection: 0
header: Cache-Control: no-cache, no-store, max-age=0, must-revalidate
header: Pragma: no-cache
header: Expires: 0
header: X-Frame-Options: DENY
header: Location: http://localhost:8080/myApp/v1/accounts ... 63CD763004
header: Content-Length: 0
header: Date: Tue, 17 Sep 2024 16:48:27 GMT
header: Keep-Alive: timeout=60
header: Connection: keep-alive
DEBUG:urllib3.connectionpool:http://localhost:8080 "POST /myApp/v1/type/service HTTP/11" 302 0
send: b'GET /myApp/v1/accounts/login;jsessionid=8C43E31342E7B70CF2621763CD763004 HTTP/1.1\r\nHost: localhost:8080\r\nUser-Agent: python-requests/2.32.3\r\nAccept-Encoding: gzip, deflate\r\nAccept: application/json\r\nConnection: keep-alive\r\nCookie: JSESSIONID=8C43E31342E7B70CF2621763CD763004\r\n\r\n'
reply: 'HTTP/1.1 302 \r\n'
header: Location: http://localhost:8080/myApp/v1/accounts/login
header: Content-Length: 0
header: Date: Tue, 17 Sep 2024 16:48:27 GMT
header: Keep-Alive: timeout=60
header: Connection: keep-alive
DEBUG:urllib3.connectionpool:http://localhost:8080 "GET /myApp/v1/accounts/login;jsessionid=8C43E31342E7B70CF2621763CD763004 HTTP/11" 302 0
send: b'GET /myApp/v1/accounts/login HTTP/1.1\r\nHost: localhost:8080\r\nUser-Agent: python-requests/2.32.3\r\nAccept-Encoding: gzip, deflate\r\nAccept: application/json\r\nConnection: keep-alive\r\nCookie: JSESSIONID=8C43E31342E7B70CF2621763CD763004\r\n\r\n'
reply: 'HTTP/1.1 200 \r\n'
header: Vary: Origin
header: Vary: Access-Control-Request-Method
header: Vary: Access-Control-Request-Headers
header: X-Content-Type-Options: nosniff
header: X-XSS-Protection: 0
header: Cache-Control: no-cache, no-store, max-age=0, must-revalidate
header: Pragma: no-cache
header: Expires: 0
header: X-Frame-Options: DENY
header: Content-Type: text/html;charset=UTF-8
header: Content-Language: en-US
header: Transfer-Encoding: chunked
header: Date: Tue, 17 Sep 2024 16:48:27 GMT
header: Keep-Alive: timeout=60
header: Connection: keep-alive
DEBUG:urllib3.connectionpool:http://localhost:8080 "GET /myApp/v1/accounts/login HTTP/11" 200 None
Request processed =============
Start response fields =============
Request URL: http://localhost:8080/myApp/v1/accounts/login
Request Headers: {'User-Agent': 'python-requests/2.32.3', 'Accept-Encoding': 'gzip, deflate', 'Accept': 'application/json', 'Connection': 'keep-alive', 'Cookie': 'JSESSIONID=8C43E31342E7B70CF2621763CD763004'}
Request Body: None
Response Status Code: 200
Response Body:
MyLogin
MyLogin
Username:
Password:
End response fields =============
Подробнее здесь: https://stackoverflow.com/questions/789 ... ed-to-logi
Почтовый запрос Python с телом json на сервер Spring Boot перенаправляется на страницу входа ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение