springsecurity-认证流程
认证流程:
从图中可以得出我们要想从数据库中取用户的信息进行验证就需要实现 UserDetailsService 接口,并将数据封装到 User 对象中即可
实现步骤:
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
编写配置类 配置 密码加解密方式
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
//定义自己的登陆页面
.loginPage("login.html")
//认证的请求
.loginProcessingUrl("/login")
//登陆成功跳转的页面
.successForwardUrl("/toMain");
http.authorizeRequests()
//指定匹配的请求直接放行,其他的请求都需要拦截认证
.antMatchers("/login.html")
.permitAll()
.antMatchers("/*.css").permitAll()
.anyRequest()
.authenticated();
http.csrf().disable();
}
@Bean
public PasswordEncoder getPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
自定义一个类实现UserDetailsService接口,并重写loadUserByUsername方法
@Service
public class UserServiceImpl implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//从数据库中查询用户信息
...............
if (username == null){
throw new UsernameNotFoundException("用户名或密码错误");
}
String encode = passwordEncoder.encode("123456");
if ("admin".equals(username)){
return new User("admin",encode, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
return null;
}
}