How to build a Rest API with Spring Boot using MySQL and JPA?

Build a Rest API with Spring Boot using MySQL and JPA

Build a Rest API with Spring Boot using MySQL and JPA

In that case, I found a very clean and elegant framework called Spring Boot to build a back end.

In that case, I found a very clean and elegant framework called Spring Boot to build a back end.

Previously, in JavaScript development, I used:

  1. Mongoose — an ORM (Object Relational Mapping) for Mongo DB
  2. Sequelize — an ORM for MySQL

For Java-related development, there are lot of ORM’s like Hibernate, JPA (Java Persistence API) & Java Object Oriented Querying.

I choose to build with JPA which is traditionally used in Java applications.

It was very interesting, and took about one week to finish as I had to learn Spring Boot (There are a lot of annotations “@” and other cool kinds of stuff to learn), JPA, and Hibernate along the way.

All this magic is mostly done by the annotations (“@” symbol) used in Spring Boot.

Creating a Spring Boot Maven Project

Let’s create a Spring Boot Maven Project Application using this link.

Maven” is a project management tool used to manage dependency management. It’s just like Node Package Manager (NPM) in the JS development environment.

We have package.json in NodeJS for dependency management and pom.xml in Spring Boot for dependency management.

In Group, write whatever the name you want. Usually, the domain name of the organization is written right to left.

For example our domain name is www.javaAPI.com, so the group name could be com.javaAPI.www

Then in the Artifact type the name of the folder you want.

On the right side, add the following dependencies:

  1. Mongoose — an ORM (Object Relational Mapping) for Mongo DB
  2. Sequelize — an ORM for MySQL

Then click “Generate Project”. You will find a rar file — extract it. Then open that folder in your favorite IDE.

Click on the com.rest.API and you will find an ApiApplication.java file as follows:

package com.rest.API;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ApiApplication {

public static void main(String[] args) {
      SpringApplication.run(ApiApplication.class, args);
   }
}

This code is enough to start your server. Normally spring boot runs on localhost:8080.

Type in your terminal as follows:

mvn spring-boot:run
See your localhost running in the web browser at port 8080. It looks blank as we haven’t done anything yet.

Let’s explore the files and their tags

If you have a look at the pom.xml file you may notice that the dependencies you put in when creating the application in Spring Initialize like MySQL, JPA, and Web will be inside a tag.

The starter and tester dependencies are the core for creating the Spring Boot Application to serve on the server.

Now, let’s move to APIApplication.java which is the main file.

package com.rest.API;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ApiApplication {

public static void main(String[] args) {
      SpringApplication.run(ApiApplication.class, args);
   }
}

Here the name of the package is in the first line of the code. Using that package name, you can import any class, method, or instances in another package file.

After that, two modules are imported from “org.springframework.boot” package.

  1. Mongoose — an ORM (Object Relational Mapping) for Mongo DB
  2. Sequelize — an ORM for MySQL

Since Spring boot is the latest application developing framework of Spring, it needs the packages of Spring Application as well as its specific packages.

After that @SpringBootApplication Annotation is used. This Annotation consists of annotation which is used in Spring:

  1. Mongoose — an ORM (Object Relational Mapping) for Mongo DB
  2. Sequelize — an ORM for MySQL

These are the annotations used to start the Spring Boot Application to run on a server.

Here is an article I have written about Annotation & their uses in Java.

Let’s create Model for our data

Let’s create a Model class to save, retrieve, update and delete the details of a book.

For that, I have to create a new package named model and inside that creating a Book.java class to put my code.

package com.rest.API.model;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;

@Entity
@Table(name = "books")

public class Book {
    @Id
    @GeneratedValue
    private Long id;

@NotBlank
    private String book_name;

@NotBlank
    private String author_name;

@NotBlank
    private String isbn;

public Book(){
        super();
    }

public Book(Long id, String book_name, String author_name, String isbn) {
        super();
        this.id = id;
        this.book_name = book_name;
        this.author_name = author_name;
        this.isbn=isbn;
    }

public Long getId() {
        return id;
    }

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

public String getBook_name() {
        return book_name;
    }

public void setBook_name(String book_name) {
        this.book_name = book_name;
    }

public String getAuthor_name() {
        return author_name;
    }

public void setAuthor_name(String author_name) {
        this.author_name = author_name;
    }

public String getIsbn() {
        return isbn;
    }

public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

}

