Securing your rest API with SpringSecurity
Tags: tutorial, java, springboot, programming
Published: 2022-01-31 13:11:37

![order66](https://cdn-images-1.medium.com/max/2000/1*vVNRSi6bmrQOYsgW5UgOBA.jpeg)

## What we will do

After creating our API in [the previous step](https://dev.to/erwanlt/building-a-simple-rest-api-with-springboot-53mc), we will now secure it using Spring Security.
In order to do so, we need to add 2 dependencies to our pom.xml file

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>

## What it will look like

![UML](https://cdn-images-1.medium.com/max/4848/1*3nhII1S2DrVWCyljQouUNw.png)

## Execute Order 66

### The Account Entity

In order to secure our API, we will use some [roles](https://javarevisited.blogspot.com/2013/07/role-based-access-control-using-spring-security-ldap-authorities-mapping-mvc.html), so to achieve that, we will create an account entity that will use those roles.
{% gist https://gist.github.com/ErwanLT/43b64fb27da8a0b1ad01e7faaa9af6a8.js %}
### The Repository

In order to know if the user who will try to use our API exists and have the role associated we also need to create the repository linked to the Account entity.
{% gist https://gist.github.com/ErwanLT/42234f4f2e93effa70969e63c0cc8b67.js %}
When we created the CloneRepository earlier, we didn’t need to create any method in it because all the methods we used were already implemented thanks to [inheritance](http://www.java67.com/2012/08/what-is-inheritance-in-java-oops-programming-example.html).
Here we will need a specific method like the one above *findOneByUsername*, with that one our repository will know that we search only one result that matches the String username passed on the argument. (see [Spring Data JPA](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods) doc if you want to know how it works).

### The controller

Now that we have created the account that will have the roles to connect to our API we can update our controller to make it accept these roles on its method.
{% gist https://gist.github.com/ErwanLT/00bcffae78f676bd9320ac0213bd0717.js %}
As you can see, our method now avec the @PreAuthorize annotation that indicates the roles who can access it.

So, is my API secured now? The response is **NO** !
We have created the account entity and its a repository, we have upgraded our controller to indicate the roles that it will use, but we have yet to implement the security configuration.
So now let’s implement it.

## The configuration

In order to make all the above code run properly, we will implement security.
To do so we will extend **WebSecurityConfigurerAdapter** in a configuration class.

### Configuration
{% gist https://gist.github.com/ErwanLT/27b00456d29c7b1799c4f69e19d8463e.js %}
As you can see in the first configure method, we indicate the roles who can access the endpoint.
In the second method, we describe the service that will be used to authenticate the user.

### Authentication Service

To authenticate our user we need to create a service that will implement the **UserDetailsService** from the [Spring Security](https://medium.com/javarevisited/top-10-courses-to-learn-spring-security-and-oauth2-with-spring-boot-for-java-developers-8f0222d6066d?source=---------5-----------------------) package, especially the method *loadUserByUsername*.
{% gist https://gist.github.com/ErwanLT/2ae4011f617e79e70ed2225a763a803a.js %}
## Testing our API

To test our API we need to first launch our application.
Then we can try to connect to the entry point that we created in our controller using [postman](https://medium.com/javarevisited/7-best-courses-to-learn-postman-tool-for-web-service-and-api-testing-f225c138fa5a?source=---------13------------------) or any other tool that permits you to make HTTP calls.

the examples will be the same as when we created the API, but with basic authentication.
In order to test my API, I have created 2 accounts that will be pre-loaded in the database.
{% gist https://gist.github.com/ErwanLT/49d9f1a5b49c0ae5d63ec64f326d4592.js %}
So now if I try to access a datapoint with bad credentials, i will have a [401 error](https://developer.mozilla.org/fr/docs/Web/HTTP/Status/401).

    {
      "timestamp": "2021-03-08T09:45:09.332+00:00",
      "status": 401,
      "error": "Unauthorized",
      "message": "Unauthorized",
      "path": "/kamino/order66"
    }

And if i try to access a datapoint when i don’t have the appropriate role, i will have a [403 error](https://developer.mozilla.org/fr/docs/Web/HTTP/Status/403).

![postman](https://cdn-images-1.medium.com/max/3276/1*XoDajP-iUhuuSZyhF9cOFA.png)

I have intercepted my 403 error in my exceptions handler to have something more readable than the exception stack trace.

Thanks for your reading time, as previously, the code used in this tutorial is findable in [this Github repository](https://github.com/ErwanLT/HumanCloningFacilities), branch security.