Spring Boot Regsiter And Login With Angular Part 1

Getting Started | Building an Application with Spring Boot






In this tutorial we show some nice features of Spring Security, Spring Boot and Angular working together to provide a pleasant and secure user experience. It should be accessible to beginners with Spring and Angular, but there also is plenty of detail that will be of use to experts in either. This is actually the first in a series of sections on Spring Security and Angular, with new features exposed in each one successively. We’ll improve on the application in the second and subsequent installments, but the main changes after this are architectural rather than functional.


Create new Spring boot project:

We are going to step through creating this application in some detail, so that anyone who isn’t completely au fait with Spring and Angular can follow what is happening.

I will use Eclipse Ide for develop this project Eclipse IDe Download


Spring Boot Architecture



Spring Boot is a module of the Spring Framework. It is used to create stand-alone, production-grade Spring Based Applications with minimum efforts. It is developed on top of the core Spring Framework.



pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>register-login</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>register-login</name>
<description>Demo project for Spring Boot register-login</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.0.Final</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>


We need to create database name it register-login

src/main/resources/application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/register-login?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

spring.datasource.username=root

spring.activemq.password=

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

spring.jpa.hibernate.ddl-auto=create-drop

server.port=8080

registerlogin.app.jwtSecret=programmingWithDrmas

registerlogin.app.jwtExpiration=86400



Class Diagram



First We Will Create a package model inside it We will add java classes

- User class

- Role class

- RoleName enum

src/main/java/registerlogin/model/User.java):

       
                 
package registerlogin.model; import java.util.HashSet; import java.util.Set; import javax.persistence.*; import java.util.Date; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import org.hibernate.annotations.NaturalId; @Entity @Table(name = "users", uniqueConstraints = { @UniqueConstraint(columnNames = { "username" }), @UniqueConstraint(columnNames = { "email" }) }) public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank @Size(min=3, max = 50) private String name; @NotBlank @Size(min=3, max = 50) private String username; @NaturalId @NotBlank @Size(max = 50) @Email private String email; @NotBlank @Size(min=6, max = 100) private String password; private String gender; private String birthDate; @Temporal(TemporalType.TIMESTAMP) private Date createAt; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<Role> roles = new HashSet<>(); public User() {} public User(@NotBlank @Size(min = 3, max = 50) String name, @NotBlank @Size(min = 3, max = 50) String username, @NotBlank @Size(max = 50) @Email String email, @NotBlank @Size(min = 6, max = 100) String password, String gender, String birthDate, Date createAt) { super(); this.name = name; this.username = username; this.email = email; this.password = password; this.gender = gender; this.birthDate = birthDate; this.createAt = createAt; } 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 getName() { return name; } public void setName(String name) { this.name = name; } 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 getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getBirthDate() { return birthDate; } public void setBirthDate(String birthDate) { this.birthDate = birthDate; } public Date getCreateAt() { return createAt; } public void setCreateAt(Date createAt) { this.createAt = createAt; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } }

src/main/java/registerlogin/model/Role.java):



package registerlogin.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.NaturalId; @Entity @Table(name = "roles") public class Role { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Enumerated(EnumType.STRING) @NaturalId @Column(length = 60) private RoleName name; public Role() {} public Role(RoleName name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public RoleName getName() { return name; } public void setName(RoleName name) { this.name = name; } }

src/main/java/registerlogin/model/RoleName.java):

       
package registerlogin.model; public enum RoleName { ROLE_ADMIN, ROLE_USER }

JPA Repositories:

Create an interface with the name UserRepository and extends the JpaRepository class. We have to pass two parameters: type of the entity that it manages and the type of the Id field.

In this interface We will create three methods.

-findByUsername

-existsByUsername

-existsByEmail

src/main/java/registerlogin/model/UserRepository.java):

       
              
package registerlogin.repository; import org.springframework.data.jpa.repository.JpaRepository; import registerlogin.model.User; import java.util.Optional; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByUsername(String username); Boolean existsByUsername(String username); Boolean existsByEmail(String email); }

src/main/java/registerlogin/model/RoleRepository.java):

       
             
package registerlogin.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import registerlogin.model.Role; import registerlogin.model.RoleName; @Repository public interface RoleRepository extends JpaRepository<Role, Long> { Optional<Role> findByName(RoleName roleName); }

We need another package message inside it two packages Request and Response.

In the request package we created two classes LoginForm and SignUpForm


