Hands-On Full Stack Development with Spring Boot 2.0  and React
eBook - ePub

Hands-On Full Stack Development with Spring Boot 2.0 and React

Build modern and scalable full stack applications using the Java-based Spring Framework 5.0 and React

Juha Hinkula

Compartir libro
  1. 302 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Hands-On Full Stack Development with Spring Boot 2.0 and React

Build modern and scalable full stack applications using the Java-based Spring Framework 5.0 and React

Juha Hinkula

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Develop efficient and modern full-stack applications using Spring Boot and React 16

Key Features

  • Develop resourceful backends using Spring Boot and faultless frontends using React.
  • Explore the techniques involved in creating a full-stack app by going through a methodical approach.
  • Learn to add CRUD functionalities and use Material UI in the user interface to make it more user-friendly.

Book Description

Apart from knowing how to write frontend and backend code, a full-stack engineer has to tackle all the problems that are encountered in the application development life cycle, starting from a simple idea to UI design, the technical design, and all the way to implementing, testing, production, deployment, and monitoring. This book covers the full set of technologies that you need to know to become a full-stack web developer with Spring Boot for the backend and React for the frontend.

This comprehensive guide demonstrates how to build a modern full-stack application in practice. This book will teach you how to build RESTful API endpoints and work with the data access Layer of Spring, using Hibernate as the ORM. As we move ahead, you will be introduced to the other components of Spring, such as Spring Security, which will teach you how to secure the backend. Then, we will move on to the frontend, where you will be introduced to React, a modern JavaScript library for building fast and reliable user interfaces, and its app development environment and components.

You will also create a Docker container for your application. Finally, the book will lay out the best practices that underpin professional full-stack web development.

What you will learn

  • Create a RESTful web service with Spring Boot
  • Understand how to use React for frontend programming
  • Gain knowledge of how to create unit tests using JUnit
  • Discover the techniques that go into securing the backend using Spring Security
  • Learn how to use Material UI in the user interface to make it more user-friendly
  • Create a React app by using the Create React App starter kit made by Facebook

Who this book is for

Java developers who are familiar with Spring, but have not yet built full-stack applications

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Hands-On Full Stack Development with Spring Boot 2.0 and React un PDF/ePUB en línea?
Sí, puedes acceder a Hands-On Full Stack Development with Spring Boot 2.0 and React de Juha Hinkula en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in Java. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2018
ISBN
9781788993166
Edición
1

Securing and Testing Your Backend

This chapter explains how to secure and test your Spring Boot backend. We will use the database application that we created in the previous chapter as a starting point.
In this chapter, we will look into the following:
  • How to secure your Spring Boot backend with Spring Boot
  • How to secure your Spring Boot backend with JWT
  • How to test your backend

Technical requirements

The Spring Boot application that was created in previous chapters is necessary.

Spring Security

Spring Security (https://spring.io/projects/spring-security) provides security services for Java-based web applications. The Spring Security project started in 2003 and was previously named The Acegi Security System for Spring.
By default, Spring Security enables the following features:
  • An AuthenticationManager bean with an in-memory single user. The username is user and the password is printed to the console output.
  • Ignored paths for common static resource locations, such as /css, /images, and more.
  • HTTP basic security for all other endpoints.
  • Security events published to Spring ApplicationEventPublisher.
  • Common low-level features are on by default (HSTS, XSS, CSRF, and so forth).
You can include Spring Security in your application by adding the following dependency to the pom.xml file:
 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
When you start your application, you can see from the console that Spring Security has created an in-memory user with the username user. The user's password can be seen in the console output:
If you make a GET request to your API endpoint, you will see that it is now secure, and you will get a 401 Unauthorized error:
To be able to make a successful GET request, we have to use basic authentication. The following screenshot shows how to do it with Postman. Now, with authentication we can see that status is 200 OK and the response is sent:
To configure how Spring Security behaves, we have to add a new configuration class that extends the WebSecurityConfigurerAdapter. Create a new class called SecurityConfig in your application root package. The following source code shows the structure of the security configuration class. The @Configration and @EnableWebSecurity annotations switch off the default web security configuration and we can define our own configuration in this class. Inside the configure(HttpSecurity http) method, we can define which endpoints in our application are secured and which are not. We actually don't need this method yet because we can use the default settings where all endpoints are secured:
package com.packt.cardatabase;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {

}

}
We also can add in-memory users to our application by adding the userDetailsService() method into our SecurityConfig class. The following is the source code of the method and it will create an in-memory user with the username user and password password:
 @Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();

return new InMemoryUserDetailsManager(user);
}
The usage of in-memory users is good in the development phase, but the real application should save the users in the database. To save the users to the database, you have to create a user entity class and repository. Passwords shouldn't be saved to the database in plain text format. Spring Security provides multiple hashing algorithms, such as BCrypt, that you can use to hash passwords. The following steps show how to implement that:
  1. Create a new class called User in the domain package. Activate the domain package and right click your mouse. Select New | Class from the menu and give the name User to a new class. After that, your project structure should look like the following screenshot:
  1. Annotate the User class with the @Entity annotation. Add the class fields—ID, username, password, and role. Finally, add the constructors, getters, and setters. We will set all fields to be nullable and that the username must be unique, by using the @Column annotation. See the following User.java source code of the fields and constructors:
package com.packt.cardatabase.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, updatable = false)
private Long id;

@Column(nullable = false, unique = true)
private String username;

@Column(nullable = false)
private String password;

@Column(nullable = false)
private String role;

public User() {
}

public User(String username, String password, String role) {
super();
this.username = username;
this.password = password;
this.role = role;
}
The following is the rest of the User.java source code with the getters and setters:
 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;
}

public String getRole() {
return role;
}

public void setRole(String role) {
this.role = role;
}
}
  1. Create a new class called UserRepository in the domain package. Activate the domain package and right click your mouse. Select New | Class from the menu and give the name UserRepository to the new class.
  2. The source code of the repository class is similar to what we have done in the previous chapter, but there is one query method, findByUsername, that we need in the next steps. See the following UserRepository source code:
package com.packt.cardatabase.domain;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends CrudRepository<User, Long> {
User findByUsername(String username);
}
  1. Next, we create a class that implements the UserDetailsService interface provided by Spr...

Índice