Here I’m using JPA (Java Persistence API) which is a collection of classes and methods to continuously store data into a database.

@Entity — used to denote that this class is going to be an Entity in the database.

@Table — which takes some values like the name you are going to name your table

**@Id **— denotes that the id is the primary key / identifying key for this table

@NotBlank — is used to say that these attributes should not be blank.

Other than that there is an empty constructor which has a super method to satisfy the JPA customs. Getter and setter methods are usually in a POJO class (Plain old Java object).

Creating the Repository

Next, we are going to create a repository package to deal with database management in Java.

Create an Interface called BookRepository.java inside the repository package.

package com.rest.API.repository;

import com.rest.API.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

}

I have imported the JpaRepository package to use that repository in the BookRepository interface by connecting my most recently coded Book model to do CRUD operations.

There are already built-in methods in those repositories to do CRUD operations.

Eg:

.findAll() - to get All datas
.save()    - to save the got Data
.delete()  - to delete the data

Inside the <> tag we are taking the Model name we are going to use and the Primary key’s datatype.

@Repository: Annotation used to Indicate the DAO (Data Access Object) component in the persistence layer.

It tells the compiler that the interface is going to use the Repository to do database activities.

Creating Controller and Exception Handling

Create a new package called controller, andinside that create a BookController.java file which contains the endpoints.

package com.rest.API.controller;

import com.rest.API.exception.BookNotFoundException;
import com.rest.API.model.Book;
import com.rest.API.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import javax.validation.Valid;
import java.util.List;

@RestController
public class BookController {

@Autowired
    BookRepository bookRepository;

// Get All Notes
    @GetMapping("/books")
    public List<Book> getAllNotes() {
        return bookRepository.findAll();
    }

// Create a new Note
    @PostMapping("/books")
    public Book createNote(@Valid @RequestBody Book book) {
        return bookRepository.save(book);
    }

// Get a Single Note
    @GetMapping("/books/{id}")
    public Book getNoteById(@PathVariable(value = "id") Long bookId) throws BookNotFoundException {
        return bookRepository.findById(bookId)
                .orElseThrow(() -> new BookNotFoundException(bookId));
    }

// Update a Note
    @PutMapping("/books/{id}")
    public Book updateNote(@PathVariable(value = "id") Long bookId,
                           @Valid @RequestBody Book bookDetails) throws BookNotFoundException {

Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new BookNotFoundException(bookId));

book.setBook_name(bookDetails.getBook_name());
        book.setAuthor_name(bookDetails.getAuthor_name());
        book.setIsbn(bookDetails.getIsbn());

Book updatedBook = bookRepository.save(book);

return updatedBook;
    }

// Delete a Note
    @DeleteMapping("/books/{id}")
    public ResponseEntity<?> deleteBook(@PathVariable(value = "id") Long bookId) throws BookNotFoundException {
        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new BookNotFoundException(bookId));

bookRepository.delete(book);

return ResponseEntity.ok().build();
    }
}

The first imported package is for the Book Not Found exception (for which we are going to create a file in a bit).

Explanation of Annotations we used here:

  1. Mongoose — an ORM (Object Relational Mapping) for Mongo DB
  2. Sequelize — an ORM for MySQL

So what is Domain Object…?

It simply says that Domain Object == Business Object.

They are usually represented by entities and value objects related to the endpoint we are giving to get the data from the database.

  1. Autowired: This annotation is used to wire the bean classes automatically.

For that, you need to know about “What is a bean Class…?

Basically, a Java Bean Class is a simple class which encapsulates many objects into it.

This is an article I wrote on Java Bean Classes.

The following are the Mapping Annotations for the endpoints to perform CRUD Operations.

  1. GetMapping: This is an interface which contains the path of the endpoint to perform a Get method. This GetMapping interface uses the RequestMapping interface which can have the “path, value, params, headers” method to perform the Get method in earlier Spring versions.

Now it’s simplified by using GetMapping.

  1. PostMapping: This is an interface which contains the path of the endpoint to perform the Post method.

  2. PutMapping: This is an interface which contains the path of the endpoint to perform the Put method to Update.

  3. DeleteMapping: This is an interface which contains the path of the endpoint to perform the Delete method.

In the final lines, you probably noticed the “ResponseEntity” keyword.

What is that…??

