Ошибка использования типа bean-компонента в AuthenticationManager в безопасности весенней загрузкиJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Ошибка использования типа bean-компонента в AuthenticationManager в безопасности весенней загрузки

Сообщение Anonymous »

Я пытаюсь реализовать пользовательскую аутентификацию в Spring Security, используя UserDetails. Для этого я создал свой сервис UserDetailsService:

Код: Выделить всё

package com.api.business_manager_api.Services;

import com.api.business_manager_api.Models.UserModel;
import com.api.business_manager_api.Repositories.UserRepository;
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 software.amazon.awssdk.services.connect.model.UserNotFoundException;

import java.util.ArrayList;
import java.util.Optional;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String username) throws UserNotFoundException {
Optional  optionalUser = userRepository.findByUsername(username);

if (optionalUser.isPresent()) {
UserModel userModel = optionalUser.get();
return new org.springframework.security.core.userdetails.User(userModel.getUsername(), userModel.getPassword(),
new ArrayList());
} else {
throw new UsernameNotFoundException("User not found with username: " + username);
}
}
}

это моя конфигурация безопасности

Код: Выделить всё

package com.api.business_manager_api.Config;

import com.api.business_manager_api.Services.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
private final UserDetailsServiceImpl userDetailsService;

public SecurityConfig(UserDetailsServiceImpl userDetailsService) {
this.userDetailsService = userDetailsService;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf().disable()
.authorizeHttpRequests(
authorizeConfig -> {
authorizeConfig.requestMatchers("/user").permitAll();
authorizeConfig.requestMatchers("/auth").permitAll();
authorizeConfig.requestMatchers("/user/**").authenticated();
authorizeConfig.anyRequest().authenticated();
})
.userDetailsService(userDetailsService)
.httpBasic()
.and()
.build();
}
}

и это мой контроллер аутентификации

Код: Выделить всё

package com.api.business_manager_api.Controllers;

import com.api.business_manager_api.Dtos.LoginDto;
import com.api.business_manager_api.Security.JwtAuthenticationResponse;
import com.api.business_manager_api.Security.JwtTokenProvider;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.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;

@RestController
@RequestMapping("/auth")
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private JwtTokenProvider jwtTokenProvider;

@PostMapping
public ResponseEntity  authenticateUser (@RequestBody @Valid LoginDto loginDto) {

Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginDto.getUsername(),
loginDto.getPassword()
)
);

SecurityContextHolder.getContext().setAuthentication(authentication);

String jwt = jwtTokenProvider.generateToken(authentication);
return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));

}
}

Проблема в том, что когда я запускаю свой API, возвращается ошибка:

Код: Выделить всё

Field authenticationManager in com.api.business_manager_api.Controllers.AuthController required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.

The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
Я не понимаю, почему и как мне следует использовать Bean в своем приложении. Может ли кто-нибудь сказать мне решение?

Подробнее здесь: https://stackoverflow.com/questions/757 ... t-security
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»