src/main/java/registerlogin/message/request/LoginForm.java):

       
            
package registerlogin.message.request; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; public class LoginForm { @NotBlank @Size(min=3, max = 60) private String username = "Drmas"; @NotBlank @Size(min = 6, max = 40) private String password = "password123"; 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; } }

src/main/java/registerlogin/message/request/SignUpForm.java):

       
           
package registerlogin.message.request; import java.util.Date; import java.util.Set; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.*; public class SignUpForm { @NotBlank @Size(min = 3, max = 50) private String name; @NotBlank @Size(min = 3, max = 50) private String username; @NotBlank @Size(max = 60) @Email private String email; private Set<String> role; @NotBlank @Size(min = 6, max = 40) private String password; private String gender; private String birthDate; @Temporal(TemporalType.TIMESTAMP) private Date createAt; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } 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 Set<String> getRole() { return role; } public void setRole(Set<String> role) { this.role = role; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getBirthDate() { return birthDate; } public void setBirthDate(String birthDate) { this.birthDate = birthDate; } public Date getCreateAt() { return createAt; } public void setCreateAt(Date createAt) { this.createAt = createAt; } }

And In the response package we created two classes JwtResponse and ResponseMessage

src/main/java/registerlogin/message/response/ResponseMessage.java):

 
          
package registerlogin.message.response; public class ResponseMessage { private String message ; public ResponseMessage(String message) { this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }

src/main/java/registerlogin/message/response/JwtResponse.java):

  
         
package registerlogin.message.response; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; public class JwtResponse { private String token; private String type = "Bearer"; private String username; private Collection<? extends GrantedAuthority> authorities; public JwtResponse(String accessToken, String username, Collection<? extends GrantedAuthority> authorities) { this.token = accessToken; this.username = username; this.authorities = authorities; } public String getAccessToken() { return token; } public void setAccessToken(String accessToken) { this.token = accessToken; } public String getTokenType() { return type; } public void setTokenType(String tokenType) { this.type = tokenType; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } }

Created security package inside it two packages jwt and services and Java Class WebSecurityConfig

src/main/java/registerlogin/security/WebSecurityConfig.java

       
        
package registerlogin.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 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; 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.authentication.UsernamePasswordAuthenticationFilter; import registerlogin.security.jwt.JwtAuthEntryPoint; import registerlogin.security.jwt.JwtAuthTokenFilter; import registerlogin.security.services.UserDetailsServiceImpl; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity( prePostEnabled = true ) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired UserDetailsServiceImpl userDetailsService; @Autowired private JwtAuthEntryPoint unauthorizedHandler; @Bean public JwtAuthTokenFilter authenticationJwtTokenFilter() { return new JwtAuthTokenFilter(); } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder .userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable(). authorizeRequests() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated() .and() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); } }

Created three classes in jwt package;

-JwtAuthEntryPoint

-JwtAuthTokenFilter

-JwtProvider

src/main/java/registerlogin/security/jwt/JwtAuthEntryPoint.java):

       
       
package registerlogin.security.jwt; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; @Component public class JwtAuthEntryPoint implements AuthenticationEntryPoint { private static final Logger logger = LoggerFactory.getLogger(JwtAuthEntryPoint.class); @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException { logger.error("Unauthorized error. Message - {}", e.getMessage()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error -> Unauthorized"); } }

src/main/java/registerlogin/security/jwt/JwtAuthTokenFilter.java):

       
      
package registerlogin.security.jwt; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.web.filter.OncePerRequestFilter; import registerlogin.security.services.UserDetailsServiceImpl; public class JwtAuthTokenFilter extends OncePerRequestFilter { @Autowired private JwtProvider tokenProvider; @Autowired private UserDetailsServiceImpl userDetailsService; private static final Logger logger = LoggerFactory.getLogger(JwtAuthTokenFilter.class); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String jwt = getJwt(request); if (jwt != null && tokenProvider.validateJwtToken(jwt)) { String username = tokenProvider.getUserNameFromJwtToken(jwt); UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception e) { logger.error("Can NOT set user authentication -> Message: {}", e); } filterChain.doFilter(request, response); } private String getJwt(HttpServletRequest request) { String authHeader = request.getHeader("Authorization"); if (authHeader != null && authHeader.startsWith("Bearer ")) { return authHeader.replace("Bearer ", ""); } return null; } }

src/main/java/registerlogin/security/jwt/JwtProvider.java):

       
     
