Spring Security 配置数据源 - 内存用户
Spring Security支持多种数据源:内存,数据库,LDAP等。不同来源的数据被封装成一个UserDetailService接口的实例。任何实现了UserDetailService的对象都可以做认证数据源。
这里介绍3种内存数据的配置方式:默认,application.properties 配置,java 配置
1.项目启动时的默认用户
默认情况下,登录的用户名是 user
,密码则是项目启动时随机生成的字符串
2.application.properties配置内存数据源
在application.properties文件中配置,则项目启动时不再打出password,我们可以使用java/123登陆系统
spring.security.user.name=java
spring.security.user.password=123
3.两种Java配置方式2选1即可
3.1 Java方式配置内存数据 InMemoryUserDetailsManager,不加密方式
InMemoryUserDetailsManager 就是系统默认提供的 UserDetailsService 实例
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration public class SecurityConfiguration{ @Bean public UserDetailsService userDetailsService() { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build()); manager.createUser(User.withDefaultPasswordEncoder().username("test12").password("abcd").roles("user").build()); return manager; } }
3.2 Java方式配置内存数据 AuthenticationManagerBuilder
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } //准备内存测试用户 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("java") .password("1234") .roles("admin") .and() .withUser("test") .password("1234") .roles("user"); } }