It’s a Java class which inherits HttpEntity class to manipulate the HTTP Responses. Whether the request of the connection is “OK” or if there are any problems, throw an exception from the HttpEntity class.

orElseThrow(): This is a method found in the Optional class in Java8 which was introduced to handle Exceptions. The optional class provides various utility methods to check the presence or absence of an object, which helps to deal with NullPointerException.

orElseThrow is a method that Returns value if present, otherwise invokes an exception.

Creating a NotFoundException if there is no such book_id

As orElseThrow method throws a NotFound Exception. The following is the Exception Handling part. Create a BookNotFoundException.java file inside exception package.

package com.rest.API.exception;

public class BookNotFoundException extends Exception {

private long book_id;

public BookNotFoundException(long book_id) {
        super(String.format("Book is not found with id : '%s'", book_id));
        }

}

The created class extends the Superclass of Exception. In the constructor, I’m passing the book_id & prints the exception.

So, that’s it…

We have finished the REST API part. Now you can build the app (which was explained in Part 1) and do some Testings with Postman.

Connecting with MySql Database

Inside the application.properties of your resources folder, add the following:

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/library
spring.datasource.username = root //normally put your MySQL username 
spring.datasource.password = YOUR_MYSQL_PASSWORD

## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

That’s it.

We have built a basic REST API in Spring Boot. Congrats!

If anything is wrong or need to be corrected, please let me know in the comments section.

Happy Coding!

What is REST API? – The Complete Guide to RESTful APIs

What is REST API? – The Complete Guide to RESTful APIs

We have been using different applications and web pages to get data for various resources. However, have you ever thought, where does this data come from? . So in this article on What is REST API, let us look into how a client communicates with the servers to extract the required information.

The following topics will be covered in this article "What is REST API":

  • Need of REST API
  • What is REST API?
  • Principles of REST API
  • Methods of REST API
  • How to create a REST API?

Now, before I define REST API for you, let me take you through an example to make you understand the need of REST API.

Need of REST API

Consider a scenario where you are using the Book My Show app. Now, obviously, this application needs a lot of Input data, as the data present in the application is never static. Either it is movies getting released on a frequent basis, or various cities showing different languages movies at various times of the day. It’s never static which implies to the fact that data is always changing in these applications.

Now, where do you think we get this data from?

Well, this data is received from the Server or most commonly known as a Web-server. So, the client requests the server for the required information, via an API, and then, the server sends a response to the client.

Over here, the response sent to the client is in the form of an HTML Web Page. But, do you think this is an apt response that you would expect when you send a request?

Well, I am assuming the fact that you would say NO. Since, you would prefer the data to be returned in the form of structured format, rather than the complete Web page.

So, for such reasons, the data returned by the server, in response to the request of the client is either in the format of JSON or XML. Both JSON and XML format have a proper hierarchical structure of data.

Now, this sounds quite simple, right?

But, the only issue which is present in this framework till now is that you have to use a lot of methods to get the required information. To the fact, using these methods to retrieve information, becomes quite cumbersome when you require complex data.

So, this is where REST API comes into the picture. The REST API creates an object, and thereafter send the values of an object in response to the client.

Now, that you know the need of REST, next in this article, let us look into the What is REST API?

What is REST API?

REST suggests to create an object of the data requested by the client and send the values of the object in response to the user. For example, if the user is requesting for a movie in Bangalore at a certain place and time, then you can create an object on the server side.

So, over here, you have an object and you are sending the state of an object. This is why REST is known as Representational State Transfer.

If I have to define REST, then,  Representational State Transfer a.k.a REST is an architectural style as well as an approach for communications purpose that is often used in various web services development.

The architectural style of REST helps in leveraging the lesser use of bandwidth to make an application more suitable for the internet. It is often regarded as the “language of the internet” and is completely based on the resources.

To understand better, let’s dive a little deeper and see how exactly does a REST API work. Basically, the REST API breaks down a transaction in order to create small modules. Now, each of these modules is used to address a specific part of the transaction. This approach provides more flexibility but requires a lot of effort to be built from the very scratch.

So, now that you know what is REST API, let us next understand the constraints or principles which must be satisfied for an application to be regarded as REST API.

Principles of REST API

Well, there are six ground principles laid down by Dr. Fielding who was the one to define the REST API design in 2000. Below are the six guiding principles of REST:

