Я использую PostgreSQL в качестве базы данных в Windows 10.
Другая проблема, которая может быть связана с этим, заключается в том, что, хотя Spring.jpa.hibernate.ddl-auto=create-drop, Spring Boot никогда не создает и не удаляет какую-либо таблицу.
Это код:
application.properties
Код: Выделить всё
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/ecommerce
spring.datasource.username=postgres
spring.datasource.password=admin
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
server.error.include-message=always
server.error.include-binding-errors=always
logging.level.org.springframework.web=DEBUG
Код: Выделить всё
package model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.Data;
@Entity
@Table(name = "user", schema = "public", catalog = "ecommerce")
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String password;
private String role;
}
Код: Выделить всё
package repository;
import model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository {
Optional findByUsername(String username);
}
Код: Выделить всё
package service;
import lombok.AllArgsConstructor;
import model.User;
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 repository.UserRepository;
import java.util.Optional;
@Service
@AllArgsConstructor
public class UserService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional user = userRepository.findByUsername(username);
if (user.isEmpty()) {
throw new UsernameNotFoundException("User not found");
}
return org.springframework.security.core.userdetails.User
.withUsername(user.get().getUsername())
.password(user.get().getPassword())
.roles(user.get().getRole())
.build();
}
}
Код: Выделить всё
package controller;
import model.User;
import org.springframework.beans.factory.annotation.Autowired;
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;
import repository.UserRepository;
@RestController
@RequestMapping("/auth")
public class AuthController {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@PostMapping(value = "/register", consumes = "application/json")
public User registerUser(@RequestBody User user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
return userRepository.save(user);
}
}
Код: Выделить всё
package config;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import service.UserService;
@Configuration
@AllArgsConstructor
@EnableWebSecurity
public class SecurityConfig {
@Autowired
private UserService userService;
@Bean
public UserDetailsService userDetailsService() {
return userService;
}
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userService);
provider.setPasswordEncoder(passwordEncoder());
return provider;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.csrf(AbstractHttpConfigurer::disable)
.formLogin(httpForm -> httpForm
.loginPage("/login").permitAll()
)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/register", "/req/login").permitAll()
.anyRequest().authenticated()
)
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Это запрос, который я отправляю:
Код: Выделить всё
POST http://localhost:8080/auth/register
Content-Type: application/json
Content-Length: 68
User-Agent: IntelliJ HTTP Client/IntelliJ IDEA 2024.2.1
Accept-Encoding: br, deflate, gzip, x-gzip
Accept: */*
Cookie: JSESSIONID=0B78821711958B77E7EBCD35516929A5
{
"username": "user",
"password": "password",
"role": "user"
}
Код: Выделить всё
POST http://localhost:8080/auth/register
HTTP/1.1 401
Set-Cookie: JSESSIONID=29D6D2B6789DFD2E35C5786005ED8228; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
WWW-Authenticate: Basic realm="Realm"
Content-Length: 0
Date: Wed, 18 Sep 2024 12:35:30 GMT
Response code: 401; Time: 582ms (582 ms); Content length: 0 bytes (0 B)
Cookies are preserved between requests:
> C:\Users\AAA\
Подробнее здесь: https://stackoverflow.com/questions/789 ... lowed-them