我正在尝试使用 UserDetails 在 Spring Security 中实现自定义身份验证。为此,我创建了 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 <UserModel> 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。谁能告诉我解决办法吗
AuthenticationManager
是身份验证提供程序的容器,为它们提供一致的接口。
为了让 AuthenticationManager bean 位于 spring 上下文中,您可以使用以下解决方案。
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
并且您可以在任何需要的地方注入 AuthenticationManager 。