- 首先引入pom坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
- 编写配置类继承
WebSecurityConfigurerAdapter
类:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//注入一个UserDetailsService接口对象,后续需要一个实现该接口类
@Autowired
private UserDetailsService userDetailsService;
@Override
//重写该方法
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
}
- 编写
UserDetailsService
的实现类
@Service("userDetailsService") //因为注入的是该类所实现的接口,因此组件应该起个别名,和注入时的变量名一致
public class MyUserDetailService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
return new User(name,new BCryptPasswordEncoder().encode(rawPassword),auths);
}
}
上面的loadUserByUsername
方法中,参数username
为用户输入的用户名,经过与DAO
层的交互和认证,最终返回的name
和rawPassword
如果与输入的一致,则认证通过,否则认证失败