Я включил базовую аутентификацию в Postman, где ввожу учетные данные существующего пользователя, но ошибка 401 ошибка сохраняется. Может кто-нибудь помочь мне понять, что может пойти не так?
Ниже приведен соответствующий код:
0.SecurityConfig
Код: Выделить всё
package com.example.new_messager.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable() // Disabled CSRF for testing (configure it properly in production)
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/api/users/register").permitAll() // Allow registration without authentication
.anyRequest().authenticated() // Require authentication for other endpoints
)
.httpBasic(); // Use basic authentication
return http.build();
}
}
Код: Выделить всё
package com.example.new_messager.controller;
import com.example.new_messager.model.User;
import com.example.new_messager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("/register")
public void registerUser(@RequestBody User user) {
userService.register(user);
}
@GetMapping("/{username}")
public User findByUsername(@PathVariable String username) {
return userService.findByUsername(username);
}
}
Код: Выделить всё
package com.example.new_messager.model;
import jakarta.persistence.*;
@Entity
@Table(name = "app_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String username;
@Column(nullable = false)
private String password;
public void setPassword(String encode) {
this.password = encode;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
- UserService
Код: Выделить всё
package com.example.new_messager.service;
import com.example.new_messager.model.User;
import com.example.new_messager.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
private final BCryptPasswordEncoder passwordEncoder;
@Autowired
public UserService(UserRepository userRepository, BCryptPasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
public void register(User user) {
if (user.getPassword() == null || user.getPassword().isEmpty()) {
throw new IllegalArgumentException("Password cannot be null or empty");
}
if (user.getUsername() == null || user.getPassword() == null) {
throw new IllegalArgumentException("Username and password must not be null");
}
String encodedPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(encodedPassword);
userRepository.save(user);
}
public boolean validatePassword(String rawPassword, String encodedPassword) {
return passwordEncoder.matches(rawPassword, encodedPassword);
}
public User findByUsername(String username) {
return userRepository.findByUsername(username)
.orElseThrow(() -> new RuntimeException("User not found"));
}
}
Код: Выделить всё
package com.example.new_messager.repository;
import com.example.new_messager.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository {
Optional findByUsername(String username);
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... ng-backend
Мобильная версия