Stateless

The requests sent from a client to a server will contain all the required information to make the server understand the requests sent from the client. This can be either a part of URL,  query-string parameters, body, or even headers. The URL is used to uniquely identify the resource and the body holds the state of the requesting resource. Once the server processes the request, a response is sent to the client through body, status or headers

Client-Server

The client-server architecture enables a uniform interface and separates clients from the servers. This enhances the portability across multiple platforms as well as the scalability of the server components.

Uniform Interface

To obtain the uniformity throughout the application, REST has the following four interface constraints:

  • Resource identification
  • Resource Manipulation using representations
  • Self-descriptive messages
  • Hypermedia as the engine of application state

Cacheable

In order to provide a better performance, the applications are often made cacheable. This is done by labeling the response from the server as cacheable or non-cacheable either implicitly or explicitly. If the response is defined as cacheable, then the client cache can reuse the response data for equivalent responses in the future.

Layered system

The layered system architecture allows an application to be more stable by limiting component behavior. This type of architecture helps in enhancing the application’s security as components in each layer cannot interact beyond the next immediate layer they are in. Also, it enables load balancing and provides shared caches for promoting scalability.

Code on demand

This is an optional constraint and is used the least. It permits a clients code or applets to be downloaded and to be used within the application. In essence, it simplifies the clients by creating a smart application which doesn’t rely on its own code structure.

Now, that you know the principles behind REST API, next let’s look into the Methods of REST API.

Methods of REST API

All of us working with the technology of the web, do CRUD operations. When I say CRUD operations, I mean that we create a resource, read a resource, update a resource and delete a resource. Now, to do these actions, you can actually use the HTTP methods, which are nothing but the REST API Methods. Refer below.

Now that you know what is a REST API and what all you need to mind in order to deliver an efficient application, let’s dive deeper and see the process of building REST API.

How to create a REST API?

In this practical demonstration, I will be creating a simple CRUD REST application using Node.js. To build this application, you will need to install the following:

  1. Node.js
  2. Express.js
  3. Joi
  4. nodemon (Node Monitor)

For this hands-on, I will be using the WebStorm IDE to write and execute the codes. You can use any IDE or code editor according to your choice. So, let’s get started.

Step 1: Create a project directory, which will consist of all the files present in the project. Then, open commands prompt and navigate to the project directory. Refer below.

Step 2: Now, call npm using the below command. This will initialize the npm modules in your system.

npm init

Once you hit enter, Node.js, will ask you to enter a few details related to the project. These details will basically be the metadata for your project. Refer below.

Here you can define your entry point along with several other information. For this demo, I will be using script.js as an entry point.

It will then, ask you for a confirmation for the data you must have mentioned. Just press on Y to confirm. Refer below.

Step 3: Next, you have yo install Express.js using the below command:

npm i express

Express is a web framework which can be used along with Node.js. This web framework will allow you to create Restful APIs, with the help of helper methods, middle layers to configure your application.

Step 3.1: Similarly, you have to install Joi.

npm i joi

This package allows you to create blueprints for JavaScript objects which store information to ensure validation of key information.

Step 3.2: Finally, install the node monitoring package nodemon, using the below command.

npm i -g nodemon

Nodemon, keeps a watch on all the files with any type of extension present in this folder. Also, with nodemon on the watch, you don’t have to restart the Node.js server each time any changes are made. Nodemon will implicitly detect the changes and restart the server for you.

package.json

{
"name": "restapidemo",
"version": "1.0.0",
"description": "Creation of REST API",
"main": "script.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "sahiti_kappagantula",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"joi": "^14.3.1"
}
}

script.js

const express = require('express'); //Import Express
const Joi = require('joi'); //Import Joi
const app = express(); //Create Express Application on the app variable
app.use(express.json()); //used the json file
 
//Give data to the server
const customers = [
{title: 'George', id: 1},
{title: 'Josh', id: 2},
{title: 'Tyler', id: 3},
{title: 'Alice', id: 4},
{title: 'Candice', id: 5}
]
 
