我正在学习Spring Boot应用程序中的Spring Security,我有一个非常简单的示例。我看到,如果我注释configure(AuthenticationManagerBuilder auth)
,没有什么不同。无论我是否使用它,我都会得到相同的输出,并且我需要使用硬编码的凭据登录。
@Configuration
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// private final MyUserDetailsService myUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
}
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.userDetailsService(myUserDetailsService);
// }
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
MyUserDetailsService类:
@Service
public class MyUserDetailsService implements UserDetailsService {
private static final String USERNAME = "john";
private static final String PASSWORD = "$2a$10$fDDUFA8rHAraWnHAERMAv.4ReqKIi7mz8wrl7.Fpjcl1uEb6sIHGu";
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
if (!userName.equals(USERNAME)) {
throw new UsernameNotFoundException(userName);
}
return new User(USERNAME, PASSWORD, new ArrayList<>());
}
}
RestController:
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
我想知道实现UserDetailsService
接口是否等同于覆盖configure(AuthenticationManagerBuilder auth)
。谢谢!
发布于 2020-10-28 18:11:29
不,实现身份验证接口并不等同于覆盖配置(AuthenticationManagerBuilder身份验证)。
如果覆盖UserDetailsSeervice并通过覆盖loadUserByUsername()验证用户名和密码,在本例中它是静态值(我建议静态用户使用inMemoryAuthentication)。
您需要自动连接UserDetailsService
@Autowired
UserDetailsService userDetailsService;
和
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
这将告诉您的authenticationManager使用userDetailsService,它是为身份验证实现的。
https://stackoverflow.com/questions/64526372
复制相似问题