Hi to all that can help me.
I’ve been sitting here for days on end and I can’t figure out how to get my Spring Boot and React app working.
The frontend is deployed as an Azure Static Web App and the spring boot backend as an Azure Web App.
Initially, everything worked fine when I tested locally but once I deployed to Azure the login does not work anymore. The basic functionality of the app is a portal where you have a product page that you can add to orders. Adding a product to an order and viewing/editing an order requires both authentication. This part of the app works fine, I click on the add to product button and it takes me to the google auth page where I select an account to sign in with. After redirection, I can’t view orders and I keep on getting asked to log in…
However, when I run an endpoint (deployed backend) in my browser to get the currently logged in user, it shows the user I just selected on the deployed frontend. The same request in the frontend gives the following:
Access to XMLHttpRequest at ” (redirected from ”) from origin ” has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
I’ve tried about everything and even disabled CSRF at some point on the backend. The flow on the local development was what I was looking for:
Adding a product or viewing/editing orders requires authentication. Going to these pages or clicking the buttons took me to Google Auth and I signed in. Afterwards I could add products to orders and edit orders. I don’t know what to do anymore 🙁
package com.xavier.client_backend.config;
import com.xavier.client_backend.domain.entities.ClientEntity;
import com.xavier.client_backend.repositories.ClientRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import java.util.List;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
private final ClientRepository clientRepository;
public SecurityConfig(ClientRepository clientRepository) {
this.clientRepository = clientRepository;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> {
CorsConfigurationSource source = request -> {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("<redacted_url>"));
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(List.of("*"));
configuration.setAllowCredentials(true);
return configuration;
};
cors.configurationSource(source);
})
.authorizeHttpRequests(auth -> {
auth.requestMatchers("/api/products/**").permitAll();
auth.anyRequest().authenticated();
})
.oauth2Login(oauth2 -> oauth2.successHandler(successHandler()))
.logout(logout -> logout
.logoutUrl("/logout")
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies("JSESSIONID")
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
);
return http.build();
}
@Bean
public AuthenticationSuccessHandler successHandler() {
return (request, response, authentication) -> {
OAuth2User oAuth2User = (OAuth2User) authentication.getPrincipal();
String email = oAuth2User.getAttribute("email");
ClientEntity client = clientRepository.findByEmail(email);
if (client == null) {
client = new ClientEntity();
client.setName(oAuth2User.getAttribute("name"));
client.setEmail(email);
clientRepository.save(client);
}
SimpleUrlAuthenticationSuccessHandler handler = new SimpleUrlAuthenticationSuccessHandler();
handler.setDefaultTargetUrl("<redacted_url>");
handler.onAuthenticationSuccess(request, response, authentication);
};
}
}
Edit 2:
Here is an ProductList.js file I have for reference to these calls:
import React, { useEffect, useState } from "react";
import axios from "axios";
const ProductList = ({ isAuthenticated }) => {
const [products, setProducts] = useState([]);
const [client, setClient] = useState(null);
const [showToast, setShowToast] = useState(false);
const [toastMessage, setToastMessage] = useState("");
useEffect(() => {
const fetchClientAndProducts = async () => {
try {
const clientResponse = await axios.get(
`https://backendurl.azurewebsites.net/api/clients/me/`,
{ withCredentials: true }
);
if (clientResponse.status === 200) {
setClient(clientResponse.data);
const productsResponse = await axios.get(
`https://backendurl.azurewebsites.net/api/products`
);
const productsData = await productsResponse.data;
setProducts(productsData);
} else {
setClient(null);
}
} catch (error) {
console.error("Error fetching client or products:", error);
setClient(null);
}
};
fetchClientAndProducts();
}, []);
const handleAddToOrder = async (productId, productName) => {
if (!isAuthenticated) {
window.location.href =
"https://backendurl.azurewebsites.net/oauth2/authorization/google";
return;
}
try {
// Check if there is an existing order for the client
const ordersResponse = await axios.get(
`https://backendurl.azurewebsites.net/api/orders/client/${client.id}`,
{ withCredentials: true }
);
const orders = ordersResponse.data;
if (orders.length > 0) {
// There is an existing order, update it
const existingOrder = orders[0]; // Assuming only one open order at a time
const updatedOrderItems = [...existingOrder.orderItems];
const existingItem = updatedOrderItems.find(
(item) => item.productId === productId
);
if (existingItem) {
existingItem.quantity += 1;
} else {
updatedOrderItems.push({ productId, quantity: 1 });
}
const updatedOrder = {
...existingOrder,
orderItems: updatedOrderItems,
};
await axios.put(
`https://backendurl.azurewebsites.net/api/orders/${existingOrder.id}`,
updatedOrder,
{ withCredentials: true }
);
setToastMessage(`${productName} added to existing order`);
setShowToast(true);
setTimeout(() => setShowToast(false), 3000); // Hide toast after 3 seconds
} else {
// No existing order, create a new one
const newOrder = {
clientId: client.id,
orderDate: new Date().toISOString(),
orderItems: [{ productId, quantity: 1 }],
};
const response = await axios.post(
`https://backendurl.azurewebsites.net/me/api/orders`,
newOrder,
{
withCredentials: true,
}
);
if (response.status === 201) {
setToastMessage(`${productName} added to new order`);
setShowToast(true);
setTimeout(() => setShowToast(false), 3000); // Hide toast after 3 seconds
} else {
console.error("Failed to add product to new order");
}
}
} catch (error) {
console.error("Error adding product to order:", error);
}
};
return (
<div className="container mt-4">
<div className="row">
{products.map((product) => (
<div className="col-md-3 mb-4" key={product.id}>
<div className="card h-100 text-center">
<div className="card-body">
<h5 className="card-title">{product.name}</h5>
<p className="card-text">Price: R{product.price.toFixed(2)}</p>
<button
className="btn btn-primary"
onClick={() => handleAddToOrder(product.id, product.name)}
>
Add to Order
</button>
</div>
</div>
</div>
))}
</div>
<div
className="toast-container position-fixed bottom-0 end-0 p-3"
style={{ zIndex: 9999 }}
>
<div
className={`toast ${showToast ? "show" : "hide"}`}
role="alert"
aria-live="assertive"
aria-atomic="true"
>
<div className="toast-header">
<strong className="me-auto">Notification</strong>
<button
type="button"
className="btn-close"
onClick={() => setShowToast(false)}
></button>
</div>
<div className="toast-body">{toastMessage}</div>
</div>
</div>
</div>
);
};
export default ProductList;
Here are the errors present in the browser:
Access to XMLHttpRequest at 'https://backendurl.azurewebsites.net/api/clients/me/' from origin 'https://mango.5.azurestaticapps.net' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
mango.5.azurestaticapps.net/:1 Access to fetch at 'https://backendurl.azurewebsites.net/api/clients/me/' from origin 'https://mango.5.azurestaticapps.net' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.
The backend and frontend url has been changed a bit. Thank you for any help!
XavierReynolds is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
10
Did you used @CrossOrigin annotation in the controller. Check once if it is working?
Pratik tayal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1