[英]Spring Boot 2 security basic authentication
为什么以下基本安全配置不适用于inMemoryAuthentication()子句?
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic()
.and()
.authorizeRequests()
.anyRequest().authenticated();
super.configure(http);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("username").password("password");
super.configure(auth);
}
}
在应用程序初始化之后,仍然只有Spring本身生成的默认user
,没有诸如username这样的username
。
不要从void configure(AuthenticationManagerBuilder auth)
调用超级方法。 它将disableLocalConfigureAuthenticationBldr
标志设置为true
,这会导致AuthenticationManagerBuilder
被忽略。 最后,您的void configure(AuthenticationManagerBuilder auth)
方法应如下所示:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("username").password("password").roles("USER");
}
在Spring Boot 2.x中,您将必须实现自己的UserDetailsService ,如此处和此处所述
例:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger log = LogManager.getLogger();
@Override
protected void configure(HttpSecurity http) throws Exception {
// Note:
// Use this to enable the tomcat basic authentication (tomcat popup rather than spring login page)
// Note that the CSRf token is disabled for all requests
log.info("Disabling CSRF, enabling basic authentication...");
http
.authorizeRequests()
.antMatchers("/**").authenticated() // These urls are allowed by any authenticated user
.and()
.httpBasic();
http.csrf().disable();
}
@Bean
public UserDetailsService userDetailsService() {
// Get the user credentials from the console (or any other source):
String username = ...
String password = ...
// Set the inMemoryAuthentication object with the given credentials:
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
String encodedPassword = passwordEncoder().encode(password);
manager.createUser(User.withUsername(username).password(encodedPassword).roles("USER").build());
return manager;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.