Adding User Repository and Service Classes
Start course
Difficulty
Beginner
Duration
2h 34m
Students
234
Ratings
3.6/5
starstarstarstar-halfstar-border
Description

In this course, we will learn the concepts of microservice and spring framework with a focus on Spring Boot.

Learning Objectives

  • Understanding Spring Boot

Intended Audience

  • Beginner Java developers
  • Java developers interested in learning how to Build and Deploy RESTful Web Services
  • Java Developers who want to develop web applications using the Spring framework
  • Java Developers who want to develop web applications with microservices
  • Java Developers who wish to develop Spring Boot Microservices with Spring Cloud

Prerequisites

  • Basic Java knowledge
Transcript

Hello, my friends. In this video, we will add repository and service classes to our project so that we may do login operations. Let's get started. Before I begin, I want to emphasize that this is the most important video for this project because we will be conducting login and security operations together in this video. Therefore, I recommend that you watch this video very carefully and pay attention to every detail. Are you ready?

Let's begin. In the previous video, we defined our web config class and adjusted the default start pages. Now, we must define our repository and service class. First, we will sign in to our project with an email and password. For this, we need to access the user tables data. First, let's add a new package  and name it repositories. Now, for each entity, we need a repository interface. Let's add the first interface for the user, add new interface. Name will be UserRepository. This must extend JPA repositories. Now the JP.A repository needs two parameters. First one is entity. Our entity is user, the other one is ID variable type.

Open user entity. Look, our ID is integer. So, return to the repository and add integer as a parameter. Now navigate to the JPA repository interface and examine the methods available. These are our CRUD methods and we will call these in our service class. Now, return to the user repository interface. Now we'll define our CRUD operations one by one in this interface. In this project, I will make all CRUD operations. However, I do not want to add user or change the user page. Because my goal in this project is to educate creating a project structure with Spring, I will manually add two users to my table. I only need a user find method. Let's define find user by email. This will take a string parameter for email. Okay, done. This will be enough for the user repository. Let's define service. Add a new package and name it service. This package will hold our service and service implementation classes. Let's start by defining our user service. Because the login action is a security operation, I'd like to keep it in a separate package, and I want to use Spring security to secure login activities. Add a new package, name it security. Let's define our first service.

Add a new class and name it UserService. Implements from user detail service, Spring provides us this interface to find any user with a string parameter. First, we need to define the user repository. Add @Autowired annotation. Now, let's override the method. Now, in this method, we need a username but we don't have any, so we will use this method for our email. Throws UsernameNotFoundException. Now, we can call our fin() method. Now, we have to add the error state orElseThrow() in this, we have to define our message like this Email not Found. Now we have to return user with methods, we have to return org.springframework.security.core.userdetails.User(). The userdetails service provides us this model. Now let's add methods, getEmail(), getPassword().

I also want to use getAuthorities method. Let's define this in our UserService. First, we need roles, getRoles(). We will use these roles in the security configuration service to redirect user to the admin or employee page. Now, let's getAuthorities(). Okay, done. Now we can use this method in the return line. Done. Now we have to adjust redirect pages. I want to use the success handler of Spring. Add a new class in the config package and name it LoginSuccessHandler, implements SavedRequestAwareAuthenticationSuccessHandler. If you look into this class, you can see we have an onAction() method.

This means we have to override this method in our SuccessHandler. As you can see, we have three parameters in this method as Request, Response, and Authentication. First, we have to get the role from authentication. If there is a role, this means the role is admin, so I will use any match authentication.getAuthorities().stream.anyMatch. If role = admin hasRole will be true. Done. Now we need to redirect URL. Let's add a condition for role type. If has a role, this means we have to redirect to the admin page. redirectURL = "/AdminHome", else redirectURL = "/EmployeeHome" page. Now response.sendRedirect(redirectURL). Okay, done. This will be enough for the SuccessHandler. Now the last operation is security configurations for authentication operations. To make login operations work, first we need a web NBC config or adapter. Add a new class in the config package named WebSecurityConfig. Configuration, EnabledWebSecurity.

Now, we have to inject our services one by one. First userService, DataSource, LoginSuccessHandler. To ensure security, we must encrypt our password. We will do it in the following video. For now we have to use the encode crypt method. Okay, done. Let's add configureGlobal() method. We will get user details with this method so we will call userService. Done. Now it's time to override the configure() method. We will use Ant Matchers. The Ant Matches is a Spring Boot HTTP method  used to configure the URL paths from which the Spring Boot application security should permit requests based on the user's roles.

The Ant Matchers method is an overloaded method that receives both the HTTP request methods and the specific URLs as its arguments. Spring Boot uses Ant Matchers to protect URLs by binding patterns representing the applications endpoints to specific users. Then it either permits or denies access to these URLs based on the roles or permissions of the users. Okay, let's use it. Authorize request. Now, we can define Ant Matchers. First we have to add our folders, resources, webjars, and assets. PermitAll. Now, add a slash to the complete URL. Now we will define our authorizations. Ant Matchers admin, hasRole admin. With any request, redirect Login with authenticated. Login page. Now, we have to define the Login's page URL that we have to find in the login HTML page. Now, we need SuccessHandler or failureURL, permitAll. For logout we will define a new Ant Matcher.

URL will be logout. Let's leave cookies also. I also wish to use the rememberMe function with the help of a cookie. Okay, done. Now for validation time, I can use tokenRepository. Let's define persistent token repository. First create a token, setDataSource, return token implementation. Done. Let's adjust token validity time. Okay, done. Now our security configuration is also ready, so I think that's enough for this video. Let's take a break here. In the next video, we will add users to our database manually, and we will try the Login operation. So, I'll see you in the next video.

 

About the Author
Students
1985
Courses
64
Learning Paths
4

OAK Academy is made up of tech experts who have been in the sector for years and years and are deeply rooted in the tech world. They specialize in critical areas like cybersecurity, coding, IT, game development, app monetization, and mobile development.