springsecurity有三种认证方式
第一种方式:通过配置文件设置登录名和密码
在application.yml文件中写入
spring:
security:
user:
name: admin
password: 123
第二种方式:通过配置类实现
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//this.disableLocalConfigureAuthenticationBldr = true;
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String password = passwordEncoder.encode("123");
auth.inMemoryAuthentication().withUser("lucy").password(password).roles("admin");
}
@Bean
PasswordEncoder password(){
return new BCryptPasswordEncoder();
}
}
第三种方式:通过自定义编写实现类
实际使用中,我们采用的是第三种方式,因为要使用数据库数据对比账号和密码,
第一步:创建配置类,设置使用哪个userDetailsService实现类
@Configuration
public class SecurityConfig1 extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(password());
}
@Bean
PasswordEncoder password(){
return new BCryptPasswordEncoder();
}
}
第二步:编写实现类,返回User对象,User对象有用户名密码和操作权限
@Service("userDetailsService")
public class MyDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
return new User("mary",new BCryptPasswordEncoder().encode("1234"),auths);
}
}