1.認識shiro 除Spring Security安全框架外,應用非常廣泛的就是Apache的強大又靈活的開源安全框架 Shiro,在國內使用量遠遠超過Spring Security。它能夠用於身份驗證、授權、加密和會話管理, 有易於理解的API,可以快速、輕鬆地構建任何應用程式。而且大部分人覺得 ...
1.認識shiro
除Spring Security安全框架外,應用非常廣泛的就是Apache的強大又靈活的開源安全框架 Shiro,在國內使用量遠遠超過Spring Security。它能夠用於身份驗證、授權、加密和會話管理, 有易於理解的API,可以快速、輕鬆地構建任何應用程式。而且大部分人覺得從Shiro入門要比 Spring Security 簡單。
1.1 認識Shiro的核心組件
Shiro有如下核心組件。
- Subject:代表當前“用戶”。與當前應用程式交互的任何東西都是Subject,如爬蟲、機器人、所有Subject都綁定到SecurityManager,與Subject的所有交互都會委托給 SecurityManager,Subject 是一個門面,SecurityManager 是實際的執行者。
- SecurityManager:與安全有關的操作都會與SecurityManager交互。它管理著所有 Subject,是Shiro的核心,員責與其他組件進行交互。
- Realm: Shiro從Realm中獲取安全數據(用戶、角色、許可權),SecurityManager 需要 從Realm中獲取相應的用戶信息進行比較用戶身份是否合法,也需要從Realm中得到用戶 相應的角色/許可權進行驗證,以確定用戶是否能進行操作。
2.實例:用shiro實現管理後臺的動態許可權功能
依賴:
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
2.1 創建實體
2.1.1 創建管理員實體
創建管理實體,用於存放管理員信息,見以下代碼:
package com.intehel.demo.domain;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
@Entity
@Data
public class Admin implements Serializable {
@Id
@GeneratedValue
private Integer id;
@Column(unique = true)
//賬號
private String username;
//名稱
private String name;
//密碼
private String password;
//鹽加密
private String salt;
//用戶狀態:0:創建未認證,等待驗證 1:正常狀態 2:用戶被鎖定
private byte state;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "SysUserRole",joinColumns = {@JoinColumn(name = "uid")},
inverseJoinColumns = {@JoinColumn(name = "roleId")})
private List<SysRole> rolesList;
}
2.1.2 創建許可權實體
許可權實體用於存放許可權數據,見以下代碼:
package com.intehel.demo.domain;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
@Entity
@Data
public class SysPermission implements Serializable {
@Id
@GeneratedValue
private Integer id;
private String name;
@Column(columnDefinition = "enum('menu','button')")
private String resourceType;
private String url;
private String permission;
private Long parentId;
private String parentIds;
private Boolean avaliable = Boolean.FALSE;
@ManyToMany
@JoinTable(name = "SysRolePermission",joinColumns = {@JoinColumn(name = "permissionId")},
inverseJoinColumns = {@JoinColumn(name = "roleId")})
private List<SysRole> rolesList;
}
2.1.3 創建角色實體
角色實體是管理員的角色,用於對管理員分組,並通過與許可權表映射來確定管理員的許可權,見以下代碼:
package com.intehel.demo.domain;
import lombok.Data;
import javax.persistence.*;
import java.util.List;
@Entity
@Data
public class SysRole {
@Id
@GeneratedValue
private Integer id;
@Column(unique = true)
private String role;
private String description;
private Boolean available = Boolean.FALSE;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "SysRolePermission",joinColumns = {@JoinColumn(name = "roleId")},
inverseJoinColumns = {@JoinColumn(name = "permissionId")})
private List<SysPermission> permissions;
@ManyToMany
@JoinTable(name = "SysUserRole",joinColumns = {@JoinColumn(name = "roleId")},
inverseJoinColumns = {@JoinColumn(name = "uid")})
private List<Admin> admins;
}
2.2 進行許可權配置
package com.intehel.demo.realm;
import com.intehel.demo.domain.Admin;
import com.intehel.demo.domain.SysPermission;
import com.intehel.demo.domain.SysRole;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
public class CustomerRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Admin adminInfo = (Admin) principalCollection.getPrimaryPrincipal();
for (SysRole role : adminInfo.getRolesList()) {
info.addRole(role.getRole());
for (SysPermission p:role.getPermissions()){
info.addStringPermission(p.getPermission());
}
}
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String username = (String) authenticationToken.getPrincipal();
System.out.println(authenticationToken.getCredentials());
Admin adminInfo = new Admin();
adminInfo.setUsername("long");
adminInfo.setPassword("longzhonghua");
adminInfo.setSalt("yan");
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
adminInfo,adminInfo.getPassword(),
ByteSource.Util.bytes(adminInfo.getSalt()),
getName()
);
return info;
}
}
2.3 將shiro註入到spring容器中
package com.intehel.demo.config;
import com.intehel.demo.realm.CustomerRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.shiro.mgt.SecurityManager;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
@Bean
@ConditionalOnMissingBean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
return defaultAdvisorAutoProxyCreator;
}
// 將自己驗證的方式加入到容器中
@Bean
public CustomerRealm customRealm() {
CustomerRealm customRealm = new CustomerRealm();
return customRealm;
}
//許可權管理,配置主要是Realm的管理認證
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager ();
defaultSecurityManager.setRealm(customRealm());
return defaultSecurityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String,String> map = new HashMap<>();
// 登出
map.put("/logout","logout");
// 對所有用戶進行認證
map.put("/**","authc");
//登錄
shiroFilterFactoryBean.setLoginUrl("/login");
// 首頁
shiroFilterFactoryBean.setSuccessUrl("/index");
// 錯誤頁面 認證不通過跳轉
shiroFilterFactoryBean.setUnauthorizedUrl("/error");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
2.4 編寫控制層
package com.intehel.demo.controller;
import com.intehel.demo.domain.Admin;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class LoginController {
@GetMapping("/login")
public String login(Admin user) {
if(StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
return "請輸入用戶名和密碼";
}
// 用戶認證信息
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(),user.getPassword());
try {
// 進行驗證,這裡可以捕獲異常,然後返回對應信息
subject.login(usernamePasswordToken);
}catch (UnknownAccountException e) {
log.error("用戶名不存在",e);
return "用戶名不存在";
} catch (AuthenticationException e) {
log.error("賬號或者密碼錯誤!",e);
return "賬號或者密碼錯誤!";
} catch (AuthorizationException e) {
log.error("沒有許可權!",e);
return "沒有許可權";
}
return "login success";
}
@RequiresRoles("admin")
@GetMapping("/admin")
public String admin() {
return "admin Success!";
}
@RequiresPermissions("query")
@GetMapping("/index")
public String index() {
return "index success";
}
@RequiresPermissions("add")
@GetMapping("/add")
public String add() {
return "add success";
}
}
2.5 測試許可權
(1)向sql中插入數據
INSERT INTO `admin` (`id`, `name`, `password`, `salt`, `state`, `username`) VALUES (1, '管理員', '32baebda76498588dabf64c6e8984097', 'yan', 0, 'long');
INSERT INTO `sys_permission` (`id`, `avaliable`, `name`, `parent_id`, `parent_ids`, `permission`, `resource_type`, `url`) VALUES (1, b'0', '用戶管理', 0, '0/', 'admin:view', 'menu', 'admin/list');
INSERT INTO `sys_permission` (`id`, `avaliable`, `name`, `parent_id`, `parent_ids`, `permission`, `resource_type`, `url`) VALUES (2, b'0', '用戶添加', 1, '0/1', 'admin:add', 'button', 'admin/add');
INSERT INTO `sys_permission` (`id`, `avaliable`, `name`, `parent_id`, `parent_ids`, `permission`, `resource_type`, `url`) VALUES (3, b'0', '用戶刪除', 1, '0/1', 'admin:del', 'button', 'admin/del');
INSERT INTO `sys_role` (`id`, `available`, `description`, `role`) VALUES (1, b'0', '管理員', 'admin');
INSERT INTO `sys_role_permission` (`role_id`, `permission_id`) VALUES (1, 1);
INSERT INTO `sys_role_permission` (`role_id`, `permission_id`) VALUES (1, 2);
INSERT INTO `sys_role_permission` (`role_id`, `permission_id`) VALUES (1, 3);
INSERT INTO `sys_user_role` (`role_id`, `uid`) VALUES (1, 1);
(2)測試登錄
2.6 對比 Spring Security 與 Shiro
(1)Shiro的特點
- 功能強大,且簡單、靈活。
- 擁有易於理解的API。
- 簡單的身份認證(登錄),支持多種數據源(LDAP、JDBC、Kerberos、ActiveDirectory等)。
- 支持對角色的簡單簽權,並且支持細粒度的簽權。
- 支持一級緩存,以提升應用程式的性能。
- 內置的基於POJO會話管理,適用於Web,以及非Web環境。
- 不跟任何的框架或容器捆綁,可以獨立運行。
(2)Spring Security 的特點。
- Shiro的功能它都有
- 對防止CSRF跨站、XSS跨站腳本可以很好地實現,對Oauth、OpenlD也有支持。Shiro 則需要開發者自己手動實現。
- 因為Spring Security是Spring自己的產品,所以對Spring的支持極好,但也正是因為這個,所以僅僅支持自己的產品,導致其捆綁到了 Spring框架,而不支持其他框架。
- Spring Security的許可權細粒度更高(這不是絕對的,Shiro也可以實現)。