package registerlogin.security.jwt; import io.jsonwebtoken.*; import registerlogin.security.services.UserPrinciple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import java.util.Date; @Component public class JwtProvider { private static final Logger logger = LoggerFactory.getLogger(JwtProvider.class); @Value("${registerlogin.app.jwtSecret}") private String jwtSecret; @Value("${registerlogin.app.jwtExpiration}") private int jwtExpiration; public String generateJwtToken(Authentication authentication) { UserPrinciple userPrincipal = (UserPrinciple) authentication.getPrincipal(); return Jwts.builder() .setSubject((userPrincipal.getUsername())) .setIssuedAt(new Date()) .setExpiration(new Date((new Date()).getTime() + jwtExpiration*1000)) .signWith(SignatureAlgorithm.HS512, jwtSecret) .compact(); } public boolean validateJwtToken(String authToken) { try { Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken); return true; } catch (SignatureException e) { logger.error("Invalid JWT signature -> Message: {} ", e); } catch (MalformedJwtException e) { logger.error("Invalid JWT token -> Message: {}", e); } catch (ExpiredJwtException e) { logger.error("Expired JWT token -> Message: {}", e); } catch (UnsupportedJwtException e) { logger.error("Unsupported JWT token -> Message: {}", e); } catch (IllegalArgumentException e) { logger.error("JWT claims string is empty -> Message: {}", e); } return false; } public String getUserNameFromJwtToken(String token) { return Jwts.parser() .setSigningKey(jwtSecret) .parseClaimsJws(token) .getBody().getSubject(); } }

Created two classes in services package;

-UserDetailsServiceImpl

-UserPrinciple

src/main/java/registerlogin/security/services/UserDetailsServiceImpl.java):

       
    
package registerlogin.security.services; import org.springframework.beans.factory.annotation.Autowired; 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 org.springframework.transaction.annotation.Transactional; import registerlogin.model.User; import registerlogin.repository.UserRepository; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override @Transactional public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username).orElseThrow( () -> new UsernameNotFoundException("User Not Found with -> username or email : " + username)); return UserPrinciple.build(user); } }

src/main/java/registerlogin/security/services/UserPrinciple.java):

       
   
package registerlogin.security.services; import com.fasterxml.jackson.annotation.JsonIgnore; import registerlogin.model.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class UserPrinciple implements UserDetails { private static final long serialVersionUID = 1L; private Long id; private String name; private String username; private String email; @JsonIgnore private String password; private Collection<? extends GrantedAuthority> authorities; public UserPrinciple(Long id, String name, String username, String email, String password, Collection<? extends GrantedAuthority> authorities) { this.id = id; this.name = name; this.username = username; this.email = email; this.password = password; this.authorities = authorities; } public static UserPrinciple build(User user) { List<GrantedAuthority> authorities = user.getRoles().stream().map(role -> new SimpleGrantedAuthority(role.getName().name())).collect(Collectors.toList()); return new UserPrinciple( user.getId(), user.getName(), user.getUsername(), user.getEmail(), user.getPassword(), authorities ); } public Long getId() { return id; } public String getName() { return name; } public String getEmail() { return email; } @Override public String getUsername() { return username; } @Override public String getPassword() { return password; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserPrinciple user = (UserPrinciple) o; return Objects.equals(id, user.id); } }

We will create controller package inside it created two classes.

-UserController

-AuthController

src/main/java/registerlogin/security/controller/UserController.java):


 
  
package registerlogin.controller; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/api/auth") public class UserController { @GetMapping("/user") //@PreAuthorize("hasRole('USER') or hasRole('ADMIN')") @Secured({"ROLE_USER", "ROLE_ADMIN"}) public String userAccess() { return ">>> User Contents!"; } @GetMapping("/admin") //@PreAuthorize("hasRole('ADMIN')") @Secured("ROLE_ADMIN") public String adminAccess() { return ">>> Admin Contents"; } }

src/main/java/registerlogin/security/controller/AuthController.java):


 
 
