5

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";
        }
    }
  }
}
Divyani Garg
  • 138
  • 1
  • 3
  • 15
  • angular is single page and redirecting to pages is not acceptable. so for redirect to angular pages you should send request with rest api and in response you can route between modules. – Amir Azizkhani Aug 03 '21 at 12:13

3 Answers3

3

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

  • Hey, I have removed the @crossorigin and added proxy.conf.json, But still I am getting CORS error : Access to XMLHttpRequest at 'http://localhost:8082/dis/login' from origin 'http://localhost:4200' 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. – Divyani Garg Jan 07 '19 at 13:57
2

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.

  • 1
    When Angular 6 work as frontend then Rest API has to be consume. From Mail It will direclty call rest API and that api will not subscribed in angular – Akash Singh Sengar Dec 27 '19 at 09:58
0

I observed that when you redirect from Spring Boot to an Angular page the error "request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response" means that, Angular node.js server does not detect field content-type in the header Access-Control-Allow-Headers in your Angular app configuration. The point here is that roles of backend server and and client app are a bit the other way around in this redirection.

To solve this I would add content-type field into the response header Access-Control-Allow-Headers in the following way:

1. create file proxy.config.js just below the package.json file in your Angular project with this code:

module.exports = {
    "/": {
       "secure": false,
            "bypass": (req, res, proxyOptions) => {
             res.setHeader('Access-Control-Allow-Headers', "Content-Type");
         }
    }
};  

and modify angular.json file by adding line:

"proxyConfig": "proxy.config.js" 

to this location:

projects >> client >> architect >> serve >> options 

This solution worked in my case. Note that the capitalization of first letter of the field name matters.