1 Build Login REST API
1.1 LoginDto
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class LoginDto {
private String usernameOrEmail;
private String password;
}
1.2 AuthService
public interface AuthService {
String login(LoginDto loginDto);
}
@Service
public class AuthServiceImpl implements AuthService {
private AuthenticationManager authenticationManager;
public AuthServiceImpl(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public String login(LoginDto loginDto) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
loginDto.getUsernameOrEmail(),
loginDto.getPassword()
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return "User Logged-in successfully!";
}
}
1.3 Controller
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private AuthService authService;
public AuthController(AuthService authService) {
this.authService = authService;
}
//Build Login REST API
@PostMapping(value = {"/login", "/signin"})
public ResponseEntity<String> login(@RequestBody LoginDto loginDto) {
return ResponseEntity.ok(authService.login(loginDto));
}
}
1.3 Security Configuration
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
private UserDetailsService userDetailsService;
public SecurityConfig(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Bean
public static PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeHttpRequests((authorize) ->
//authorize.anyRequest().authenticated())
authorize.requestMatchers(HttpMethod.GET, "/api/**").permitAll()
.requestMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
);
return http.build();
}
}
2 Build Register API
2.1 RegisterDto
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class RegisterDto {
private String name;
private String username;
private String email;
private String password;
}
2.2 Service
public interface AuthService {
String register(RegisterDto registerDto);
}
@Service
public class AuthServiceImpl implements AuthService {
private UserRepository userRepository;
private RoleRepository roleRepository;
private PasswordEncoder passwordEncoder;
public AuthServiceImpl(UserRepository userRepository, RoleRepository roleRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.passwordEncoder = passwordEncoder;
}
@Override
public String register(RegisterDto registerDto) {
//add check for username exist in database
if (userRepository.existsByUsername(registerDto.getUsername()))
throw new BlogAPIException(HttpStatus.BAD_REQUEST,"Username already exists!");
//add check for email in database
if (userRepository.existsByEmail(registerDto.getEmail()))
throw new BlogAPIException(HttpStatus.BAD_REQUEST,"Email already exists!");
User user = new User();
user.setName(registerDto.getName());
user.setUsername(registerDto.getUsername());
user.setEmail(registerDto.getEmail());
user.setPassword(passwordEncoder.encode(registerDto.getPassword()));
Set<Role> roles = new HashSet<>();
Role roleUser = roleRepository.findByName("ROLE_USER").get();
roles.add(roleUser);
user.setRoles(roles);
userRepository.save(user);
return "User registered successfully!";
}
}
2.3 Controller
//Build Register REST API
@PostMapping(value = {"/register","/signup"})
public ResponseEntity<String> register(@RequestBody RegisterDto registerDto){
return ResponseEntity.ok(authService.register(registerDto));
}