CrossOrigin in RESTful Web Service

In this short tutorial, I am going to share with you how to enable CrossOrigin in a RESTful Web Service API build with Spring Boot and Spring MVC. And to do that you need to simply annotate a method in your RestController class with @CrossOrigin annotation like in the example below.

Enable CrossOrigin

@CrossOrigin(origins = "http://localhost:8080")
@GetMapping(path = "/email-verification", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
 public OperationResponseModel verifyEmailToken(@RequestParam(value="token") String token) 
 {
     
      boolean isVerified = userService.verifyEmailToken(token);
      
      OperationResponseModel returnValue = new OperationResponseModel();
      returnValue.setOperationName(RequestOperation.VERIFY_EMAIL.name());
     
      if(isVerified)
      {
          returnValue.setMessage("Email address is verified");
          returnValue.setResult(ResponseStatus.SUCCESS.name());
      } else {
          returnValue.setMessage("Email token could not be verified");
          returnValue.setResult(ResponseStatus.ERROR.name());
      }
     
      return returnValue;
 }

In the brackets of @CrossOrigin you need to specify the domain name from which an AJAX HTTP request is sent. In my example I used localhost but of course, it does not need to be a localhost domain name but a remote domain name from which HTTP request is sent.

Once you do that, you can send an AJAX HTTP Request to your RESTful Web Service endpoint from a web app hosted on a different server like this:

Sending CrossOrigin HTTP Request

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


        <script language="javascript">

            $(document).ready(function () {

                var urlParams = new URLSearchParams(location.search);

                if (urlParams.has('token'))
                {
                    verifyToken(urlParams.get('token'));
                }
            });

            function verifyToken(tokenValue)
            {
                $.get('http://localhost:8080/mobile-app-ws/users/email-verification', {token: tokenValue})
                        .done(function (response) {
                            if (response["result"] === "SUCCESS")
                            {
                                $("#not-successful-result").attr( "style", "display: none !important;" ); 
                                $("#successful-result").attr( "style", "display: block !important;" ); 
                                
                            } else {
                                $("#successful-result").attr( "style", "display: none !important;" ); 
                                $("#not-successful-result").attr( "style", "display: block !important;" ); 
                            }

                        });
            }

        </script>
    </head>
    <body>
        <div id="successful-result" style="display:none">Successful verification</div>
        <div id="not-successful-result" style="display:none">Verification link has expired</div>
    </body>
</html>

I hope this short example will help you add a CrossOrigin support to your RESTful Web Service API. If you are interested in learning more about building RESTful Web Service APIs, have a look at the below list of video courses and hopefully one of them will be exactly what you needed.

The code examples used in this tutorial I took from my video course which demonstrates how to implement most of the commonly needed functionality like:

  • User sign-up,
  • User sign-in,
  • Email verification feature,
  • Get list of users and pagination,
  • Update and Delete user details,
  • and other useful functionality.

Have a look at the complete list of video lessons here.