package registerlogin.controller; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.*; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; 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.validation.BindingResult; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import registerlogin.message.request.LoginForm; import registerlogin.message.request.SignUpForm; import registerlogin.message.response.JwtResponse; import registerlogin.message.response.ResponseMessage; import registerlogin.model.Role; import registerlogin.model.RoleName; import registerlogin.model.User; import registerlogin.repository.RoleRepository; import registerlogin.repository.UserRepository; import registerlogin.security.jwt.JwtProvider; @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/api/auth") public class AuthController { @Autowired AuthenticationManager authenticationManager; @Autowired UserRepository userRepository; @Autowired RoleRepository roleRepository; @Autowired PasswordEncoder encoder; @Autowired JwtProvider jwtProvider; @PostMapping("/login") public ResponseEntity<?> login(@Valid @RequestBody LoginForm loginRequest, BindingResult result) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = jwtProvider.generateJwtToken(authentication); UserDetails userDetails = (UserDetails) authentication.getPrincipal(); if (result.hasErrors()) { return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getUsername(), userDetails.getAuthorities())); } return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getUsername(), userDetails.getAuthorities())); } @PostMapping("/register") public ResponseEntity<?> register(@Valid @RequestBody SignUpForm signUpRequest) { if (userRepository.existsByUsername(signUpRequest.getUsername())) { return new ResponseEntity<>(new ResponseMessage("Fail -> Username is already taken!"), HttpStatus.BAD_REQUEST); } if (userRepository.existsByEmail(signUpRequest.getEmail())) { return new ResponseEntity<>(new ResponseMessage("Fail -> Email is already in use!"), HttpStatus.BAD_REQUEST); } // Creating user's account User user = new User(signUpRequest.getName(), signUpRequest.getUsername(), signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword()), signUpRequest.getGender(), signUpRequest.getBirthDate(), new Date()); Set<String> strRoles = signUpRequest.getRole(); Set<Role> roles = new HashSet<>(); strRoles.forEach(role -> { switch (role) { case "admin": Role adminRole = roleRepository.findByName(RoleName.ROLE_ADMIN).orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find.")); roles.add(adminRole); break; default: Role userRole = roleRepository.findByName(RoleName.ROLE_USER).orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find.")); roles.add(userRole); } }); user.setRoles(roles); userRepository.save(user); return new ResponseEntity<>(new ResponseMessage("User registered successfully!"), HttpStatus.OK); } @GetMapping("/findAllUsers") public List<User> findAllUsers() { return userRepository.findAll(); } @GetMapping("/getUserByUsername/{username}") public Optional<User> getUserByUsername(@PathVariable("username") String username) { return userRepository.findByUsername(username); } @PutMapping("/updateUser/{id}") public ResponseEntity<User> updateUser(@PathVariable("id") Long userId, @RequestBody User user){ Optional<User> users = userRepository.findById(userId); if (users.isPresent()) { User _user = users.get(); _user.setName(user.getName()); _user.setUsername(user.getUsername()); _user.setEmail(user.getEmail()); _user.setCreateAt(new Date()); _user.setPassword(encoder.encode(user.getPassword())); return new ResponseEntity<User>(userRepository.save(_user), HttpStatus.OK); } return new ResponseEntity<User>(HttpStatus.NOT_FOUND); } @DeleteMapping("/deleteUser/{id}") public ResponseEntity<String> deleteUser(@PathVariable("id") Long userId) { userRepository.deleteById(userId); return new ResponseEntity<String>("User deleted", HttpStatus.OK); } @GetMapping("/getUserById/{id}") public Optional<User> getUserById(@PathVariable("id") Long userId) { return userRepository.findById(userId); } }

We will run application Spring boot

-RegisterLoginApplication

We need to save Role In The database With Jpa RoleRepository

src/main/java/registerlogin/RegisterLoginApplication.java):


 

package registerlogin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import registerlogin.model.Role; import registerlogin.model.RoleName; import registerlogin.repository.RoleRepository; @SpringBootApplication public class RegisterLoginApplication { @Autowired RoleRepository roleRepository; public static void main(String[] args) { SpringApplication.run(RegisterLoginApplication.class, args); System.out.print("\n"); System.out.print("App started ..."); } @Bean CommandLineRunner runner() { return args -> { // roleRepository.deleteAll(); Role adminRole = new Role(RoleName.ROLE_ADMIN); Role useRole = new Role(RoleName.ROLE_USER); roleRepository.save(adminRole); roleRepository.save(useRole); }; } }

Conclusion

We were building this application with functionality:

- Create a package model inside it We will add java classes
- Created security package inside it two packages jwt and services and Java Class WebSecurityConfig
- Created three classes in jwt package;
- Created two classes in services package;
- created controller package inside it created two classes.


Create application With Angular Part 2

Post a Comment

Previous Post Next Post


Follow us on facebook