Это моя конфигурация безопасности:
Код: Выделить всё
@Configuration
public class SecurityConfig {
private String[] publicUrls = {.....};
private CustomUserDetailsService customUserDetailsService;
private AllUsersService allUsersService;
private UsersService usersService;
@Autowired
public SecurityConfig(CustomUserDetailsService customUserDetailsService, AllUsersService allUsersService, UsersService usersService) {
this.customUserDetailsService = customUserDetailsService;
this.allUsersService = allUsersService;
this.usersService = usersService;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(config -> config
.requestMatchers(publicUrls).permitAll()
.anyRequest().authenticated()
).formLogin(login -> login
.loginPage("/login")
.permitAll()
.successHandler((request, response, authentication) -> {
// Upon successful login, send a 200 ok response
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json");
response.getWriter().write("{\"message\": \"Login successful\"}");
})
.failureHandler((request, response, exception) -> {
// Upon failed login, send a 401 Unauthorized response
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json");
response.getWriter().write("{\"message\": \"Invalid email or password\"}");
})
).logout(logout -> logout
.logoutUrl("/logout")
.logoutSuccessHandler((request, response, authentication) -> {
// Return a JSON response
response.setContentType("application/json");
response.getWriter().write("{\"message\": \"Logout successful\"}");
})
);
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(customUserDetailsService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
// CORS configuration
@Bean
public FilterRegistrationBean corsFilter() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000");
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "Accept"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(-102);
return bean;
}
}
Код: Выделить всё
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
try {
const response = await axios.post("http://localhost:8080/login",
{
username,
password
},
{
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
)
if (response.status === 200) {
window.location.href = "/home";
}
}
catch (error) {
if (axios.isAxiosError(error) && error.response) {
if (error.response.status === 401) {
alert("Invalid email or password");
}
}
}
}
Это мой запрос на вход, отправленный из интерфейса реагирования после развертывания серверной части для рендеринга:
Код: Выделить всё
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
try {
const response = await axios.post("http://-----.onrender.com/login",
{
username,
password
},
{
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}enter image description here
}
)
if (response.status === 200) {
window.location.href = "/home";
}
}
catch (error) {
if (axios.isAxiosError(error) && error.response) {
if (error.response.status === 401) {
alert("Invalid email or password");
}
}
}
}
Скриншот сообщения об ошибке
Как я развертывание моего приложения Spring для рендеринга через изображение докера, где изображение докера запускается без каких-либо проблем, но при развертывании для рендеринга оно показывает эту ошибку.
Я новичок в этой производственной среде, и я был бы очень признателен за ваш отзыв. Я хочу, чтобы развернутое приложение отлично работало на платформе рендеринга, так же, как оно работало нормально через образ Docker
Подробнее здесь: https://stackoverflow.com/questions/793 ... en-i-deplo