Login and Register REST APIs using Spring Security 6 & Spring Boot 3

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));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure, here's an outline of how you can implement the shipping REST APIs using Spring Boot, Spring MVC, JPA/Batis, MySQL, and JWT: 1. Set up a Spring Boot project with the necessary dependencies for Spring MVC, JPA/Batis, MySQL, and JWT. You can use Spring Initializr to generate the project structure and add the dependencies. 2. Define the domain model for the shipping application, including entities such as Order, Product, Customer, and ShippingAddress. Map the entities to database tables using JPA annotations or MyBatis mapper XML files. 3. Implement the repository layer to perform CRUD operations on the database using JPA or MyBatis. You can use Spring Data JPA or MyBatis-Spring to simplify the implementation. 4. Define the REST API endpoints for the shipping application using Spring MVC annotations. Use JWT for authentication and authorization of the API endpoints. 5. Implement the service layer to perform business logic operations such as calculating shipping costs, validating orders, and processing payments. Use dependency injection to inject the repository and other services into the service layer. 6. Write unit tests to ensure that the application logic is working correctly. You can use JUnit and Mockito to write the tests. 7. Deploy the application to a server and test the API endpoints using a tool such as Postman. Here's some example code to get you started: ```java @RestController @RequestMapping("/api/orders") public class OrderController { @Autowired private OrderService orderService; @PostMapping("/") public ResponseEntity<Order> createOrder(@RequestBody Order order) { Order createdOrder = orderService.createOrder(order); return ResponseEntity.ok(createdOrder); } @GetMapping("/{id}") public ResponseEntity<Order> getOrder(@PathVariable("id") Long orderId) { Order order = orderService.getOrder(orderId); return ResponseEntity.ok(order); } // Other API endpoints for updating and deleting orders } @Service public class OrderService { @Autowired private OrderRepository orderRepository; public Order createOrder(Order order) { // Calculate shipping costs and validate the order order.setShippingCosts(10.0); order.setTotalPrice(order.getProducts().stream() .mapToDouble(Product::getPrice) .sum() + order.getShippingCosts()); return orderRepository.save(order); } public Order getOrder(Long orderId) { return orderRepository.findById(orderId) .orElseThrow(() -> new NotFoundException("Order not found")); } // Other service methods for updating and deleting orders } @Repository public interface OrderRepository extends JpaRepository<Order, Long> { } ``` This code defines a REST API endpoint for creating orders and getting orders by ID. The order creation logic is implemented in the OrderService class, which calculates shipping costs and saves the order to the database using the OrderRepository interface. JWT authentication and authorization can be added to the API endpoints using Spring Security.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值