Tag Archives: REST

Json Web Token: How to Secure Spring Boot REST API

In this post, I will show how to secure your spring boot based REST API. It has been more of a trend to secure REST APIs to avoid any unnecessary calls to public APIs. We will be using some Spring boot features for Spring security along with JSON WebTokens for authorization. You can learn more about basic authentication here.

User flow in this case is

  1. User logs in
  2. We validate user credentials
  3. A token is sent back to user agent.
  4. User tries to access a protected resource.
  5. User sends JWT when accessing the protected resource. We validate JWT.
  6. If JWT is valid, we allow the user to access the resource.

JSON WebTokens, known as JWTs are used for forming authorization for users. This helps us to build secure APIs and it is also easy to scale. During authentication, a JSON web token is returned. Whenever the user wants to access a protected resource, the browser must send JWTs in the Authorization header along with the request. One thing to understand here is that it is a good security practice to secure REST API.

Basically, we will show

  1. Verify JSON WebToken
  2. Validate the signature
  3. Check the client permissions

What you will need?

  1. Java 8,
  2. MySQL Database
  3. IntelliJ Editor
  4. Gradle

Note – This won’t be a full-fledged app, but REST APIs based on Spring Boot, and Spring security.

Spring Boot Based REST API

Since I have already shown this before on my blog, I won’t be creating any new APIs. I will be securing REST API for company that I created in this blog post REST API. This API also includes caching. A user will try to access /cachedemo/v1/companies/ and since APIs are protected, he will get a response like below:

Secure REST API - Forbidden

Response from protected API

Now we will implement how to protect this API and how to access it.

Adding User and User Registration

Since we want to add authorization for APIs, we will need where the user is able to log in and send credentials. These credentials will be validated and a token will be generated. This token then will be transmitted in a request to an API call. The token will be validated in the Spring security authorization filter that we will add. If a valid token, the user will be able to access the API.

Create a user model


package com.betterjavacode.models;

import javax.persistence.*;
import java.io.Serializable;

@Entity(name = "User")
@Table(name = "user")
public class User implements Serializable
{
    public User()
    {

    }

    @Id
    @GeneratedValue(strategy =  GenerationType.IDENTITY)
    private long id;

    @Column(name = "username")
    private String username;

    @Column(name = "password")
    private String password;

    public long getId()
    {
        return id;
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }
}

We will add a controller where a user can register with its details for username and password.


package com.betterjavacode.resources;

import com.betterjavacode.models.User;
import com.betterjavacode.repositories.UserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/cachedemo/v1/users")
public class UserController
{
    private UserRepository userRepository;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public UserController(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder)
    {
        this.userRepository = userRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @PostMapping("/signup")
    public void signUp(@RequestBody User user)
    {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }

}

Now when we POST a request to /cachedemo/v1/users/signup , a user will be saved in the database. Password for the user will be saved in encrypted format as we are using BCryptPasswordEncoder. We will show how a user can log in to create a token.

User Login

To handle user login, we will add an AuthenticationFilter which will get added in FilterChain and Spring boot will handle the execution of it appropriately. This filter will look like below:


package com.betterjavacode.SpringAppCache;


import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter
{
    private AuthenticationManager authenticationManager;

    public AuthenticationFilter(AuthenticationManager authenticationManager)
    {
        this.authenticationManager = authenticationManager;
        setFilterProcessesUrl("/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException
    {
        try
        {
            com.betterjavacode.models.User creds = new ObjectMapper().readValue(request.getInputStream(), com.betterjavacode .models.User.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(), creds.getPassword(),new ArrayList<>()));
        }
        catch(IOException e)
        {
            throw new RuntimeException("Could not read request" + e);
        }
    }

    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, Authentication authentication)
    {
        String token = Jwts.builder()
                .setSubject(((User) authentication.getPrincipal()).getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + 864_000_000))
                .signWith(SignatureAlgorithm.HS512, "SecretKeyToGenJWTs".getBytes())
                .compact();
        response.addHeader("Authorization","Bearer " + token);
    }
}

Basically, a user will send credentials in a request to URL ending with /login . This filter will help to authenticate the user, if there is successful authentication, a Token will be added in response header with the key Authorization.

Token Validation and Authorization

We add another filter AuthorizationFilter to validate the token that we passed through AuthenticationFilter earlier. This filter will look like below:


package com.betterjavacode.SpringAppCache;

import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;


