目录
整合Mybatis框架
1、Maven依赖
<!-->spring-boot 整合security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- springboot 整合mybatis框架 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2、application.yml
# 配置freemarker
spring:
freemarker:
# 设置模板后缀名
suffix: .ftl
# 设置文档类型
content-type: text/html
# 设置页面编码格式
charset: UTF-8
# 设置页面缓存
cache: false
# 设置ftl文件路径
template-loader-path:
- classpath:/templates
# 设置静态文件路径,js,css等
mvc:
static-path-pattern: /static/**
####整合数据库层
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/rbac_db
username: root
password: root
# druid 连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
3、导入mapper
public interface UserMapper {
// 查询用户信息
@Select(" select * from sys_user where username = #{userName}")
User findByUsername(@Param("userName") String userName);
// 查询用户的权限
@Select(" select permission.* from sys_user user" + " inner join sys_user_role user_role"
+ " on user.id = user_role.user_id inner join "
+ "sys_role_permission role_permission on user_role.role_id = role_permission.role_id "
+ " inner join sys_permission permission on role_permission.perm_id = permission.id where user.username = #{userName};")
List<Permission> findPermissionByUsername(@Param("userName") String userName);
}
public interface PermissionMapper {
// 查询苏所有权限
@Select(" select * from sys_permission ")
List<Permission> findAllPermission();
}
4、动态查询账号
使用UserDetailsService实现动态查询数据库验证账号
@Component
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 1.根据数据库查询,用户是否登陆
User user = userMapper.findByUsername(username);
// 2.查询该用户信息权限
if (user != null) {
// 设置用户权限
List<Permission> listPermission = userMapper.findPermissionByUsername(username);
System.out.println("用户信息权限:" + user.getUsername() + ",权限:" + listPermission.toString());
if (listPermission != null && listPermission.size() > 0) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Permission permission : listPermission) {
// 添加用户权限
authorities.add(new SimpleGrantedAuthority(permission.getPermTag()));
}
// 设置用户权限
user.setAuthorities(authorities);
}
}
return user;
}
}
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// // 添加admin账号
// auth.inMemoryAuthentication().withUser("admin").password("123456").
// authorities("showOrder","addOrder","updateOrder","deleteOrder");
// // 添加userAdd账号
// auth.inMemoryAuthentication().withUser("userAdd").password("123456").authorities("showOrder","addOrder");
// // 如果想实现动态账号与数据库关联 在该地方改为查询数据库
auth.userDetailsService(myUserDetailsService);
}
5、密码使用MD5加密
public class MD5Util {
private static final String SALT = "mayikt";
public static String encode(String password) {
password = password + SALT;
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
throw new RuntimeException(e);
}
char[] charArray = password.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
public static void main(String[] args) {
System.out.println(MD5Util.encode("123456"));
}
}
auth.userDetailsService(myUserDetailsService).passwordEncoder(new PasswordEncoder() {
//验证密码
public boolean matches(CharSequence rawPassword, String encodedPassword) {
String rawPass= MD5Util.encode((String)rawPassword);
boolean result = rawPass.equals(encodedPassword);
return result;
}
// 加密密码
public String encode(CharSequence rawPassword) {
return MD5Util.encode((String)rawPassword);
}
});
6、动态请求资源
// 配置拦截请求资源
protected void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests = http
.authorizeRequests();
// 查询数据库获取权限列表
List<Permission> listPermission = permissionMapper.findAllPermission();
for (Permission permission : listPermission) {
authorizeRequests.antMatchers(permission.getUrl()).hasAuthority(permission.getPermTag());
}
authorizeRequests.antMatchers("/login").permitAll().antMatchers("/**").fullyAuthenticated().and().formLogin()
.loginPage("/login").successHandler(successHandler).failureHandler(failureHandler).and().csrf()
.disable();
}