I am developing a application with angular 6 as front end and spring boot as back end. In this while implementing user authentication module I want to redirect to student and staff home after login accordingly.
But, I am not able to redirect the page from spring boot. Using Redirect to an external URL from controller action in Spring MVC this solution I am getting the CORS error : "Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response."
Or, if there is another way to do this task?
AuthenticationController.java
package sgsits.cse.dis.user.controller;
@CrossOrigin(origins = "*") // enables cross origin request
@RestController
@RequestMapping(value = "/dis")
@Api(value = "Authentication Resource")
public class AuthenticationController {
@Autowired
StudentRepository studRepo;
@Autowired
StaffRepository staffRepo;
@Autowired
EmailController email;
String pattern = "MM-dd-yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
@ApiOperation(value = "login", response = Object.class, httpMethod = "POST", produces = "application/json")
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestBody Authentication auth, HttpServletResponse httpServletResponse) {
Optional<StaffProfile> staff = staffRepo.findByEmail(auth.getUsername());
if (staff.isPresent()) {
String md5_pass = MD5.getHash(auth.getPassword());
if (staff.get().getPassword().equals(md5_pass)) {
// set session
// update last login
return "forward:/localhost:4200/staff";
} else
return "You have entered incorrect password";
} else {
Optional<StudentProfile> student = studRepo.findByEnrollmentId(auth.getUsername());
if (student.isPresent()) {
String md5_pass = MD5.getHash(auth.getPassword());
if (student.get().getPassword().equals(md5_pass)) {
// set session
// update last login
httpServletResponse.setHeader("Location", "http://localhost:4200/reset-password");
httpServletResponse.setStatus(302);
return "redirect:localhost:4200/student";
} else
return "You have entered incorrect password";
} else {
return "You are not registered with the system. Please signup first";
}
}
}
}
Do not add @CrossOrigin(origins = "*")
annotation to controller.
Assume your api runs on 8080 and your angular code on 4200. If true;
create a file called proxy.conf.json
{
"/api/": {
"target": "http://localhost:8080/",
"secure": false,
"changeOrigin": true
}
Start angular app using this command
ng serve --proxy-config proxy.conf.json
With this configuration when you call localhost:4200/api you it will call 8080 and it won't have any CORS error
Why don't you return a proper API Response and code and depending on your response and Code you can redirect on the front end.
It makes your API Completely RESTFUL. I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With