1. 前言
Apache Shiro是一個功能強大且易於使用的Java安全框架,提供了認證,授權,加密,和會話管理。
Shiro有三大核心元件:
Subject:即當前使用者,在許可權管理的應用程式裡往往需要知道誰能夠操作什麼,誰擁有操作該程式的權利,shiro中則需要通過Subject來提供基礎的當前使用者資訊,Subject 不僅僅代表某個使用者,與當前應用互動的任何東西都是Subject,如網路爬蟲等。所有的Subject都要繫結到SecurityManager上,與Subject的互動實際上是被轉換為與SecurityManager的互動。
SecurityManager:即所有Subject的管理者,這是Shiro框架的核心元件,可以把他看做是一個Shiro框架的全域性管理元件,用於排程各種Shiro框架的服務。作用類似於SpringMVC中的DispatcherServlet,用於攔截所有請求並進行處理。
Realm:Realm是使用者的資訊認證器和使用者的許可權人證器,我們需要自己來實現Realm來自定義的管理我們自己系統內部的許可權規則。SecurityManager要驗證使用者,需要從Realm中獲取使用者。可以把Realm看做是資料來源。
2. 資料庫設計
2.1 User(使用者)
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`account` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'root', '超級使用者', 'root');
INSERT INTO `user` VALUES (2, 'user', '普通使用者', 'user');
INSERT INTO `user` VALUES (3, 'vip', 'VIP使用者', 'vip');
SET FOREIGN_KEY_CHECKS = 1;
複製程式碼
2.2 Role(角色)
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`desc` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES (1, 'admin', '超級管理員');
INSERT INTO `role` VALUES (2, 'user', '普通使用者');
INSERT INTO `role` VALUES (3, 'vip_user', 'VIP使用者');
SET FOREIGN_KEY_CHECKS = 1;
複製程式碼
2.3 Permission(許可權)
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for permission
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`permission` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '許可權名稱',
`desc` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '許可權描述',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of permission
-- ----------------------------
INSERT INTO `permission` VALUES (1, 'add', '增加');
INSERT INTO `permission` VALUES (2, 'update', '更新');
INSERT INTO `permission` VALUES (3, 'select', '檢視');
INSERT INTO `permission` VALUES (4, 'delete', '刪除');
SET FOREIGN_KEY_CHECKS = 1;
複製程式碼
2.4 User_Role(使用者-角色)
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NULL DEFAULT NULL,
`role_id` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Fixed;
-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES (1, 1, 1);
INSERT INTO `user_role` VALUES (2, 2, 2);
INSERT INTO `user_role` VALUES (3, 3, 3);
SET FOREIGN_KEY_CHECKS = 1;
複製程式碼
2.5 Role_Permission(角色-許可權)
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for role_permission
-- ----------------------------
DROP TABLE IF EXISTS `role_permission`;
CREATE TABLE `role_permission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_id` int(11) NULL DEFAULT NULL,
`permission_id` int(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 9 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Fixed;
-- ----------------------------
-- Records of role_permission
-- ----------------------------
INSERT INTO `role_permission` VALUES (1, 1, 1);
INSERT INTO `role_permission` VALUES (2, 1, 2);
INSERT INTO `role_permission` VALUES (3, 1, 3);
INSERT INTO `role_permission` VALUES (4, 1, 4);
INSERT INTO `role_permission` VALUES (5, 2, 3);
INSERT INTO `role_permission` VALUES (6, 3, 3);
INSERT INTO `role_permission` VALUES (7, 3, 2);
INSERT INTO `role_permission` VALUES (8, 2, 1);
SET FOREIGN_KEY_CHECKS = 1;
複製程式碼
3. 專案結構
4. 前期準備
4.1 匯入Pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
複製程式碼
4.2 application.yml
server:
port: 8903
spring:
application:
name: lab-user
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/laboratory?charset=utf8
username: root
password: root
mybatis:
type-aliases-package: cn.ntshare.laboratory.entity
mapper-locations: classpath:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
複製程式碼
4.3 實體類
4.3.1 User.java
@Data
@ToString
public class User implements Serializable {
private static final long serialVersionUID = -6056125703075132981L;
private Integer id;
private String account;
private String password;
private String username;
}
複製程式碼
4.3.2 Role.java
@Data
@ToString
public class Role implements Serializable {
private static final long serialVersionUID = -1767327914553823741L;
private Integer id;
private String role;
private String desc;
}
複製程式碼
4.4 Dao層
4.4.1 PermissionMapper.java
@Mapper
@Repository
public interface PermissionMapper {
List<String> findByRoleId(@Param("roleIds") List<Integer> roleIds);
}
複製程式碼
4.4.2 PermissionMapper.xml
<mapper namespace="cn.ntshare.laboratory.dao.PermissionMapper">
<sql id="base_column_list">
id, permission, desc
</sql>
<select id="findByRoleId" parameterType="List" resultType="String">
select permission
from permission, role_permission rp
where rp.permission_id = permission.id and rp.role_id in
<foreach collection="roleIds" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
</mapper>
複製程式碼
4.4.3 RoleMapper.java
@Mapper
@Repository
public interface RoleMapper {
List<Role> findRoleByUserId(@Param("userId") Integer userId);
}
複製程式碼
4.4.4 RoleMapper.xml
<mapper namespace="cn.ntshare.laboratory.dao.RoleMapper">
<sql id="base_column_list">
id, user_id, role_id
</sql>
<select id="findRoleByUserId" parameterType="Integer" resultType="Role">
select role.id, role
from role, user, user_role ur
where role.id = ur.role_id and ur.user_id = user.id and user.id = #{userId}
</select>
</mapper>
複製程式碼
4.4.5 UserMapper.java
@Mapper
@Repository
public interface UserMapper {
User findByAccount(@Param("account") String account);
}
複製程式碼
4.4.6 UserMapper.xml
<mapper namespace="cn.ntshare.laboratory.dao.UserMapper">
<sql id="base_column_list">
id, account, password, username
</sql>
<select id="findByAccount" parameterType="Map" resultType="User">
select
<include refid="base_column_list"/>
from user
where account = #{account}
</select>
</mapper>
複製程式碼
4.5 Service層
4.5.1 PermissionServiceImpl.java
@Service
public class PermissionServiceImpl implements PermissionService {
@Autowired
private PermissionMapper permissionMapper;
@Override
public List<String> findByRoleId(List<Integer> roleIds) {
return permissionMapper.findByRoleId(roleIds);
}
}
複製程式碼
4.5.2 RoleServiceImpl.java
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Override
public List<Role> findRoleByUserId(Integer id) {
return roleMapper.findRoleByUserId(id);
}
}
複製程式碼
4.5.3 UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findByAccount(String account) {
return userMapper.findByAccount(account);
}
}
複製程式碼
4.6. 系統返回狀態列舉與包裝函式
4.6.1 ServerResponseEnum.java
@AllArgsConstructor
@Getter
public enum ServerResponseEnum {
SUCCESS(0, "成功"),
ERROR(10, "失敗"),
ACCOUNT_NOT_EXIST(11, "賬號不存在"),
DUPLICATE_ACCOUNT(12, "賬號重複"),
ACCOUNT_IS_DISABLED(13, "賬號被禁用"),
INCORRECT_CREDENTIALS(14, "賬號或密碼錯誤"),
NOT_LOGIN_IN(15, "賬號未登入"),
UNAUTHORIZED(16, "沒有許可權")
;
Integer code;
String message;
}
複製程式碼
4.6.2 ServerResponseVO.java
@Getter
@Setter
@NoArgsConstructor
public class ServerResponseVO<T> implements Serializable {
private static final long serialVersionUID = -1005863670741860901L;
// 響應碼
private Integer code;
// 描述資訊
private String message;
// 響應內容
private T data;
private ServerResponseVO(ServerResponseEnum responseCode) {
this.code = responseCode.getCode();
this.message = responseCode.getMessage();
}
private ServerResponseVO(ServerResponseEnum responseCode, T data) {
this.code = responseCode.getCode();
this.message = responseCode.getMessage();
this.data = data;
}
private ServerResponseVO(Integer code, String message) {
this.code = code;
this.message = message;
}
/**
* 返回成功資訊
* @param data 資訊內容
* @param <T>
* @return
*/
public static<T> ServerResponseVO success(T data) {
return new ServerResponseVO<>(ServerResponseEnum.SUCCESS, data);
}
/**
* 返回成功資訊
* @return
*/
public static ServerResponseVO success() {
return new ServerResponseVO(ServerResponseEnum.SUCCESS);
}
/**
* 返回錯誤資訊
* @param responseCode 響應碼
* @return
*/
public static ServerResponseVO error(ServerResponseEnum responseCode) {
return new ServerResponseVO(responseCode);
}
}
複製程式碼
4.7 統一異常處理
當使用者身份認證失敗時,會丟擲UnauthorizedException
,我們可以通過統一異常處理來處理該異常
@RestControllerAdvice
public class UserExceptionHandler {
@ExceptionHandler(UnauthorizedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ServerResponseVO UnAuthorizedExceptionHandler(UnauthorizedException e) {
return ServerResponseVO.error(ServerResponseEnum.UNAUTHORIZED);
}
}
複製程式碼
5. 整合Shiro
5.1 UserRealm.java
/**
* 負責認證使用者身份和對使用者進行授權
*/
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private PermissionService permissionService;
// 使用者授權
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
User user = (User) principalCollection.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
List<Role> roleList = roleService.findRoleByUserId(user.getId());
Set<String> roleSet = new HashSet<>();
List<Integer> roleIds = new ArrayList<>();
for (Role role : roleList) {
roleSet.add(role.getRole());
roleIds.add(role.getId());
}
// 放入角色資訊
authorizationInfo.setRoles(roleSet);
// 放入許可權資訊
List<String> permissionList = permissionService.findByRoleId(roleIds);
authorizationInfo.setStringPermissions(new HashSet<>(permissionList));
return authorizationInfo;
}
// 使用者認證
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authToken;
User user = userService.findByAccount(token.getUsername());
if (user == null) {
return null;
}
return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}
}
複製程式碼
5.2 ShiroConfig.java
@Configuration
public class ShiroConfig {
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
@Bean
public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(userRealm());
return securityManager;
}
/**
* 路徑過濾規則
* @return
*/
@Bean
public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/");
Map<String, String> map = new LinkedHashMap<>();
// 有先後順序
map.put("/login", "anon"); // 允許匿名訪問
map.put("/**", "authc"); // 進行身份認證後才能訪問
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
/**
* 開啟Shiro註解模式,可以在Controller中的方法上新增註解
* @param securityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") DefaultSecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
複製程式碼
5.3 LoginController.java
@RestController
@RequestMapping("")
public class LoginController {
@PostMapping("/login")
public ServerResponseVO login(@RequestParam(value = "account") String account,
@RequestParam(value = "password") String password) {
Subject userSubject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(account, password);
try {
// 登入驗證
userSubject.login(token);
return ServerResponseVO.success();
} catch (UnknownAccountException e) {
return ServerResponseVO.error(ServerResponseEnum.ACCOUNT_NOT_EXIST);
} catch (DisabledAccountException e) {
return ServerResponseVO.error(ServerResponseEnum.ACCOUNT_IS_DISABLED);
} catch (IncorrectCredentialsException e) {
return ServerResponseVO.error(ServerResponseEnum.INCORRECT_CREDENTIALS);
} catch (Throwable e) {
e.printStackTrace();
return ServerResponseVO.error(ServerResponseEnum.ERROR);
}
}
@GetMapping("/login")
public ServerResponseVO login() {
return ServerResponseVO.error(ServerResponseEnum.NOT_LOGIN_IN);
}
@GetMapping("/auth")
public String auth() {
return "已成功登入";
}
@GetMapping("/role")
@RequiresRoles("vip")
public String role() {
return "測試Vip角色";
}
@GetMapping("/permission")
@RequiresPermissions(value = {"add", "update"}, logical = Logical.AND)
public String permission() {
return "測試Add和Update許可權";
}
}
複製程式碼
6. 測試
6.1 用root使用者登入
6.1.1 登入
6.1.2 驗證是否登入
6.1.3 測試角色許可權
6.1.4 測試使用者操作許可權
6.2 user使用者和vip使用者測試略
7. 總結
本文演示了SpringBoot極簡整合Shiro框架,實現了基礎的身份認證和授權功能,如有不足,請多指教。
後續可擴充套件的功能點有:
- 整合Redis實現Shiro的分散式會話
- 整合JWT實現單點登入功能