//Read Request Handlers
// Display the Message when the URL consist of '/'
app.get('/', (req, res) => {
res.send('Welcome to Edurekas REST API!');
});
// Display the List Of Customers when URL consists of api customers
app.get('/api/customers', (req,res)=> {
res.send(customers);
});
// Display the Information Of Specific Customer when you mention the id.
app.get('/api/customers/:id', (req, res) => {
const customer = customers.find(c => c.id === parseInt(req.params.id));
//If there is no valid customer ID, then display an error with the following message
if (!customer) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;">Ooops... Cant find what you are looking for!</h2>');
res.send(customer);
});
 
//CREATE Request Handler
//CREATE New Customer Information
app.post('/api/customers', (req, res)=> {
 
const { error } = validateCustomer(req.body);
if (error){
res.status(400).send(error.details[0].message)
return;
}
//Increment the customer id
const customer = {
id: customers.length + 1,
title: req.body.title
};
customers.push(customer);
res.send(customer);
});
 
//Update Request Handler
// Update Existing Customer Information
app.put('/api/customers/:id', (req, res) => {
const customer = customers.find(c=> c.id === parseInt(req.params.id));
if (!customer) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;">Not Found!! </h2>');
 
const { error } = validateCustomer(req.body);
if (error){
res.status(400).send(error.details[0].message);
return;
}
 
customer.title = req.body.title;
res.send(customer);
});
 
//Delete Request Handler
// Delete Customer Details
app.delete('/api/customers/:id', (req, res) => {
 
const customer = customers.find( c=> c.id === parseInt(req.params.id));
if(!customer) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;"> Not Found!! </h2>');
 
const index = customers.indexOf(customer);
customers.splice(index,1);
 
res.send(customer);
});
//Validate Information
function validateCustomer(customer) {
const schema = {
title: Joi.string().min(3).required()
};
return Joi.validate(customer, schema);
 
}
 
