SpringBoot项目 2.0.8
配置类:BrowserSecurityConfig
- 配置认证方式、授权
- 配置加密类
@Configuration
@EnableWebSecurity
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean // 配置加密类
public PasswordEncoder passwordEncoder(){
// return new BCryptPasswordEncoder();
return PasswordEncoderFactories.createDelegatingPasswordEncoder(); // 返回一个加密类
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable(); // 关闭csrf跨域认证
http.formLogin() // 表单登陆
// http.httpBasic() // httpBasic登陆方式
.and()
.authorizeRequests() // 请求授权
.anyRequest() // 任何请求
.authenticated(); // 需要身份认证
}
}
配置UserServiceImpl
- 实现UserDetailService接口
- 实现loadUserByUsername(String username)方法
- 注入PasswordEncoder 加解密类
@Service
public class UserServiceImpl implements UserService {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private PasswordEncoder PasswordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 根据用户名查找用户信息
logger.info("登陆用户名:" + username);
//验证逻辑。。。。。 用户名、密码、可用、没失效、证书没失效、锁定、权限
String password = PasswordEncoder.encode("123456");
logger.info(password);
User user = new User(username, password, true,true,true,true,AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
return user;
}
}