Skip to main content

REST tutorial : security

Greetings!

So far we have created a nice looking REST API with Java tech stack. But it is missing a crucial piece. Security!!!

Complete source code, todoapp
$ git clone https://github.com/slmanju/todoapp.git
$ cd todoapp
$ git checkout security

Spring Security

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.
spring-security

Lets add spring security starter to our project.
compile('org.springframework.boot:spring-boot-starter-security')

$ gradle clean bootrun
$ curl -i http://localhost:8080/todos
You will get a message like this,
{"timestamp":1515304279482,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/todos"}

With just adding the library Spring has secured our application!

Have a look at the console log. You can see something like this,
Using default security password: fc55e01e-16b7-4344-b567-7d6fe90fcb32

Now try this,
$ curl -i -u user:fc55e01e-16b7-4344-b567-7d6fe90fcb32 http://localhost:8080/todos

We get our secured todos!

Spring boot provides us basic security. We only need to override as necessary.

Using username, password for each request is not an ideal for REST. So let's change this to use token based authentication.

Steps:

  • Handle unauthenticated request
  • Request a token
  • Request resource with the token
  • Token validation and set security context
  • Make it stateless
  • No form login/ logout
  • Secure with user roles

Code:




Test:

// request a token
$ curl -i -H "Content-Type: application/json" -X POST -d '{"username":"manjula","password":"password"}' http://localhost:8080/token

// receive token like this
{"token":"winteriscoming"}

// request with token
$ curl -i -H "Authorization":"winteriscoming" http://localhost:8080/todos


In this tutorial we have secured our REST API with a token. But still we can improve it. Let's do it in next tutorial.



Comments