//PORT ENVIRONMENT VARIABLE
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}..`));

Step 4: Now, the next step is to check whether the handlers are working properly or not. For that, we will use a Chrome extension called Postman. To install Postman you can visit here and click on ‘Add to Chrome’.

Step 5: Now, once you have installed Postman, open it to test your application.

Step 6: But before that you have to start your server. To start your server, type the following command.

node script.js

You would see the output as below:

Results

Let us start by testing the GET Method.

Step 7: In order to do that you need to select GET from the drop-down list, type in the defined URL and hit send.

If your code is working fine, then you will see the list of all the customers which we have added manually in our code. In the below picture, you can see how my result looks like. Here I have mentioned the URL to be localhost:8080/api/customers

Step 8: Now, let’s try adding a new customer to our stack of customers. For that, select ‘POST’ from the drop-down list and type in the defined URL for the POST method. Then, click on ‘Body’, select ‘raw’ and move on to select ‘JSON’ from the drop-down list as depicted in the below image. Now, in the text area, type in the name of your customer as shown and hit send.

If your POST method is working fine, your response body will contain the new customer’s name along with the Customer ID. Here if you observe, we have only mentioned the name but we did not give the customer ID. This implies that the Customer ID is automatically incremented

Step 9: Now, let’s try to update a Customer name. Let us say we ant to update the name of the Customer ID = 3. So, to update the data, you need to first select ‘PUT’ from the drop-down table and enter the PUT request’s URL along with the customer id you wish to update. Next in the ‘Body’, type in the new customer name and hit enter.

This will give you a response with the customer id and updated customer name.

Step 10: Finally, let’s send a ‘DELETE’ request to delete an existing record. For that select DELETE from the drop-down list and type in the URL of the delete request handler along with the customer’s details, you want to remove and hit enter. Let’s say, I want to delete the details of a customer with id = 3. If your transaction is successful, you will see the complete details of the entry you have removed in the response body.

Now, let’s send a GET request for our final list of customers.

As you can see from the above screenshot, the response body contains a total of five customers with the customer id 3 missing as we have already deleted that entry.





Spring REST API Security Tutorial: Using OAuth2 + MySQL

Spring REST API Security Tutorial: Using OAuth2 + MySQL

Let's secure our Spring REST API with OAuth2 and MySQL. REST easy knowing your APIs are secure after this tutorial.

Let’s secure our Spring REST API with OAuth2 and MySQL. We will store user credentials in the MySQL database, and client credentials will be stored in the in-memory database. Every client has its own unique client ID.

To secure our REST API, we will have to do the following things:

  • Configure Spring Security and the database.

  • Configure the authorization server and resource server.

  • Get an access token and a refresh token.

  • Get a protected Resource (REST API) using an access token.

Before we start, let's look at some basic concepts related to Spring Security OAuth2.

You may also like: Spring Security Tutorial: Simple Authentication with Spring Boot.

OAuth2 Roles

Resource Owner

A resource owner is a person (like an end-user) in an application that owns the service or security policy.

Resource Server

This is the resource server hosting the protected resource or service.

Client Application

The client application is the application requesting access to resources stored on the resource server. The client application also obtains authorization from the resource owner.

Authorization Server

The authorization server is the server authorizing the client app to access the resources of the resource owner.

Application

Let's start to secure our REST API endpoints.

First, we need to enable Spring Security to add the security feature in the application. To configure and enable Spring Security, the @EnableWebSecurity annotation is used.

By using @EnableGlobalMethodSecurity, we can easily secure our methods with Java configurations. Global method security will activate  @PreFilter@PostFilter , @PreAuthorize, and the @PostAuthorize  annotations if we want to use them.

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  UserDetailsServiceImpl userDetailsService;
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 
      .and().authorizeRequests().antMatchers("/oauth/token")
      .permitAll().anyRequest().authenticated();
  }
  @Bean
  public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setPasswordEncoder( bCryptPasswordEncoder() );
    provider.setUserDetailsService(userDetailsService);
    return provider;
  }
  @Bean
  public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
  }
  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider());
  }
}

Note:

  • Here, WebSecurityConfigurerAdapter  is used to customize security implementation.

  • Endpoint /OAuth/tpken is used to request a token (access or refresh).

  • We inject a custom implementation of UserDetailsService in order to retrieve user details from the database.

  • We use the defined BCryptPasswordEncoder bean for password encoding.

Now, we need to configure the authorization server. The @EnableAuhtorizationServer  annotation enables an authorization server. AuthorizationServerConfigurerAdapter  implements the  AuthorizationServerConfigurer, which provides all the necessary methods to configure an Authorization server. It also contains information about registered clients and possible access to scopes and grant types.

@Configuration
@EnableAuthorizationServer
public class OAuthConfiguration extends AuthorizationServerConfigurerAdapter {
  @Autowired
  @Qualifier("authenticationManagerBean")
  private AuthenticationManager authenticationManager;
  @Autowired
  UserDetailsService userDetailsService;
  @Override
  public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
  }
  @Override
  public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
      .withClient("fooClientId").secret("secret")
      .authorizedGrantTypes("password", "authorization_code", "refresh_token").scopes("read","write")
      .autoApprove(true);
  }
  @Override
  public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager).accessTokenConverter(defaultAccessTokenConverter())
      .userDetailsService(userDetailsService);
  }
  @Bean
  public TokenStore tokenStore(){
    return new JwtTokenStore(defaultAccessTokenConverter());
  }
  @Bean
  public JwtAccessTokenConverter defaultAccessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setSigningKey("123");
    return converter;
  }
}

Notes on the above configuration:

  • Registers a client with client-id ‘fooClientId’ and password ‘ secret’ and the roles and scope they are allowed.

  • Specifies authorized grant types (password, authorization_code, refresh_token).

  • Specifies the JwtTokenStore to store tokens.

Next, we need to configure the resource server. The @EnableResourceServer  annotation, applied on OAuth2 Resource Servers, enables a Spring Security filter that authenticates requests using an incoming OAuth2 token.

The class ResourceServerConfigurerAdapter implements the ResourceServerConfigure,  providing methods to adjust the access rules and paths that are protected by OAuth2 security.

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "resource-server-rest-api";
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID);
    }
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests().anyRequest().authenticated();
    }
}

Next, we need to update the application.properties to configure the MySQL database. Create the user_management schema in MySQL and add the user table to store user credentials with roles.

spring.datasource.url = jdbc:mysql://localhost:3306/user_management
spring.datasource.username = root
spring.datasource.password = root

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
server.port = 8080
Test Application

To access any secured REST API endpoint, first, we will have to get the access token. To get the access token, we will need to add an authorization header with client credentials and add the request body with user credentials in postman.

After receiving the access token and refresh token, we can access any secured REST API endpoints using access token. When the access token expired, the refresh token is used to get a new access token.

I have attached some of postmen request responses

getToken

getUser

addUser

You can refer to the whole project on GitHub.

Thank for reading. I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others

Originally published on dzone.com

Related Articles