一、什麼是SpringSecurity
Spring Security是一個能夠爲基於Spring的企業應用系統提供聲明式的安全訪問控制解決方案的安全框架。它提供了一組可以在Spring應用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反轉Inversion of Control ,DI:Dependency Injection 依賴注入)和AOP(面向切面編程)功能,爲應用系統提供聲明式的安全訪問控制功能,減少了爲企業系統安全控制編寫大量重複代碼的工作。
參考百度百科:https://baike.baidu.com/item/spring security/8831652?fr=aladdin
SpringSecurity官網:https://spring.io/projects/spring-security
二、應用場景
Security在很多企業中作爲後臺角色權限框架、授權認證oauth2.0 、安全防護(防止跨站點請求)、Session攻擊、非常容易融合SpringMVC使用等
三、環境搭建
實現效果
admin賬戶 所有請求都有權限訪問
userAdd賬戶 只能訪問查詢和添加訂單
spring-security兩種模式
formLogin模式 : 表單提交認證模式 (應用廣泛)
httpBasic模式 :瀏覽器與服務器做認證授權
關於httpBasic模式:
在HTTP協議進行通信的過程中,HTTP協議定義了基本認證過程以允許HTTP服務器對WEB瀏覽器進行用戶身份證的方法,當一個客戶端向HTTP服務 器進行數據請求時,如果客戶端未被認證,則HTTP服務器將通過基本認證過程對客戶端的用戶名及密碼進行驗證,以決定用戶是否合法。客戶端在接收到HTTP服務器的身份認證要求後,會提示用戶輸入用戶名及密碼,然後將用戶名及密碼以BASE64加密,加密後的密文將附加於請求信息中, 如當用戶名爲toov5,密碼爲:123456時,客戶端將用戶名和密碼用“:”合併,並將合併後的字符串用BASE64加密爲密文,並於每次請求數據 時,將密文附加於請求頭(Request Header)中。HTTP服務器在每次收到請求包後,根據協議取得客戶端附加的用戶信息(BASE64加密的用戶名和密碼),解開請求包,對用戶名及密碼進行驗證,如果用 戶名及密碼正確,則根據客戶端請求,返回客戶端所需要的數據;否則,返回錯誤代碼或重新要求客戶端提供用戶名及密碼。
RBAC權限模型:
基於角色的權限訪問控制(Role-Based Access Control)作爲傳統訪問控制(自主訪問,強制訪問)的有前景的代替受到廣泛的關注。在RBAC中,權限與角色相關聯,用戶通過成爲適當角色的成員而得到這些角色的權限。這就極大地簡化了權限的管理。在一個組織中,角色是爲了完成各種工作而創造,用戶則依據它的責任和資格來被指派相應的角色,用戶可以很容易地從一個角色被指派到另一個角色。角色可依新的需求和系統的合併而賦予新的權限,而權限也可根據需要而從某角色中回收。角色與角色的關係可以建立起來以囊括更廣泛的客觀情況。
httpStatus:狀態碼
401:未授權
403:權限不足
maven依賴:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<!-- 管理依賴 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.M7</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- SpringBoot整合Web組件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- springboot整合freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-->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>
</dependencies>
<!-- 注意: 這裏必須要添加, 否者各種依賴有問題 -->
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
controller:
@Controller
public class OrderController {
// 首頁
@RequestMapping("/")
public String index() {
return "index";
}
// 查詢訂單
@RequestMapping("/showOrder")
public String showOrder() {
return "showOrder";
}
// 添加訂單
@RequestMapping("/addOrder")
public String addOrder() {
return "addOrder";
}
// 修改訂單
@RequestMapping("/updateOrder")
public String updateOrder() {
return "updateOrder";
}
// 刪除訂單
@RequestMapping("/deleteOrder")
public String deleteOrder() {
return "deleteOrder";
}
// 自定義登陸頁面
@GetMapping("/login")
public String login() {
return "login";
}
}
對於403錯誤碼的處理:
@Controller
public class ErrorController {
@RequestMapping("/error/403")
public String error() {
return "/error/403";
}
}
config:攔截請求路徑與權限的配置:
對於fromLogin登錄頁面的修改自定義 關閉csdrf 配置loginpage就OK了
這裏查詢認證用戶與對應權限都是通過數據庫來進行查詢。
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationSuccessHandler successHandler;
@Autowired
private MyAuthenticationFailureHandler failureHandler;
@Autowired
private MyUserDetailService myUserDetailService;
@Autowired
private PermissionMapper permissionMapper;
//用戶認證信息
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// //設置用戶賬號信息和權限
// auth.inMemoryAuthentication().withUser("admin").password("123456").authorities("addOrder","showOrder","updateOrder","deleteOrder");
// //添加userAdd賬號
// auth.inMemoryAuthentication().withUser("userAdd").password("123456").authorities("showOrder","addOrder");
auth.userDetailsService(myUserDetailService).passwordEncoder(new PasswordEncoder() {
//對錶單密碼進行加密
public String encode(CharSequence rawPassword) {
// System.err.println("form ..."+rawPassword);
return MD5Util.encode((String)rawPassword);
}
//加密的密碼與數據庫密碼進行比對
//rawPassword 表單密碼 encodedPassword數據庫密碼
public boolean matches(CharSequence rawPassword, String encodedPassword) {
System.out.println("rawPassword:"+rawPassword+",encodedPassword:"+encodedPassword);
//返回true代表認證成功,false失敗
return MD5Util.encode((String)rawPassword).equals(encodedPassword);
}
});
}
//配置httpSecurity攔截資源
@Override
protected void configure(HttpSecurity http) throws Exception {
// http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
// http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin();
//如何進行權限控制 給每一個請求路徑分配一個權限名稱,然後賬號只要關聯該名稱,就可以有訪問權限
// http.authorizeRequests()
// //配置相關權限
// .antMatchers("/showOrder").hasAnyAuthority("showOrder")
// .antMatchers("/addOrder").hasAnyAuthority("addOrder")
// .antMatchers("/updateOrder").hasAnyAuthority("updateOrder")
// .antMatchers("/deleteOrder").hasAnyAuthority("deleteOrder")
// //自定義登錄界面,不攔截登錄請求
// .antMatchers("/login").permitAll()
// .antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login")
// .successHandler(successHandler)
//// .failureHandler(failureHandler)
// .and().csrf().disable();
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests = http.authorizeRequests();
List<Permission> permissionList = permissionMapper.findAllPermission();
if (permissionList != null && permissionList.size() > 0) {
permissionList.stream().forEach(permission -> {
//設置權限
authorizeRequests.antMatchers(permission.getUrl()).hasAnyAuthority(permission.getPermTag());
});
}
authorizeRequests.antMatchers("/login").permitAll()
.antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").successHandler(successHandler).failureHandler(failureHandler)
.and().csrf().disable();
}
// @Bean
// public static NoOpPasswordEncoder passwordEncoder() {
// return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
// }
}
配置默認錯誤頁面:
/**
* 自定義 WEB 服務器參數 可以配置默認錯誤頁面
*/
@Configuration
public class WebServerAutoConfiguration {
@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
return factory;
}
}
數據庫相關配置:
sql腳本:
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50556
Source Host : localhost:3306
Source Database : rbac_db
Target Server Type : MYSQL
Target Server Version : 50556
File Encoding : 65001
Date: 2018-11-13 18:29:33
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for sys_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_permission`;
CREATE TABLE `sys_permission` (
`id` int(10) NOT NULL,
`permName` varchar(50) DEFAULT NULL,
`permTag` varchar(50) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL COMMENT '請求url',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_permission
-- ----------------------------
INSERT INTO `sys_permission` VALUES ('1', '查詢訂單', 'showOrder', '/showOrder');
INSERT INTO `sys_permission` VALUES ('2', '添加訂單', 'addOrder', '/addOrder');
INSERT INTO `sys_permission` VALUES ('3', '修改訂單', 'updateOrder', '/updateOrder');
INSERT INTO `sys_permission` VALUES ('4', '刪除訂單', 'deleteOrder', '/deleteOrder');
-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` int(10) NOT NULL,
`roleName` varchar(50) DEFAULT NULL,
`roleDesc` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES ('1', 'admin', '管理員');
INSERT INTO `sys_role` VALUES ('2', 'add_user', '添加管理員');
-- ----------------------------
-- Table structure for sys_role_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_permission`;
CREATE TABLE `sys_role_permission` (
`role_id` int(10) DEFAULT NULL,
`perm_id` int(10) DEFAULT NULL,
KEY `FK_Reference_3` (`role_id`),
KEY `FK_Reference_4` (`perm_id`),
CONSTRAINT `FK_Reference_4` FOREIGN KEY (`perm_id`) REFERENCES `sys_permission` (`id`),
CONSTRAINT `FK_Reference_3` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_role_permission
-- ----------------------------
INSERT INTO `sys_role_permission` VALUES ('1', '1');
INSERT INTO `sys_role_permission` VALUES ('1', '2');
INSERT INTO `sys_role_permission` VALUES ('1', '3');
INSERT INTO `sys_role_permission` VALUES ('1', '4');
INSERT INTO `sys_role_permission` VALUES ('2', '1');
INSERT INTO `sys_role_permission` VALUES ('2', '2');
-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` int(10) NOT NULL,
`username` varchar(50) DEFAULT NULL,
`realname` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`createDate` date DEFAULT NULL,
`lastLoginTime` date DEFAULT NULL,
`enabled` int(5) DEFAULT NULL,
`accountNonExpired` int(5) DEFAULT NULL,
`accountNonLocked` int(5) DEFAULT NULL,
`credentialsNonExpired` int(5) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES ('1', 'admin', '張三', '15a013bcac0c50049356b322e955035e\r\n', '2018-11-13', '2018-11-13', '1', '1', '1', '1');
INSERT INTO `sys_user` VALUES ('2', 'userAdd', '小余', '15a013bcac0c50049356b322e955035e\r\n', '2018-11-13', '2018-11-13', '1', '1', '1', '1');
-- ----------------------------
-- Table structure for sys_user_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`user_id` int(10) DEFAULT NULL,
`role_id` int(10) DEFAULT NULL,
KEY `FK_Reference_1` (`user_id`),
KEY `FK_Reference_2` (`role_id`),
CONSTRAINT `FK_Reference_2` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`id`),
CONSTRAINT `FK_Reference_1` FOREIGN KEY (`user_id`) REFERENCES `sys_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_user_role
-- ----------------------------
INSERT INTO `sys_user_role` VALUES ('1', '1');
INSERT INTO `sys_user_role` VALUES ('2', '2');
實體類Entity: 用戶信息表的字段都是框架底層封裝好的,所以要進行對應,必須實現UserDetails接口
// 用戶信息表
@Data
public class User implements UserDetails {
/*用戶ID*/
private Integer id;
/*用戶名稱*/
private String username;
/*真實姓名*/
private String realname;
/*密碼*/
private String password;
/*創建日期*/
private Date createDate;
/*最後登錄時間*/
private Date lastLoginTime;
/*是否可用*/
private boolean enabled;
/*是否過期*/
private boolean accountNonExpired;
/*是否鎖定*/
private boolean accountNonLocked;
/*證書是否過期*/
private boolean credentialsNonExpired;
// 用戶所有權限
private List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
}
// 角色信息表
@Data
public class Role {
private Integer id;
private String roleName;
private String roleDesc;
}
@Data
public class Permission {
private Integer id;
// 權限名稱
private String permName;
// 權限標識
private String permTag;
// 請求url
private String url;
}
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();
}
AuthenticationFailureHandler 認證失敗接口
AuthenticationSuccessHandler 認證成功接口
成功和失敗的處理:
成功:
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
// 用戶認證成功
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth)
throws IOException, ServletException {
System.out.println("用戶登陸成功");
res.sendRedirect("/");
}
}
失敗:
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException auth)
throws IOException, ServletException {
System.out.println("用戶認證失敗");
res.sendRedirect("http://www.baidu.com");
}
}
MD5加密utils:
public class MD5Util {
// 加鹽
private static final String SALT = "xwhy";
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"));
}
}
MyUserDetailService: 設置用戶動態信息,認證用戶,給用戶分配權限
@Service
public class MyUserDetailService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.findByUsername(username);
if(!Objects.isNull(user)){
List<Permission> permissionList = userMapper.findPermissionByUsername(username);
if(permissionList!=null&&permissionList.size()>0){
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
permissionList.stream().forEach(e->{
authorities.add(new SimpleGrantedAuthority(e.getPermTag()));
});
user.setAuthorities(authorities);
}
}
return user;
}
}
啓動類:
@SpringBootApplication
@MapperScan("com.xwhy.mapper")
public class AppSecurity {
public static void main(String[] args) {
SpringApplication.run(AppSecurity.class,args);
}
}
配置文件:
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: 123456
# druid 連接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
相關頁面:
login.ftl:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>每特教育--權限控制登陸系統</h1>
<form action="/login" method="post">
<span>用戶名稱</span><input type="text" name="username" /> <br>
<span>用戶密碼</span><input type="password" name="password" /> <br>
<input type="submit" value="登陸">
</form>
<#if RequestParameters['error']??>
用戶名稱或者密碼錯誤
</#if>
</body>
</html>