public class AuthorizationFilter extends BasicAuthenticationFilter
{
    public AuthorizationFilter(AuthenticationManager authenticationManager)
    {
        super(authenticationManager);
    }

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException
    {
        String header = request.getHeader("Authorization");
        if(header == null || !header.startsWith("Bearer"))
        {
            filterChain.doFilter(request,response);
            return;
        }

        UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(request);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request)
    {
        String token = request.getHeader("Authorization");
        if(token != null)
        {
            String user = Jwts.parser().setSigningKey("SecretKeyToGenJWTs".getBytes())
                    .parseClaimsJws(token.replace("Bearer",""))
                    .getBody()
                    .getSubject();
            if(user != null)
            {
                return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
            }
            return null;
        }
        return null;
    }
}

If the validation of the token is successful, the application returns a user and assigns it to a security context.

To enable Spring security, we will add a new class WebSecurityConfiguration with annotation @EnableWebSecurity. This class will extend the standard WebSecurityConfigurerAdapter . In this class, we will restrict our APIs and also add some whitelisted URLs that we will need to access without any authorization token. This will look like below:


package com.betterjavacode.SpringAppCache;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter
{
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    private UserDetailsService userDetailsService;

    private static final String[] AUTH_WHITELIST = {
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**"
    };

    public WebSecurityConfiguration(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder)
    {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.userDetailsService = userDetailsService;
    }


    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(AUTH_WHITELIST).permitAll()
                .antMatchers(HttpMethod.POST, "/cachedemo/v1/users/signup").permitAll()
                .anyRequest().authenticated()
                .and().addFilter(new AuthenticationFilter(authenticationManager()))
                .addFilter(new AuthorizationFilter(authenticationManager()))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception
    {
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource()
    {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}

In method configure we have restricted most APIs, only allowing Swagger URLs and signup URL. We also add filters to HttpSecurity. We will add our own UserDetailsServiceImpl class to validate user credentials.


package com.betterjavacode.services;

import com.betterjavacode.models.User;
import com.betterjavacode.repositories.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class UserDetailsServiceImpl implements UserDetailsService
{
    private UserRepository userRepository;

    public UserDetailsServiceImpl(UserRepository userRepository)
    {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        User user = userRepository.findByUsername(username);
        if(user == null)
        {
            throw new UsernameNotFoundException(username);
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), Collections.emptyList());
    }
}

Demo

With all the code changes, now we are ready to create a user, login and access secured REST APIs. From the image above, a user gets Access Denied error for accessing secured APIs. To demo this, I have already registered a user with username `test1` and password test@123.

Secure REST API - send use credentials to login

This POST request will give us Authorization token in response as shown above. Now using this token in our GET request to retrieve companies data. This GET request will look like below:

Secure REST API - Postman call

In this way, we showed how to secure REST API using JSON web token.

I will be launching the book “Simplifying Spring Security“. Do you want to get updates on launch? Sign up

References

  1. Implementing JWTs Authentication on Spring Boot API – JWT Authentication
  2. How to secure REST APIs – Secure REST APIs

Design of REST API for web application

One reason I like to build an application in public is that it keeps me accountable. I can’t run away. If I don’t finish something, it’s ok. At least, I will have something done to show to people. Building in public is not a new idea, a lot of people have used it. In this post, I discuss the design of REST API for Social KPI.

In the previous post here, we discussed the architecture of the application we are building.  This will be an ongoing process as we continue to build our application and evolve.

We will follow the following tips to design REST APIs

  1. We will use Resource to represent object for REST APIs
  2. API endpoint will represent a resource object in the plural. Example – companies, users
  3. We will use HTTP status codes for success or failure of the request
  4. We will use JSON object to represent a response
  5. And we will use versioning to represent a version of APIs

As discussed in the previous post application idea, we will have APIs for companies, users of those companies, customers, clicks, engagements data. While concluding this short post, I want to say that the next post will include database design as well as URL design for REST APIs.

We will be using Spring Boot to build REST API.

In conclusion, I discussed the design of the REST API for the web application Social KPI. If you want to follow the progress, subscribe here.

How To: AngularJS User Interface to CRUD Spring Boot REST API

In this post, we will add an user interface using AngularJS to the REST api we created here.

Controller for home page

First we will create a controller in Spring Boot rest API to call our home page. All the requests that will come to web server, will go through this controller and the controller will return a home page for the request based on path.

MainController.java will look like below:

package com.betterjavacode.benefits.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MainController 
{

     public static final Logger LOGGER = LogManager.getLogger(MainController.class);

     @RequestMapping(value = "/home", method = RequestMethod.GET)
     public String homepage() 
     {
         LOGGER.info(" Enter >> homepage() ");
         return "index";
     }
}

Any request coming to https://localhost:8443/home will return a page from index.html.

Create a Home Page

Now, we will create an index.html page. We will also be using angular JS framework as part of this home page so that we can build a single page application. If you are not aware of Angular JS or new to this framework, you can read about it AngularJS. One thing to remember while creating this page is a directory structure. Lot of issues that arise to create html pages are because of directory structure. Directory structure will look like below:

directorystructure

The home page index.html page is under main/resources/templates/ directory and it looks like below

<html ng-app="benefitApp">

<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /><title>Benefit Application</title>

<script>document.write('<base href="' + document.location + '" />');</script>

<link rel="stylesheet" href="/css/bootstrap.css" />

<script src="https://code.angularjs.org/1.6.1/angular.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-resource.js"></script>

<script type="text/javascript" src="./js/app.js"></script>

</head>

<body ng-controller="MainCtrl">

Hello {{name}}!
<div>
<ul class="menu">
<li><a href="listUser">user-list</a></li>
<li><a href="listCompany">company-list</a></li>
</ul>
<div ng-view="ng-view"></div>
</div>
</body></html>

Home page shows that this is an angular app with name benefitApp. This also declares a controller MainCtrl with an angular view. Important to see we are importing angular.js, angular-route.js and angular-resource.js modules. Click on user-list or company-list, will show list of users and list of companies respectively.

Create a controller

Now to handle the controller (MainCtrl), we added in index.html, we will add app.js which will declare the controller. This javascript file also contains config data to handle all the routing of pages. That’s why we will be importing “ngRoute” and “ngResource” angular modules.

var app = angular.module('benefitApp', ['ngRoute','ngResource']);

var app = angular.module('benefitApp', ['ngRoute','ngResource']);
app.controller('MainCtrl', function($scope, $routeParams) {

$scope.name = 'World';

$scope.$routeParams = $routeParams;

})

 

Through out the interaction on web pages, we will be using different controllers for editing user or company information and creating user or company. The same file app.js will also handle routing of these pages which is shown below

app.config(function($routeProvider,$locationProvider) {

$locationProvider.html5Mode(true);

$routeProvider.when('/listUser',

{templateUrl: 'views/listUser.html', controller: 'userController'});

$routeProvider.when('/listCompany',

{templateUrl: 'views/listCompany.html', controller: 'companyController'});

$routeProvider .when('/editUser/:userId',

{ templateUrl : 'views/editUser.html' }) ;

$routeProvider .when('/editCompany/:companyId',

{ templateUrl : 'views/editCompany.html' }) ;

$routeProvider.when('/createUser',

{templateUrl:'views/createUser.html'});

$routeProvider.when('/createCompany',

{templateUrl:'views/createCompany.html'});

});

Rest of the code showing all controllers’ logic has been skipped for post purposes. It is available on github repository.

UserController or CompanyController are calling rest apis which we have built using Spring boot.

Demo

Now build the code and run our embedded tomcat webserver. Fire up the url https://localhost:8443/home – it will look like below:

Home Page created with AngularJS for CRUD REST API

Click on user-list and it will show list of users inside the same page as below:

List of User Page created with AngularJS

Click on edit button and we will see a form to update user information:

edituserpage

Download –

In this post, we showed how to create a simple CRUD user interface using angular JS for Spring Boot REST API. The code for this is available in repository

 

Consuming a RESTful Webservice – Part IV

Continuing the series of posts on Spring Boot, in this post, we will investigate how to consume a REST API service we built previously. This will be a short post on how to use Rest Template to call REST service. We will show how to read the data and how to post the data with some of the features Spring Boot offers to consume a REST service for the client-side.

The eventual goal is to use this feature to call our rest service during runtime to use the data from the database to display on views that a user will be able to see.

You can read previous posts on this series Part I, Part II, and Part III.

Purpose

The purpose of this post is to read company data from Company REST API and also to create a company by posting company data using the same REST API.

Build a client with Rest Template

To consume a rest service programmatically, Spring provides a feature called RestTemplate. RestTemplate is the easiest way for a client to interact with the server-side code with just one line of code.

In our client code, we will need a RestTemplate object, REST service URL. Since this is a sample we are building, we will be adding the main method in this class to run this client side of the code. In real-life scenarios, during runtime, client code will call the rest template to get server-side data, and use that data to massage or display to the user on the user interface.

 

RestTemplate restTemplate = new RestTemplate();
String resourceAPI_URL = "http://localhost:8080/benefits/v1/companies/{id}";
Company company = restTemplate.getForObject(resourceAPI_URL, Company.class, 1);

This code is showing that we are calling REST service to read company data for a company with id that a client will pass.

Similarly, we will have another request to post the data on the server side to create a company. The code for that will look like below:

String resourceAPI_POSTURL = "http://localhost:8080/benefits/v1/companies/";

Company comp = new Company();

comp.setName("XYZ Company");
comp.setStatusid(1);
comp.setType("Corporation");
comp.setEin("9343423232");

Company newcomp = restTemplate.postForObject(resourceAPI_POSTURL, comp, Company.class);

In this post, we showed how to use RestTemplate a feature that Spring Boot provides to consume a REST service. The code for this is available here

Home » REST

 

Error Handling and Logging in Spring Boot REST API – Part III

In previous posts, I wrote about how to create a spring boot REST API Part I and how to add swagger documentation for REST API Part II. In this post, we will add error handling and logging to our REST API. Error handling and Logging are two different ideas, so I will divide this post in two sections.

1. Logging

In most production applications, logging is critical and it is used for multiple purposes. Few of those uses are debugging the production issues or auditing for the application. Over the years, different logging libraries have evolved to use in java based applications. slf4j is the most popular framework as it provides a simple abstraction layer to any kind of logging framework.

In our tutorial for this application, we will be using log4j2 which is the most recent and advance logging library out there. It provides lot of useful features for performance, support for multiple APIs, advance filtering, automatic reloading of configurations etc. We will not cover any of these in this article, if you are interested to read about log4j2 libraries, read here.

Add log4j2 library in application –

To use log4j2, we will add the maven dependency to our project’s pom file. This should look like below

 <dependency>
 <groupId>org.apache.logging.log4j</groupId>
 <artifactId>log4j-api</artifactId>
 </dependency>
 <dependency>
 <groupId>org.apache.logging.log4j</groupId>
 <artifactId>log4j-core</artifactId>
 </dependency>

Add log4j2 configuration file

To enable logging, we will have to add a configuration file in our application. This configuration file can be XML, JSON or YAML file. We will be using a XML file log4j2.xml which will look like below

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
 <Appenders>
 <Console name="Console" target="SYSTEM_OUT">
 <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
 </Console>
 <File name="BenefitsFile" fileName="benefits.log" append="true">
 <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
 </File>
 </Appenders>
 <Loggers>
 <Root level="debug">
 <AppenderRef ref="Console" />
 <AppenderRef ref="BenefitsFile"/>
 </Root>
 </Loggers>
</Configuration>

So we are using Console  and BenefitsFile as two loggers which will log into a console and file respectively. We are setting log level to DEBUG. If you log any messages with a level lower than DEBUG, they will be logged into console or file. We will have to add a file benefits.log in classpath to achieve this logging in file. Log pattern is with date time, log level, class from which log is originating and log message.

Add logging in application code

Once we have required logging libraries and logging configuration adjusted, we can add logging in our code to capture this logging during runtime execution. In one of the managers CompanyManagerImpl, we will add a logger.

public static final Logger LOGGER = LogManager.getLogger(CompanyManagerImpl.class);

@Override
public List<Company> getAllCompanies()
{
  LOGGER.info(" Enter >> getAllCompanies() ");
  List<Company> cList = (List<Company>) companyRepository.findAll();
  LOGGER.info(" Exit << getAllCompanies() ");
  return cList;
}

Now once we execute our spring boot application, we can capture the logs in console or file. The file will be benefits.log.

2. Error Handling

We will not write about exceptions in detail as it has been covered in this post Exceptions. We will create our own custom exception which will be extended from WebApplicationException which jersey library provides.

This will look like below:

package com.betterjavacode.benefits.utilities;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

public class InvalidRequestException extends WebApplicationException 
{

  /**
  *
  */
  private static final long serialVersionUID = 1L;
  private int errorcode = 00; // 00 indicates - no error

  public InvalidRequestException() 
  {

  }

  public InvalidRequestException(int errorcode, String message) 
  {
    super(Response.status(Response.Status.BAD_REQUEST).entity(message).build());
    this.errorcode = errorcode;
  }

  public InvalidRequestException(int errorcode, String message, Throwable cause) 
  {
     super(cause, Response.status(Response.Status.BAD_REQUEST).entity(message).build());
     this.errorcode = errorcode;
  }
}

Now we can use this custom exception in our managers when we want to throw an error message to indicate if there is anything wrong with client request. Similarly we can build another exception to show if there is anything wrong on server side. Following snippet shows from CompanyManagerImpl where we have shown how to throw this exception.

@Override
public Company getCompany(int guid) 
{
  LOGGER.info(" Enter >> getCompany() ");
  Company company = companyRepository.findOne(guid);
  if (company == null) {
    LOGGER.info(" Exit << createCompany() ");
    throw new InvalidRequestException(400, "Company not found");
  }
  LOGGER.info(" Exit << getCompany() ");
  return company;
}

In this post, we showed how to handle logging and errors in a REST API. The code for this is available on github repository.