Reputation: 177
I am creating a spring boot API and react front end in a project I am working on. There is no user logon on the front end, however, I would like to ensure my API endpoints are secure and only accessed by my react front end and I am struggling to come up with solutions.
One possible solution I was thinking is to secure the API with JWT. Create a user table and create a user for the front end client. When the user visits the front end get a token and validate this token on all requests. I’m not sure if this is a valid approach or if there is another solution better fitted.
The app will be hosted on Heroku, stack: spring boot, react and MySQL database. Anyone come across this before or any advice greatly appreciated.
Upvotes: 2
Views: 1215
Reputation: 2407
This is not possible.
At its core, this would require the frontend to have access to some secret value with which to authenticate it's request with, i.e. a token. You would then allow requests based on the presence of this secret value, and serve the responses.
However, frontends serve public assets and thus can't have secrets. At the end of the day, any user would be able to inspect their network requests, and extract the token from the requests your frontend makes.
With this information they can then forge their own requests.
Upvotes: 2
Reputation: 1088
I would recommend to add domain at allowedOrigins of CORS config :
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
import java.util.List;
@Component
public class CorsFilterConfig {
public static final List<String> allowedOrigins = Arrays.asList("yourDomainsHere");
@Bean
public FilterRegistrationBean<CorsFilter> initCorsFilter() {
// @formatter:off
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
config.addAllowedMethod("*");
config.setAllowedOrigins(allowedOrigins);
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
// @formatter:on
}
}
Upvotes: 0