springboot backend solves cross domain problems

  • 2021-07-07 07:25:38
  • OfStack

First of all, we need to know what cross-domain is:

Cross-domain refers to the mutual access between different domain names. Cross-domain means that browsers cannot execute scripts from other websites. It is caused by the browser's homologous policy, which is the security restriction imposed by the browser on JavaScript.

That is, if we are in the A website, we want to use Ajax to obtain specific content in the B website

If the A site is not in the same domain as the B site, a cross-domain access problem occurs.

What is the same domain?

The same 1 protocol, the same 1ip, the same 1 port, and one difference among three identical results in cross-domain.

Front-end solution cross-domain:

As mentioned earlier, cross-domain means that browsers cannot execute scripts of other websites. It is caused by the browser's homologous policy, which is the security restriction imposed by the browser on JavaScript.

Resolve:

Therefore, make an node server as a proxy, send a request to the node server, and forward the node server to the back end to bypass the cross-domain problem.

The back end solves cross-domain problems:

The back-end solution is simpler. For example, the springboot I use can realize cross-domain access to the current controller only by adding a "@ CrossOrigin" annotation to the Controller class. Of course, this tag can also be added to the method.


@RequestMapping(value = "/users")
@RestController
@CrossOrigin
public class UserController {
  @Autowired
  private UserService userService;
  @RequestMapping(method = RequestMethod.POST)
  @CrossOrigin
  public User create(@RequestBody @Validated User user) {
    return userService.create(user);
  }
   } 

Related knowledge:

What is CSRF?

CSRF (Cross-site request forgery), Chinese name: cross-site request forgery, also known as one click attack/session riding, abbreviated as CSRF/XSRF.

Summarize


Related articles: