So, my friend has a problem with her login page. When she tries to make a request to her api, it just makes an error in the front-end and in the api nothing happens.
This is the error that appears on the console:
Access to XMLHttpRequest at ‘http://localhost:8082/login’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
AuthenticationService.js:10 AxiosError {message: ‘Network Error’, name: ‘AxiosError’, code: ‘ERR_NETWORK’, config: {…}, request: XMLHttpRequest, …}
This is the login endpoint
@Controller
@CrossOrigin(
origins = "http://localhost:3000",
allowCredentials = "true"
)
@RequestMapping("/login")
public class AuthenticationController {
@Autowired
AuthenticationManager authenticationManager;
private static final Logger logger = LoggerFactory.getLogger(AuthenticationController.class);
@PostMapping
public ResponseEntity<?> login(
@RequestBody Login login,
HttpServletRequest request,
HttpServletResponse response
){
logger.debug("Received login request for username: {}", login.getUsername());
System.out.println("AuthenticationCOntroller");
SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword());
Authentication authentication = authenticationManager.authenticate(token);
if(authentication.isAuthenticated()){
User user = (User) authentication.getPrincipal();
Cookie cookie = CookieUtil.generateCookie(user);
response.addCookie(cookie);
return ResponseEntity.ok(authentication.getPrincipal());
}
}
This is her github links:
API
Front-end
She tried to refactor all her code and it still gets an error doing login.
2
Answers
the error message is self-explanatory. It is a CORS error. You need to configure the api side to include the Access-Control-Allow-Origin header in its responses. The value of this header should be the origin of the requesting site, or * to allow any origin.
I may have the solution!
In your AuthenticationManager you have two methods to configure cors.
You can have only one: