TaskUserService Microservice

In this microservice, we can develop the microservice for responsible for managing the user-related operations such as user authentication, authorization and user profile management. In this service we can develop the USER and ADMIN role then admin can able to create the tasks and approve the tasks of the user.

We can create the project using Spring STS IDE and on creating the project adding the below dependencies into the project.

Dependencies:

  • Spring Web
  • Spring Security
  • Spring data for mongodb
  • Spring Dev tools
  • Lombok
  • Spring Actuator
  • Netflix Eureka client server
  • Zipkin server

Once created the project includes the above dependencies the file structure below image:

Open the application.properties file and put the below code for server post assigning and data bases configuration, spring security and eureka client server configuration into the project.

server.port=8081
spring.data.mongodb.uri=mongodb://localhost:27017/userData
spring.application.name=USER-SERVICE
eureka.instance.prefer-ip-address=true
eureka.client.fetch-registry=true
eureka.client.register-with-eureka=true
eureka.client.service-url.defaultZone = http://localhost:8085/eureka
# Session Management Configuration
spring.security.filter.chain.content-negotiation.parameter-strategy=ignore
spring.security.filter.chain.any-request.authorized=permitAll
spring.security.filter.chain.request-matcher.path.pattern=/api/**
spring.security.filter.chain.request-matcher.path.authenticated=true
#Zipkin server configuration
spring.zipkin.base-url=http://localhost:9411
spring.sleuth.sampler.probability=1.0

Step 1: Once completed the configuration of the database, eureka server, Spring security and Zipkin server. Create the one package in in.mahesh.tasks and named as usermodel and create the class named User into that package.

Go to src > java > in.mahesh.tasks > usermodel > User and put the code below:

Java




package in.mahesh.tasks.usermodel;
  
import java.util.List;
  
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
  
import com.fasterxml.jackson.annotation.JsonProperty;
  
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
  
@Document(collection = "user")
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
  
    @Id
    private String id;
    private String fullName;
    private String email;
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String password;
    private String role = "ROLE_CUSTOMER";
    private String mobile;
      
    private List<Long> completedTasks;
      
      
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public List<Long> getCompletedTasks() {
        return completedTasks;
    }
    public void setCompletedTasks(List<Long> completedTasks) {
        this.completedTasks = completedTasks;
    }
    public String get_id() {
        return id;
    }
    public void set_id(String id) {
        this.id = id;
    }
    public String getFullName() {
        return fullName;
    }
    public void setFullName(String fullName) {
        this.fullName = fullName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    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;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
      
}


Step 2: Create the one package in in.mahesh.tasks and named as repository and create the interface named UserRepository into that package.

Go to src > java > in.mahesh.tasks > repository > UserRepository and put the code below:

Java




package in.mahesh.tasks.repository;
  
  
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;
  
import in.mahesh.tasks.usermodel.User;
  
@Repository
public interface UserRepository extends MongoRepository<User,String> {
    @Query("{email :?0}")
    User findByEmail(String email);
      
  
}


Step 3: Create the one package in in.mahesh.tasks and named as service and create the class named UserService into that package.

Go to src > java > in.mahesh.tasks > service > UserService and put the code below:

Java




package in.mahesh.tasks.service;
  
import in.mahesh.tasks.exception.UserException;
import in.mahesh.tasks.usermodel.User;
  
import java.util.List;
  
  
public interface UserService {
  
       
     public List<User> getAllUser()  throws UserException;
       
     public User findUserProfileByJwt(String jwt) throws UserException;
       
     public User findUserByEmail(String email) throws UserException;
       
     public User findUserById(String userId) throws UserException;
  
     public List<User> findAllUsers();
       
           
     }


Step 4 : create the one more class in same package and it named as UserServiceImplementation into that package.

Go to src > java > in.mahesh.tasks > service > UserServiceImplementation and put the code below:

Java




package in.mahesh.tasks.service;
  
import in.mahesh.tasks.exception.UserException;
import in.mahesh.tasks.repository.UserRepository;
import in.mahesh.tasks.taskSecurityConfig.JwtProvider;
import in.mahesh.tasks.usermodel.User;
  
import java.util.List;
  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
  
  
  
@Service
public class UserServiceImplementation implements UserService {
  
    @Autowired
    private UserRepository userRepository;
      
    @Override
    public User findUserProfileByJwt(String jwt) throws UserException {
        String email= JwtProvider.getEmailFromJwtToken(jwt);
          
          
        User user = userRepository.findByEmail(email);
          
        if(user==null) {
            throw new UserException("user not exist with email "+email);
        }
        return user;
    }
      
      
    public List<User> getAllUser()  throws UserException{
        return userRepository.findAll();
          
    }
  
    @Override
    public User findUserByEmail(String email) throws UserException {
        User user=userRepository.findByEmail(email);
        return user;
    }
  
    @Override
    public User findUserById(String userId) throws UserException {
        // TODO Auto-generated method stub
java.util.Optional<User> opt = userRepository.findById(userId);
          
        if(opt.isEmpty()) {
            throw new UserException("user not found with id "+userId);
        }
        return opt.get();
    }
      
  
    @Override
    public List<User> findAllUsers() {
        // TODO Auto-generated method stub
        return userRepository.findAll();
    }
      
}


Step 5: Create the one more class in same package and it named as CustomerServiceImplementation into that package.

Go to src > java > in.mahesh.tasks > service > CustomerServiceImplementation and put the code below:

Java




package in.mahesh.tasks.service;
  
import in.mahesh.tasks.repository.UserRepository;
  
  
import in.mahesh.tasks.usermodel.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
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.Service;
  
  
import java.util.ArrayList;
import java.util.List;
  
  
@Service
public class CustomerServiceImplementation implements UserDetailsService {
  
    @Autowired
    private UserRepository userRepository;
      
    public CustomerServiceImplementation(UserRepository userRepository) {
        this.userRepository=userRepository;
    }
      
      
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByEmail(username);
        System.out.println(user);
         
        if(user==null) {
            throw new UsernameNotFoundException("User not found with this email"+username);
  
        }
  
          
        System.out.println("Loaded user: " + user.getEmail() + ", Role: " + user.getRole());
        List<GrantedAuthority> authorities = new ArrayList<>();
        return new org.springframework.security.core.userdetails.User(
                user.getEmail(),
                user.getPassword(),
                authorities);
    }
}


Step 6: Create the another package and it named as taskSecurityConfig and create the one class and it named as ApplicationConfig into that package.

Go to src > java > in.mahesh.tasks > taskSecurityConfig > ApplicationConfig and put the code below:

Java




package in.mahesh.tasks.taskSecurityConfig;
  
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
  
import java.util.Arrays;
import java.util.Collections;
  
@Configuration
public class ApplicatonConfig {
  
    @SuppressWarnings("deprecation")
    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeRequests(
                        authorize -> authorize.requestMatchers("/api/**")
                        .authenticated().anyRequest().permitAll())
                .addFilterBefore(new JwtTokenValidator(), BasicAuthenticationFilter.class)
                .csrf(csrf -> csrf.disable())
                .cors(cors -> cors.configurationSource(corsConfigurationSource()));
                //.httpBasic(Customizer.withDefaults())
                //.formLogin(Customizer.withDefaults());
        return http.build();
    }
  
    private CorsConfigurationSource corsConfigurationSource() {
        return new CorsConfigurationSource() {
            @Override
            public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
                CorsConfiguration ccfg = new CorsConfiguration();
                ccfg.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
                ccfg.setAllowedMethods(Collections.singletonList("*"));
                ccfg.setAllowCredentials(true);
                ccfg.setAllowedHeaders(Collections.singletonList("*"));
                ccfg.setExposedHeaders(Arrays.asList("Authorization"));
                ccfg.setMaxAge(3600L);
                return ccfg;
  
            }
        };
  
    }
  
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
  
}


Step 7: Create the one more class in that same package and it named as JwtProvider into that package.

Go to src > java > in.mahesh.tasks > taskSecurityConfig > JwtProvider and put the code below:

Java




package in.mahesh.tasks.taskSecurityConfig;
  
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
  
import javax.crypto.SecretKey;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
  
public class JwtProvider {
    static SecretKey key = Keys.hmacShaKeyFor(JwtConstant.SECRET_KEY.getBytes());
  
    public static String generateToken(Authentication auth) {
        Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
        String roles = populateAuthorities(authorities);
        @SuppressWarnings("deprecation")
        String jwt = Jwts.builder()
                .setIssuedAt(new Date())
                .setExpiration(new Date(new Date().getTime()+86400000))
                .claim("email", auth.getName())
                .claim( "authorities",roles)
                .signWith(key)
                .compact();
        System.out.println("Token for parsing in JwtProvider: " + jwt);
        return jwt;
  
    }
  
    private static String populateAuthorities(Collection<? extends GrantedAuthority> authorities) {
        Set<String> auths = new HashSet<>();
        for(GrantedAuthority authority: authorities) {
            auths.add(authority.getAuthority());
        }
        return String.join(",",auths);
    }
  
  
    @SuppressWarnings("deprecation")
    public static String getEmailFromJwtToken(String jwt) {
        jwt = jwt.substring(7); // Assuming "Bearer " is removed from the token
        try {
            //Claims claims=Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jwt).getBody();
            Claims claims = Jwts.parser().setSigningKey(key).build().parseClaimsJws(jwt).getBody();
            String email = String.valueOf(claims.get("email"));
            System.out.println("Email extracted from JWT: " + claims);
            return email;
        } catch (Exception e) {
            System.err.println("Error extracting email from JWT: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
  
}


Step 8: Create the one more class in that same package and it named as JwtTokenValidator into that package.

Go to src > java > in.mahesh.tasks > taskSecurityConfig > JwtTokenValidator and put the code below:

Java




package in.mahesh.tasks.taskSecurityConfig;
  
  
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
  
  
import javax.crypto.SecretKey;
import java.io.IOException;
import java.util.List;
  
public class JwtTokenValidator extends OncePerRequestFilter {
  
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jwt = request.getHeader(JwtConstant.JWT_HEADER);
        System.out.println("JWT Token in JwtTokenValidator: " + jwt);
        if (jwt != null && jwt.startsWith("Bearer ")) {
            jwt = jwt.substring(7);
              
            System.out.println("JWT Token in JwtTokenValidator: " + jwt);
            try {
                SecretKey key = Keys.hmacShaKeyFor(JwtConstant.SECRET_KEY.getBytes());
                @SuppressWarnings("deprecation")
                Claims claims = Jwts.parser().setSigningKey(key).build().parseClaimsJws(jwt).getBody();
                System.out.print(claims);
  
                String email = String.valueOf(claims.get("email"));
                System.out.print(email);
                String authorities = String.valueOf(claims.get("authorities"));
                List<GrantedAuthority> auth = AuthorityUtils.commaSeparatedStringToAuthorityList(authorities);
                Authentication authentication = new UsernamePasswordAuthenticationToken(email, null, auth);
                SecurityContextHolder.getContext().setAuthentication(authentication);
  
            } catch (Exception e) {
                throw new BadCredentialsException("Invalid token", e);
            }
        }
  
        filterChain.doFilter(request, response);
    }
}


Step 9: Create the one more class in that same package and it named as JwtConstant into that package.

Go to src > java > in.mahesh.tasks > taskSecurityConfig > JwtConstant and put the code below:

Java




package in.mahesh.tasks.taskSecurityConfig;
  
public class JwtConstant {
    public static final String SECRET_KEY = "wpembytrwcvnryxksdbqwjebruyGHyudqgwveytrtrCSnwifoesarjbwe";
    public static final String JWT_HEADER = "Authorization";
}


Step 10: Create the new package named as the controller and create the one class in that same package and it named as AuthController into that package.

Go to src > java > in.mahesh.tasks > controller > AuthController and put the code below:

Java




package in.mahesh.tasks.controller;
  
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import in.mahesh.tasks.exception.UserException;
import in.mahesh.tasks.repository.UserRepository;
import in.mahesh.tasks.request.LoginRequest;
import in.mahesh.tasks.response.AuthResponse;
import in.mahesh.tasks.service.CustomerServiceImplementation;
import in.mahesh.tasks.service.UserService;
import in.mahesh.tasks.taskSecurityConfig.JwtProvider;
import in.mahesh.tasks.usermodel.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
  
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
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("/auth")
public class AuthController {
  
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
  
     
    @Autowired
    private CustomerServiceImplementation customUserDetails;
      
    @Autowired
    private UserService userService;
  
  
  
    @HystrixCommand(fallbackMethod = "createUserFallback")
    @PostMapping("/signup")
    public ResponseEntity<AuthResponse> createUserHandler(@RequestBody User user) throws UserException {
        String email = user.getEmail();
        String password = user.getPassword();
        String fullName = user.getFullName();
        String mobile = user.getMobile();
        String role = user.getRole();
  
        User isEmailExist = userRepository.findByEmail(email);
        if (isEmailExist != null) {
            throw new UserException("Email Is Already Used With Another Account");
  
        }
        User createdUser = new User();
        createdUser.setEmail(email);
        createdUser.setFullName(fullName);
        createdUser.setMobile(mobile);
        createdUser.setRole(role);
        createdUser.setPassword(passwordEncoder.encode(password));
          
        User savedUser = userRepository.save(createdUser);
          userRepository.save(savedUser);
        Authentication authentication = new UsernamePasswordAuthenticationToken(email,password);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = JwtProvider.generateToken(authentication);
  
  
        AuthResponse authResponse = new AuthResponse();
        authResponse.setJwt(token);
        authResponse.setMessage("Register Success");
        authResponse.setStatus(true);
        return new ResponseEntity<AuthResponse>(authResponse, HttpStatus.OK);
  
    }
    public ResponseEntity<AuthResponse> createUserFallback(User user, Throwable throwable) {
        // Handle the fallback logic here
        // You can return a default response or log the error
        AuthResponse authResponse = new AuthResponse();
        authResponse.setMessage("User registration failed due to a temporary issue.");
        authResponse.setStatus(false);
        return new ResponseEntity<>(authResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  
  
  
    @HystrixCommand(fallbackMethod = "signinFallback")
    @PostMapping("/signin")
    public ResponseEntity<AuthResponse> signin(@RequestBody LoginRequest loginRequest) {
        String username = loginRequest.getemail();
        String password = loginRequest.getPassword();
  
        System.out.println(username+"-------"+password);
  
        Authentication authentication = authenticate(username,password);
        SecurityContextHolder.getContext().setAuthentication(authentication);
  
        String token = JwtProvider.generateToken(authentication);
        AuthResponse authResponse = new AuthResponse();
  
        authResponse.setMessage("Login success");
        authResponse.setJwt(token);
        authResponse.setStatus(true);
  
        return new ResponseEntity<>(authResponse,HttpStatus.OK);
    }
    public ResponseEntity<AuthResponse> signinFallback(LoginRequest loginRequest, Throwable throwable) {
        // Handle the fallback logic here
        // You can return a default response or log the error
        AuthResponse authResponse = new AuthResponse();
        authResponse.setMessage("Login failed due to a temporary issue.");
        authResponse.setStatus(false);
        return new ResponseEntity<>(authResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  
  
      
    private Authentication authenticate(String username, String password) {
  
        System.out.println(username+"---++----"+password);
  
        UserDetails userDetails = customUserDetails.loadUserByUsername(username);
  
        System.out.println("Sig in in user details"+ userDetails);
  
        if(userDetails == null) {
            System.out.println("Sign in details - null" + userDetails);
  
            throw new BadCredentialsException("Invalid username and password");
        }
        if(!passwordEncoder.matches(password,userDetails.getPassword())) {
            System.out.println("Sign in userDetails - password mismatch"+userDetails);
  
            throw new BadCredentialsException("Invalid password");
  
        }
        return new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
  
    }
}


Step 11: Create the one class in that same package and it named as UserController into that package.

Go to src > java > in.mahesh.tasks > controller > UserController and put the code below:

Java




package in.mahesh.tasks.controller;
  
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import in.mahesh.tasks.exception.UserException;
import in.mahesh.tasks.response.ApiResponse;
import in.mahesh.tasks.service.UserService;
import in.mahesh.tasks.usermodel.User;
  
import java.util.List;
  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
  
@RestController
@RequestMapping("/api/users")
public class UserController {
  
    @Autowired
    private UserService userService;
      
    public UserController(UserService userService) {
        this.userService = userService;
    }
  
  
    @HystrixCommand(fallbackMethod = "fallbackForGetUserProfile")
    @GetMapping("/profile")
    public ResponseEntity<User> getUserProfile(@RequestHeader("Authorization") String jwt) throws UserException {
          
        User user = userService.findUserProfileByJwt(jwt);
        user.setPassword(null);
        System.out.print(user);
        return new ResponseEntity<>(user, HttpStatus.OK);
    }
  
    public ResponseEntity<User> fallbackForGetUserProfile(String jwt, Throwable throwable) {
        // Handle the fallback logic here
        // For example, you can return a default user or a custom error message
        return new ResponseEntity<>(new User(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
  
    @HystrixCommand(fallbackMethod = "fallbackForFindUserById")
    @GetMapping("/api/users/{userId}")
    public ResponseEntity<User> findUserById(
            @PathVariable String userId,
            @RequestHeader("Authorization") String jwt) throws UserException {
  
        User user = userService.findUserById(userId);
        user.setPassword(null);
  
        return new ResponseEntity<>(user, HttpStatus.ACCEPTED);
    }
  
    public ResponseEntity<User> fallbackForFindUserById(String userId, String jwt, Throwable throwable) {
        // Handle the fallback logic here
        // For example, you can return a default user or a custom error message
        return new ResponseEntity<>(new User(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
  
  
    @HystrixCommand(fallbackMethod = "fallbackForFindAllUsers")
    @GetMapping("/api/users")
    public ResponseEntity<List<User>> findAllUsers(
  
            @RequestHeader("Authorization") String jwt)  {
  
        List<User> users = userService.findAllUsers();
  
  
        return new ResponseEntity<>(users, HttpStatus.ACCEPTED);
    }
    public ResponseEntity<List<User>> fallbackForFindAllUsers(String jwt, Throwable throwable) {
        // Handle the fallback logic here
        // For example, you can return an empty list or a custom error message
        return new ResponseEntity<>(List.of(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
  
  
    @GetMapping()
    public ResponseEntity<?> getUsers(@RequestHeader("Authorization") String jwt) {
        try {
            List<User> users = userService.getAllUser();
            System.out.print(users);
            return new ResponseEntity<>(users, HttpStatus.OK);
        } catch (Exception e) {
            // Log the exception or handle it based on your application's requirements
            return new ResponseEntity<>("Error retrieving users", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}


Step 12: Create the one class in that same package and it named as HomeController into that package.

Go to src > java > in.mahesh.tasks > controller > HomeController and put the code below:

Java




package in.mahesh.tasks.controller;
  
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
  
import in.mahesh.tasks.response.ApiResponse;
  
@RestController
public class HomeController {
      
    @GetMapping
    public ResponseEntity<ApiResponse> homeController(){
        ApiResponse res=new ApiResponse("Welcome To Task Management Microservice Project",true);
        return new ResponseEntity<ApiResponse>(res,HttpStatus.ACCEPTED);
    }
  
    @GetMapping("/users")
    public ResponseEntity<ApiResponse> userHomeController(){
        ApiResponse res=new ApiResponse("Welcome To Task Management User Service",true);
        return new ResponseEntity<ApiResponse>(res,HttpStatus.ACCEPTED);
    }
}


Step 13: Create the new package named as request and create the one class in that same package and it named as LoginRequest into that package.

Go to src > java > in.mahesh.tasks > request > LoginRequest and put the code below:

Java




package in.mahesh.tasks.request;
  
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.data.mongodb.core.mapping.Document;
  
@AllArgsConstructor
@NoArgsConstructor
@Document
public class LoginRequest {
  
    private String email;
    private String password;
  
    public String getemail() {
        return email;
    }
  
    public void setUsername(String email) {
        this.email = email;
    }
  
    public String getPassword() {
        return password;
    }
  
    public void setPassword(String password) {
        this.password = password;
    }
  
    public void setemail(String username) {
        // TODO Auto-generated method stub
        this.setUsername(username);
          
    }
}


Step 14: Create the new package named as response and create the one class in that same package and it named as AuthReponse into that package.

Go to src > java > in.mahesh.tasks > response > AuthReponse and put the code below:

Java




package in.mahesh.tasks.response;
  
  
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
  
@AllArgsConstructor
@NoArgsConstructor
public class AuthResponse {
    private String jwt;
    private String message;
    private Boolean status;
  
    public String getJwt() {
        return jwt;
    }
  
    public void setJwt(String jwt) {
        this.jwt = jwt;
    }
  
    public String getMessage() {
        return message;
    }
  
    public void setMessage(String message) {
        this.message = message;
    }
  
    public Boolean getStatus() {
        return status;
    }
  
    public void setStatus(Boolean status) {
        this.status = status;
    }
}


Step 15: Create the new package named as response and create the one class in that same package and it named as ApiReponse into that package.

Go to src > java > in.mahesh.tasks > response > ApiReponse and put the code below:

Java




package in.mahesh.tasks.response;
  
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
  
@Data
public class ApiResponse {
    private String message;
    private boolean status;
    public ApiResponse(String string, boolean b) {
        // TODO Auto-generated constructor stub
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public boolean isStatus() {
        return status;
    }
    public void setStatus(boolean status) {
        this.status = status;
    }
      
}


Step 16: Create the new package named as exception and create the one class in that same package and it named as UserException into that package.

Go to src > java > in.mahesh.tasks > exception > UserException and put the code below:

Java




package in.mahesh.tasks.exception;
  
public class UserException extends Exception {
      
    public UserException(String message) {
        super(message);
    }
  
}


Step 17: Open the main class and in that main class enables the Hystrix using @EnableHystrix annotation.

Java




package in.mahesh.tasks;
  
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
  
  
@SpringBootApplication
@EnableHystrix
public class TaskUserServiceApplication {
  
    public static void main(String[] args) {
        SpringApplication.run(TaskUserServiceApplication.class, args);
    }
  
}


Step 18: Once completed the TaskUserService Microservice after that run the application once runs the application successfully looks like the below image.

Endpoints of the TaskUserService microservice:

Endpoint Name

Method

Endpoint

Sign Up

POST

http://localhost:8081/auth/signUp

Sign In

POST

http://localhost:8081/auth/signin

Get Profile

GET

http://localhost:8081/api/users/profile

Get Profile by Id

GET

http://localhost:8081/api/users/{UserId}

Get All Users

GET

http://localhost:8081/users

SignUp:

Sign Token:

Sign Crediedentials:

Profile:

All profiles:

Create a Backend Task Management System using Microservices

Microservices is an architectural pattern, and its approach can be used in software development where the large applications are built as a collection of loosely coupled and independent deployable services. All microservices communicate with each other using a well-defined API, typically using lightweight protocols using HTTP.

Developing the backend task management system using microservices involves breaking down the smaller functionalities into independent services that can communicate with each other using the eureka server and implementing the API Gateway for routing client requests.

In this project, we can develop the 5 individual microservices and communicate with each other.

  • Task User Service
  • Task Creation Service
  • Task Submission Service
  • Eureka Server configuration
  • API Gateway

TaskUserService:

In this microservice, we can develop the microservice for responsible for managing the user-related operations such as user authentication, authorization and user profile management. In this service we can develop the USER and ADMIN role then admin can be able to create the tasks and approve the tasks of the user.

TaskCreationService:

In this microservice, we can develop the microservice for creating the task and modification of the tasks and assigning the users and one more thing only admin can create the tasks and user unable to create the tasks.

TaskSubmissionService:

In this microservice, we can develop the microservice can be manages the submission of the tasks by users and handles the related functionalities such as validation and processing.

EurekaServerConfiguration:

In this microservice, we can develop the microservice and it can be used to establish the communication of the microservices using eureka server using discovery client and server with communicates with each dynamically.

APIGatway:

In this microservice, we can develop the microservice and it can be used to API Gateway and establish the routing the client requests of the system.

Similar Reads

TaskUserService Microservice:

In this microservice, we can develop the microservice for responsible for managing the user-related operations such as user authentication, authorization and user profile management. In this service we can develop the USER and ADMIN role then admin can able to create the tasks and approve the tasks of the user....

TaskService Microservice

...

TaskSubmissionService Microservice:

...

EurekaServerConfiguration microservice:

...

APIGatway microservice:

...

Contact Us