主要步骤
1、创建数据库表(user,role,user_role,permission,role_permission),这里为了测试方便只创建了前三个表
2、配置连接池和ORM框架,测试使用的时druid数据源和mybatis
3、配置SecurityConfig继承WebSecurityConfigurerAdapter,并添加@EnableWebSecurity(组合注解),重新configure方法
4、编写一个Service类并实现UserDetailsService接口,重写loadUserByUsername方法
1、数据库
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', 'VIP1');
INSERT INTO `role` VALUES ('2', 'VIP2');
INSERT INTO `role` VALUES ('3', 'VIP3');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user 密码为:PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123");
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '{bcrypt}$2a$10$NhTcM87XJrKe8EbdtpaVqu/auoMIvVboBRWNXhCAsRCeOn6OIAUHG');
INSERT INTO `user` VALUES ('2', 'lisi', '{bcrypt}$2a$10$NhTcM87XJrKe8EbdtpaVqu/auoMIvVboBRWNXhCAsRCeOn6OIAUHG');
INSERT INTO `user` VALUES ('3', 'wangwu', '{bcrypt}$2a$10$NhTcM87XJrKe8EbdtpaVqu/auoMIvVboBRWNXhCAsRCeOn6OIAUHG');
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`userId` int(3) DEFAULT NULL,
`roleId` int(3) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES ('1', '1', '1');
INSERT INTO `user_role` VALUES ('2', '1', '2');
INSERT INTO `user_role` VALUES ('3', '2', '2');
INSERT INTO `user_role` VALUES ('4', '2', '3');
INSERT INTO `user_role` VALUES ('5', '3', '1');
INSERT INTO `user_role` VALUES ('6', '3', '3');
注意数据库user表密码使用的是:PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123");
SpringSecurity5升级后不支持明文密码,若不使用Encoder,会抛java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"异常
或者在明文密码前添加{noop},这样spring security就不会进行解密
2、配置druid数据源和mybatis
application.properties配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/cache?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=xxxxxxx
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#druid其他配置,需要在配置类中关联
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.filters=stat,wall,log4j
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.useGlobalDataSourceStat=true
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
Druid配置类:DruidConfig
//导入druid数据源
@Configuration
public class DruidConfig {
//把yml中的配置生效
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
/*Springboot 1.5 的写法*/
//Map<String,String> initParams = new HashMap<>();
//initParams.put("loginUsername","admin");
//initParams.put("loginPassword","123456");
//initParams.put("allow","");
//initParams.put("deny","192.168.15.21");
//bean.setInitParameters(initParams);
/*Springboot 2.1.9不需要再建HashMap*/
bean.addInitParameter("loginUsername","admin");
bean.addInitParameter("loginPassword","123456");
bean.addInitParameter("allow",""); //默认就是允许所有访问
bean.addInitParameter("deny","192.168.15.21");
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
/*Springboot 1.5 的写法*/
//Map<String,String> initParams = new HashMap<>();
//initParams.put("exclusions","*.js,*.css,/druid/*");
//bean.setInitParameters(initParams);
bean.addInitParameter("exclusions","*.js,*.css,/druid/*");
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
3、WebSecurityConfigurerAdapter子类(自定义)
SecurityConfig
@EnableWebSecurity //改为@Configuration也可以
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3") //需要VIP3角色
.antMatchers("/access").access("hasRole('VIP3')") //需要VIP3
.antMatchers("/user/**").hasAnyRole("VIP1","VIP2","VIP3") //只要有其中一个角色就可以
.antMatchers("/hello/**").authenticated(); //只要认证就可以
//开启自动配置的登陆功能,效果,如果没有登陆,没有权限就会来到登陆页面
//1、默认post形式的 /login代表处理登陆
//2、重定向到/login?error表示登陆失败
//3、一但定制loginPage;那么 loginPage的post请求就是登陆
http.formLogin()
.usernameParameter("user") //指定参数名 默认username
.passwordParameter("pwd") //指定参数名 默认password
.loginPage("/userlogin") //指定登录页面 默认post方式的/login
.permitAll();
//.successForwardUrl(String forwardUrl),.failureForwardUrl(String forwardUrl)指定登录成功/失败的跳转页面
//.successHandler(AuthenticationSuccessHandler handler),.failureHandler(AuthenticationFailureHandler handler) 如果是前后的分离的项目可以用这个方法
/*.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
Map<String,Object> map = new HashMap<>();
map.put("status",200);
map.put("msg","登录成功");
map.put("data",authentication.getPrincipal());
String result = new ObjectMapper().writeValueAsString(map);
out.write(result);
out.flush();
out.close();
}
})
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
Map<String,Object> map = new HashMap<>();
map.put("status",400);
Stirng msg = "登录失败";
if (exception instanceof LockedException) {
msg = "账户被锁定,请联系管理员!";
} else if (exception instanceof CredentialsExpiredException) {
msg = "密码过期,请联系管理员!";
} else if (exception instanceof AccountExpiredException) {
msg = "账户过期,请联系管理员!";
} else if (exception instanceof DisabledException) {
msg = "账户被禁用,请联系管理员!";
} else if (exception instanceof BadCredentialsException) {
msg = "用户名或者密码输入错误,请重新输入!";
}
map.put("msg",msg);
String result = new ObjectMapper().writeValueAsString(map);
out.write(result);
out.flush();
out.close();
}
})*/
//开启自动配置的注销功能。
//1、访问 /logout 表示用户注销,清空session
//2、默认注销成功会返回 /login?logout 页面;
http.logout().logoutSuccessUrl("/");//注销成功以后来到首页
/* 前后端分离的项目使用logoutSuccessHandler
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write(new ObjectMapper().writeValueAsString(RespBean.ok("注销成功!")));
out.flush();
out.close();
}
})
*/
//开启记住我功能
http.rememberMe().rememberMeParameter("remeber");
//登陆成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登录
//点击注销会删除cookie
}
/*@Override //用于添加内存中的用户、密码、权限
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//super.configure(auth);
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
auth.inMemoryAuthentication()
.withUser("zhangsan").password(encoder.encode("123")).roles("VIP1","VIP2")
.and()
.withUser("lisi").password(encoder.encode("123")).roles("VIP2,VIP3")
.and()
.withUser("wangwu").password(encoder.encode("123")).roles("VIP1","VIP3");
}*/
}
4、UserDetailsService实现类(自定义)
MyUserDetailsService
SpringSecurity中Role和Authority区别,系统在添加Role时会添加ROLE_前缀,而Authority不会,所以在重写的loadUserByUsername中添加了前缀后,在SecurityConfig重写的configure方法中添加页面权限应该使用hasRole,在html中使用<sec:authorize="hasRole('VIP1')">或<sec:authorize="hasAuthority('ROLE_VIP1')">,若没有添加前缀,在SecurityConfig重写的configure方法中添加页面权限应该使用hasAuthority,html中使用<sec:authorize="hasAuthority('VIP1')">
Role和Authority区别参考https://www.cnblogs.com/Rocky_/p/11799772.html
@Service
public class MyUserDetailsService implements UserDetailsService {
@Resource
MyMapper myMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Collection<GrantedAuthority> authorities = new ArrayList<>();
User user = myMapper.getUserByUsername(username); //这里也可以让User类去实现UserDetails类,实现里边的方法,然后直接返回这个User
List<Role> roles = myMapper.getRolesByUserId(user.getId());
for(Role role:roles){
authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
}
return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
}
}
MyMapper,为了简单直接写在了一个mapper里
@Mapper //或者在配置类或springboot主程序上添加@MapperScan("自己的mapper包")
public interface MyMapper {
@Select("select * from user where username=#{username}")
User getUserByUsername(String username);
@Select("select * from role where id in (select roleId from user_role where userId=#{userId})")
List<Role> getRolesByUserId(int userId);
}
前端,需导入themeleaf及thymeleaf-extras-springsecurity5
KungfuController用于前端访问
@Controller
public class KungfuController {
private final String PREFIX = "pages/";
/**
* 欢迎页
* @return
*/
@GetMapping("/")
public String index() {
return "welcome";
}
/**
* 登陆页
* @return
*/
@GetMapping("/userlogin")
public String loginPage() {
return PREFIX+"login";
}
/**
* level1页面映射
* @param path
* @return
*/
@GetMapping("/level1/{path}")
public String level1(@PathVariable("path")String path) {
return PREFIX+"level1/"+path;
}
/**
* level2页面映射
* @param path
* @return
*/
@GetMapping("/level2/{path}")
public String level2(@PathVariable("path")String path) {
return PREFIX+"level2/"+path;
}
/**
* level3页面映射
* @param path
* @return
*/
@GetMapping("/level3/{path}")
public String level3(@PathVariable("path")String path) {
return PREFIX+"level3/"+path;
}
}
welcome.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<div sec:authorize="!isAuthenticated()">
<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</a></h2>
</div>
<div sec:authorize="isAuthenticated()">
<h2><span sec:authentication="name"></span>,您好,您的角色有:
<span sec:authentication="principal.authorities"></span></h2>
<form th:action="@{/logout}" method="post">
<input type="submit" value="注销"/>
</form>
</div>
<hr>
<div sec:authorize="hasRole('VIP1')"><!--注意使用的是hasRole,需要在MyUserDetailsService重写的loadUserByUsername方法中Collection<GrantedAuthority> authorities中添加的rolename添加ROLE_前缀-->
<h3>普通武功秘籍</h3>
<ul>
<li><a th:href="@{/level1/1}">罗汉拳</a></li>
<li><a th:href="@{/level1/2}">武当长拳</a></li>
<li><a th:href="@{/level1/3}">全真剑法</a></li>
</ul>
</div>
<div sec:authorize="hasRole('VIP2')">
<h3>高级武功秘籍</h3>
<ul>
<li><a th:href="@{/level2/1}">太极拳</a></li>
<li><a th:href="@{/level2/2}">七伤拳</a></li>
<li><a th:href="@{/level2/3}">梯云纵</a></li>
</ul>
</div>
<div sec:authorize="hasRole('VIP3')">
<h3>绝世武功秘籍</h3>
<ul>
<li><a th:href="@{/level3/1}">葵花宝典</a></li>
<li><a th:href="@{/level3/2}">龟派气功</a></li>
<li><a th:href="@{/level3/3}">独孤九剑</a></li>
</ul>
</div>
</body>
</html>
login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎登陆武林秘籍管理系统</h1>
<hr>
<div align="center">
<form th:action="@{/userlogin}" method="post">
用户名:<input name="user"/><br>
密码:<input name="pwd"><br/>
<input type="checkbox" name="remeber"> 记住我<br/>
<input type="submit" value="登陆">
</form>
</div>
</body>
</html>
pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.crsbg</groupId>
<artifactId>cache</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cache</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
开启方法级别的安全注解
1、在SecurityConfig配置类添加@EnableGlobalMethodSecutiry注解
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
2、在Service的方法上添加@PreAuthorize或@Secured注解(prePostEnabled=true开启preAuthorize和postAuthorize注解,securedEnabled = true开启Secured注解)
@PreAuthorize("hasRole('admin')")
public String admin(){
return "admin";
}
@Secured("ROLE_user")
public String user(){
return "user";
}