我正在使用 spring security 基本身份验证,在应用程序启动时出现以下错误:
com.spring.security.firstapp.security.MySecurityConfig 中方法 authManager 的参数 2 需要一个无法找到类型为“org.springframework.security.core.userdetails.UserDetailsService”的 bean。
动作:
考虑在您的配置中定义类型为“org.springframework.security.core.userdetails.UserDetailsService”的 bean。
@配置 公开课 MySecurityConfig {
@Autowired
private MyAuthenticationProvider authenticationProvider;
@Bean
public AuthenticationManager authManager(HttpSecurity http, BCryptPasswordEncoder passwordEncoder,
UserDetailsService userDetailService) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.authenticationProvider(authenticationProvider)
.build();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.httpBasic();
http.authorizeHttpRequests().anyRequest().authenticated();
return http.build();
}
@Bean
public static BCryptPasswordEncoder bcryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
@组件 公共类 MyAuthenticationProvider 实现 AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userName = authentication.getName();
String passWord = authentication.getCredentials().toString();
if("tom".equals(userName) && "abc".equals(passWord))
return new UsernamePasswordAuthenticationToken(userName, passWord);
else
throw new BadCredentialsException("Invalid credentials!!");
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
@RestController 公共类 HelloController {
@GetMapping("/hello")
public String hello() {
return "Spring Boot Security";
}
}
4.0.0
org.springframework.boot
spring-boot-starter-parent
3.0.4
com.first-app
弹簧安全
0.0.1-快照
弹簧安全
弹簧安全
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
我在课堂上添加了豆MySecurityConfig
@Bean
public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) {
UserDetails user = User.withUsername("user")
.password(passwordEncoder.encode("password"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(passwordEncoder.encode("admin"))
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
运行良好后