Spring Security基于数据库实现认证过程解析
创建数据库
SETFOREIGN_KEY_CHECKS=0;
------------------------------
--Tablestructureforrole
------------------------------
DROPTABLEIFEXISTS`role`;
CREATETABLE`role`(
`id`int(11)NOTNULLAUTO_INCREMENT,
`name`varchar(32)DEFAULTNULL,
`nameZh`varchar(32)DEFAULTNULL,
PRIMARYKEY(`id`)
)ENGINE=InnoDBAUTO_INCREMENT=4DEFAULTCHARSET=utf8;
------------------------------
--Recordsofrole
------------------------------
INSERTINTO`role`VALUES('1','dba','数据库管理员');
INSERTINTO`role`VALUES('2','admin','系统管理员');
INSERTINTO`role`VALUES('3','user','用户');
------------------------------
--Tablestructureforuser
------------------------------
DROPTABLEIFEXISTS`user`;
CREATETABLE`user`(
`id`int(11)NOTNULLAUTO_INCREMENT,
`username`varchar(32)DEFAULTNULL,
`password`varchar(255)DEFAULTNULL,
`enabled`tinyint(1)DEFAULTNULL,
`locked`tinyint(1)DEFAULTNULL,
PRIMARYKEY(`id`)
)ENGINE=InnoDBAUTO_INCREMENT=4DEFAULTCHARSET=utf8;
------------------------------
--Recordsofuser
------------------------------
INSERTINTO`user`VALUES('1','root','$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq','1','0');
INSERTINTO`user`VALUES('2','admin','$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq','1','0');
INSERTINTO`user`VALUES('3','sang','$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq','1','0');
------------------------------
--Tablestructureforuser_role
------------------------------
DROPTABLEIFEXISTS`user_role`;
CREATETABLE`user_role`(
`id`int(11)NOTNULLAUTO_INCREMENT,
`uid`int(11)DEFAULTNULL,
`rid`int(11)DEFAULTNULL,
PRIMARYKEY(`id`)
)ENGINE=InnoDBAUTO_INCREMENT=5DEFAULTCHARSET=utf8;
------------------------------
--Recordsofuser_role
------------------------------
INSERTINTO`user_role`VALUES('1','1','1');
INSERTINTO`user_role`VALUES('2','1','2');
INSERTINTO`user_role`VALUES('3','2','2');
INSERTINTO`user_role`VALUES('4','3','3');
SETFOREIGN_KEY_CHECKS=1;
导入依赖
org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.3 mysql mysql-connector-java runtime 5.1.46 com.alibaba druid-spring-boot-starter 1.1.22
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/javaboy?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
让bean实现UserDetails接口
publicclassUserimplementsUserDetails{
privateIntegerid;
privateStringusername;
privateStringpassword;
privateBooleanenabled;
privateBooleanlocked;
privateListroles;
publicListgetRoles(){
returnroles;
}
publicvoidsetRoles(Listroles){
this.roles=roles;
}
publicIntegergetId(){
returnid;
}
publicvoidsetId(Integerid){
this.id=id;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
publicvoidsetPassword(Stringpassword){this.password=password;}
publicvoidsetEnabled(Booleanenabled){
this.enabled=enabled;
}
publicvoidsetLocked(Booleanlocked){
this.locked=locked;
}
@Override
publicCollectiongetAuthorities(){
Listauthorities=newArrayList<>();
for(Rolerole:roles){
authorities.add(newSimpleGrantedAuthority("ROLE_"+role.getName()));
}
returnauthorities;
}
@Override
publicStringgetPassword(){
returnpassword;
}
publicStringgetUsername(){
returnusername;
}
//账户是否未过期
@Override
publicbooleanisAccountNonExpired(){
returntrue;
}
//账户是否未锁定
@Override
publicbooleanisAccountNonLocked(){
return!locked;
}
@Override
publicbooleanisCredentialsNonExpired(){
returntrue;
}
@Override
publicbooleanisEnabled(){
returnenabled;
}
}
publicclassRole{
privateIntegerid;
privateStringname;
privateStringnameZh;
...
}
userMapper
在类上直接加@Mapper或者在SpringBoot启动类上配置全局的扫描@MapperScan(basePackages="")
@Mapper
publicinterfaceUserMapper{
UserloadUserByUsername(Stringusername);
ListgetUserRolesById(Integerid);
}
select*fromuserwhereusername=#{username} select*fromrolewhereidin(selectridfromuser_rolewhereuid=#{id})
userService同样也要继承UserServiceDetails接口
@Service
publicclassUserServiceimplementsUserDetailsService{
@Autowired
UserMapperuserMapper;
@Override
publicUserDetailsloadUserByUsername(Stringusername)throwsUsernameNotFoundException{
Useruser=userMapper.loadUserByUsername(username);
if(user==null){
thrownewUsernameNotFoundException("用户不存在");
}
user.setRoles(userMapper.getUserRolesById(user.getId()));
returnuser;
}
}
HelloController
@RestController
publicclassHelloController{
@GetMapping("/hello")
publicStringhello(){
return"hellosecurity";
}
@GetMapping("/dba/hello")
publicStringdba(){
return"hellodba";
}
@GetMapping("/admin/hello")
publicStringadmin(){
return"helloadmin";
}
@GetMapping("/user/hello")
publicStringuser(){
return"hellouser";
}
}
SecurityConfig
- SercurityConfig需要继承WebSecurityConfigurerAdapter类,并在类上加@Configuration
- SpringSecurity5.0之后密码必须加密
- 把数据库查出的用户信息交给SpringSecurity处理
- 配置httpSercurity
@Configuration
publicclassSecurityConfigextendsWebSecurityConfigurerAdapter{
@Autowired
UserServiceuserService;
//把数据库查出的用户信息交给SpringSecurity处理
@Override
protectedvoidconfigure(AuthenticationManagerBuilderauth)throwsException{
auth.userDetailsService(userService);
}
@Bean
PasswordEncoderpasswordEncoder(){
returnnewBCryptPasswordEncoder();
}
@Override
protectedvoidconfigure(HttpSecurityhttp)throwsException{
http.authorizeRequests()
.antMatchers("/dba/**").hasRole("dba")
.antMatchers("/admin/**").hasRole("admin")
.antMatchers("/user/**").hasRole("user")
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll()
.and()
.csrf().disable();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。