本文共 2958 字,大约阅读时间需要 9 分钟。
1、首先我们准备数据库,在这我们只需要准备一个user
表,因为还未涉及到授权的过程。
2、导入依赖
这里我们使用的是mysql
、mybatis-plus
、以及lombok
com.baomidou mybatis-plus-boot-starter 3.0.5 org.projectlombok lombok mysql mysql-connector-java runtime 5.1.27
3、编写实现类和配置类
自定义配置类SecurityConfig2
/** * 自定义配置类 * 实现从数据库获取用户名和密码 */@Configurationpublic class SecurityConfig2 extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder()); } @Bean PasswordEncoder getPasswordEncoder(){ return new BCryptPasswordEncoder(); }}
编写UserDetailsService
的实现类MyUserDetailsService
UserDetailsService
的作用:
SpringSecurity
中进行身份验证的是AuthenticationManager
接口,ProviderManager
是它的一个默认实现,但它并不用来处理身份认证,而是委托给配置好的AuthenticationProvider
,每个AuthenticationProvider
会轮流检查身份认证。检查后或者返回Authentication
对象或者抛出异常。
验证身份就是加载响应的UserDetails
,看看是否和用户输入的账号、密码、权限等信息匹配。此步骤由实现AuthenticationProvider
的DaoAuthenticationProvider
(它利用UserDetailsService
验证用户名、密码和授权)处理。包含GrantedAuthority
的UserDetails
对象在构建 Authentication
对象时填入数据。
在真实的系统中,我们希望用户的信息来自数据库,而不是写死的,我们就需要实现UserDetailsService
接口。
@Service("userDetailsService")public class MyUserDetailsService implements UserDetailsService { @Autowired private UserMapper userMapper; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 调用userMapper方法。根据用户名查询数据库 QueryWrapperusersQueryWrapper = new QueryWrapper<>(); // where username = ? usersQueryWrapper.eq("username",username); Users users = userMapper.selectOne(usersQueryWrapper); // 判断 if(users == null){ // 没有用户名,认证失败 throw new UsernameNotFoundException("用户名不存在"); } List authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList("admin"); // 从查询数据库返回users对象中获取用户名和密码 return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),authorityList); }}
3、编写mapper
层
@Repositorypublic interface UserMapper extends BaseMapper{ }
4、配置数据库连接
spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://127.0.0.1:3306/testspring.datasource.username=rootspring.datasource.password=root
5、编写controller
测试访问
@Controller@RequestMapping("/test")public class LoginController { @RequestMapping("/index") @ResponseBody public String index(){ return "hello index"; } @RequestMapping("/hello") @ResponseBody public String hello(){ return "new hello"; }}
输入url
进行访问/test/index
,跳转到SpringSecurity
的默认登录页面
输入账号密码,进行用户认证,认证成功。
转载地址:http://whtgn.baihongyu.com/