SpringBoot安全管理--基于数据库的认证
Posted CrazyDream
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot安全管理--基于数据库的认证相关的知识,希望对你有一定的参考价值。
简介:
上篇文章向读者介绍的认证数据都是定义在内存中的,在真实项目中,用户的基本信息以及角色等都存储在数据库中,因此需要从数据库中获取数据进行认证。
开始:
首先建表并且插入数据:
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency>
创建实体类:
public class User implements UserDetails { private Integer id; private String username; private String password; private Boolean enabled; private Boolean locked; private List<Role> roles;
//获取当前用户对象所具有的所有角色信息 @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<SimpleGrantedAuthority> authorities = new ArrayList<>(); for (Role role : roles) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return authorities; }
//获取当前对象密码 @Override public String getPassword() { return password; }
//获取当前对象用户名 @Override public String getUsername() { return username; }
//判断账户是否过期 @Override public boolean isAccountNonExpired() { return true; }
//判断账户是否被锁 @Override public boolean isAccountNonLocked() { return !locked; }
//当前账户密码是否过期 @Override public boolean isCredentialsNonExpired() { return true; }
//判断当前账户是否可用 @Override public boolean isEnabled() { return enabled; } //省略getter/setter }
public class Role { private Integer id; private String name; private String nameZh; //省略getter/setter }
Service:
定义UserService实现UserDetailsService接口,并实现该接口中的loadUserByUsemame方法,该方法的参数就是用户登录时输入的用户名,通过用户名去数据库中查找用户,如果没有查找到用户,就抛出一个账户不存在的异常,如果查找到了用户,就继续查找该用户所具有的角色信息,并将获取到的user对象返回,再由系统提供DaoAuthenticationProvider 类去比对密码是否正确。
@Service public class UserService implements UserDetailsService { @Autowired UserMapper userMapper;
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userMapper.loadUserByUsername(username); if (user == null) { throw new UsernameNotFoundException("账户不存在!"); } user.setRoles(userMapper.getUserRolesByUid(user.getId())); return user; } }
Mapper:
@Mapper public interface UserMapper { User loadUserByUsername(String username); List<Role> getUserRolesByUid(Integer id); }
<mapper namespace="org.sang.security02.mapper.UserMapper"> <select id="loadUserByUsername" resultType="org.sang.security02.model.User"> select * from user where username=#{username} </select> <select id="getUserRolesByUid" resultType="org.sang.security02.model.Role"> select * from role r,user_role ur where r.id=ur.rid and ur.uid=#{id} </select> </mapper>
配置SpringSecurity
角色继承:
在上面定义了三种角色,但是这三种角色之间不具备任何关系,一般来说角色之间是有关系的,例如ROLE admin -般既具有admin的权限,又具有user的权限。那么如何配置
这种角色继承关系呢?在Spring Security 中只需要开发者提供一-个RoleHierarchy即可。
以上面的案例为例,假设ROLE_dba是终极大Boss,具有所有的权限,ROLE_admin具有ROLE _user 的权限,ROL_user 则是一个公共角色,即ROLE_admin继承ROLE_user、 ROLE_dba继承ROLE_ admin, 要描述这种继承关系,只需要开发者在Spring Security 的配置类中提供一个RoleHierarchy即可,代码如下:
@Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired UserService userService;
@Bean RoleHierarchy roleHierarchy() { RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl(); String hierarchy = "ROLE_dba > ROLE_admin ROLE_admin > ROLE_user"; roleHierarchy.setHierarchy(hierarchy); return roleHierarchy; } @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService); //没有将用户存在内存中,而是从数据库中取出来 } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() { @Override public <O extends FilterSecurityInterceptor> O postProcess(O object) { object.setSecurityMetadataSource(cfisms()); object.setAccessDecisionManager(cadm()); return object; } }) .and() .formLogin() .loginProcessingUrl("/login").permitAll() .and() .csrf().disable(); } @Bean CustomFilterInvocationSecurityMetadataSource cfisms() { return new CustomFilterInvocationSecurityMetadataSource(); } @Bean CustomAccessDecisionManager cadm() { return new CustomAccessDecisionManager(); } }
Controller:
@RestController public class HelloController { @GetMapping("/admin/hello") public String admin() { return "hello admin"; } @GetMapping("/db/hello") public String dba() { return "hello dba"; } @GetMapping("/user/hello") public String user() { return "hello user"; } }
以上是关于SpringBoot安全管理--基于数据库的认证的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot实现基于shiro安全框架的,配合thymeleaf模板引擎的用户认证和授权