Java Spring: JWT Security and Cors

Robert Taylor
2 min readMay 31, 2020

--

Now we’ve covered how to setup our Spring API, getting it connected to a database, and setting up our controllers so we can use it. So what’s next? With any API, especially if it’s going to be used in production, you want to set up some kind of security system. There are many different ways you can set up security for your API, for this tutorial we’ll be using JWT token authentication.

Getting Started

As per usual, I’ve created a nice Github repository to help you get started. Go ahead and clone it down to your machine.

Also be sure to change the application.properties file to make sure the app connects to your database.

You’ll see that this is a simple Spring Application that has a User object, as well as it’s DAO and Controller. Right now it’s just a java object that stores a username, password, and name. We’ll be adding most of the code to our Controller and a few config files.

Now let’s take a look at our pom.xml to see what dependencies we loaded up:

The main dependencies that we have to worry about when setting up security are the spring security and json web token dependencies.

The first thing we’re going to cover is setting up a CORS configuration.

CORS Configuration

Now that we’ve learned how to set up a Spring API, we have to manually allow it to be accessed by frontend applications. Your API will return an error unless we override the defaults for our CORS config.

To get started, create a ‘config’ folder in your ‘main/java’ folder. In that folder, create a new class file called Cors Config. To this class we’re gonna want to add a @Configuration annotation to let our Spring app know that this a configuration file. Also, implement WebMvcConfigurer. This will allow us to overwrite the Spring MVC and allow us to access our app from a frontend in addition to using a Spring template.

Next we’re going to add a function that returns an instance of a WebMvcConfigurer, we’ll call this corsConfigurer(). We’ll also add a @Bean annotation to make sure our program loads it up on launch.

Now we just need to add a function to define our cors mapping for our configuration. This function will have three main parts:

addMapping: this allows us to specify which endpoints are allowed through the Cors Configuration

allowedOrigins: this specifies which ip addresses are allowed through the configuration

allowedHeaders: this specifies which HTTP request headers are allowed through the configuration.

For this tutorial we’re going to allow all for each option:

This all we need to do to setup our Cors Configuration. Now we can move on to setting up our token authorization.

--

--