目录
2、shiro 的相关 jar 包和使用注解需要用到的 aspectj 包
一、Shrio 简介
1、什么是 shiro ?
- Apache 的强大灵活的开源安全框架
- 四大部分:认证(Authentication)、授权(Authorization)、企业回话管理(Session Management)、安全加密(Cryptography)
2、shiro 整体框架
3、shiro 认证和授权的过程
二、SSM 整合 Shiro
1、前提
准备一个 SSM 项目的环境:https://blog.csdn.net/weidong_y/article/details/80800191
新建一个数据库,还有三张表:用户表、用户角色表、角色权限表。
2、shiro 的相关 jar 包和使用注解需要用到的 aspectj 包
<!-- shiro 相关依赖 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.2</version>
</dependency>
<!-- aop 注解包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
3、自定义 Realm
自定义的 Realm 是继承了 AuthorizingRealm 类,然后实现这个类下的两个方法:doGetAuthorizationInfo() 和 doGetAuthenticationInfo() 。代码中带有注释,就不一一解说功能了。
package com.shiro.realm;
import com.pojo.Users;
import com.service.RolesPermissionsService;
import com.service.UserRolesService;
import com.service.UserService;
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.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
public class CustomRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Autowired
private UserRolesService userRolesService;
@Autowired
private RolesPermissionsService rolesPermissionsService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String userName = (String) principals.getPrimaryPrincipal();
Set<String> roles = getRolesByUsername(userName);
Set<String> permissions = getPermissionsByUserName(userName);
// 设置用户的角色和权限
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.setStringPermissions(permissions);
simpleAuthorizationInfo.setRoles(roles);
return simpleAuthorizationInfo;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 1. 从主体传过来的认证信息中,获得用户名
String userName = (String)token.getPrincipal();
// 2. 通过用户名到数据库中获取凭证
String password = getPasswordByUserName(userName);
if( password == null ){
return null;
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName,password,"customRealm");
// 将加入的 盐 返回
authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(userName));
return authenticationInfo;
}
// 通过用户名从数据库中获取当前用户的权限数据
private Set<String> getPermissionsByUserName(String userName) {
List<String> list = rolesPermissionsService.queryPermissionsByUserName(userName);
if( list != null ) {
Set<String> sets = new HashSet<>(list);
return sets;
}else{
return null;
}
}
// 通过用户名从数据库中获取当前用户的角色数据
private Set<String> getRolesByUsername(String userName) {
List<String> list = userRolesService.queryRolesByUserName(userName);
if( list != null ){
Set<String> sets = new HashSet<>(list);
return sets;
}else{
return null;
}
}
// 通过用户名从数据库中获取当前用户的密码
private String getPasswordByUserName(String userName) {
Users user = userService.getUserByUserName(userName);
if( user != null ){
return user.getPassword();
}else{
return null;
}
}
public static void main(String[] args){
Md5Hash md5Hash = new Md5Hash("123456","Mark");
System.out.println(md5Hash);
}
}
自定义的 Realm 中还有三个自定义的方法:getPermissionsByUserName() 和 getRolesByUsername() 和 getPasswordByUserName()。主要就是实现从数据库获取相应的信息(调用服务层的接口)。getPermissionsByUserName() 根据用户名获取权限,需要联合两张表查询,没办法直接用 mybatis 实现,这里就简单介绍下,其他两个接口直接贴服务层代码。
① getPermissionsByUserName() 方法中
服务层:
@Override
public List<String> queryPermissionsByUserName(String userName) {
return rolesPermissionsMapper.queryPermissionsByUserName(userName);
}
dao层:
List<String> queryPermissionsByUserName(String userName);
<select id="queryPermissionsByUserName" resultType="String">
select permission
from user_roles ur,roles_permissions rp
where ur.username = #{userName}
and ur.role_name = rp.role_name
GROUP BY permission
</select>
② getRolesByUsername() 方法中
服务层:
@Override
public List<String> queryRolesByUserName(String userName) {
UserRolesExample example = new UserRolesExample();
example.createCriteria().andUsernameEqualTo(userName);
List<UserRoles> roleList = userRolesMapper.selectByExample(example);
List<String> list = new ArrayList<>();
for( int i=0; i<roleList.size(); i++ ){
list.add(roleList.get(i).getRoleName());
}
return list;
}
③ getPasswordByUserName() 方法中
服务层:
@Override
public Users getUserByUserName(String userName) {
UsersExample example = new UsersExample();
example.createCriteria().andUsernameEqualTo(userName);
return usersMapper.selectByExample(example).get(0);
}
4、shiro 的配置
在自己的 spring 配置下,新建两个配置文件 spring-shiro.xml 和 spring-aop.xml 用来存放 shiro 和 aop 注解的先关配置。下面是我的项目 spring 配置的目录。仅供参考。
这样配置的好处,就是在 web.xml 中整合 spring 的配置时候,可以直接只用泛型。
1)spring-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-lazy-init="true">
<!-- 创建 SecurityManager 对象-->
<bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
<property name="realm" ref="realm"></property>
</bean>
<!-- 创建自定义 realm -->
<bean class="com.shiro.realm.CustomRealm" id="realm">
<property name="credentialsMatcher" ref="credentialsMatcher"></property>
</bean>
<!-- 设置加密算法和加密的次数 -->
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher" id="credentialsMatcher">
<property name="hashAlgorithmName" value="md5"></property>
<property name="hashIterations" value="1"></property>
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"></property>
<!-- 配置用户的登录页面 -->
<property name="loginUrl" value="login.html"></property>
<!-- 配置用户没有权限跳转的页面 -->
<property name="unauthorizedUrl" value="403.html"></property>
<!-- 过滤器链 -->
<property name="filterChainDefinitions">
<!-- anon 指定排除认证的 uri -->
<!-- authc 指定需要认证的 uri -->
<value>
/login.html = anon
/subLogin = anon
/* = authc
</value>
</property>
</bean>
</beans>
2)spring-aop.xml
配置完 shiro 后,把 aop 的注解打开。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启 AOP 注解模式 -->
<aop:config proxy-target-class="true" />
<!-- 配置 shiro 的注解 -->
<bean class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"></property>
</bean>
</beans>
3)web.xml
需要在 web.xml 中配置下 shiro 的过滤器。一般直接放在"post乱码过虑器"后面较好。然后这里的 shiroFilter 需要跟 spring-shiro.xml 中的 org.apache.shiro.spring.web.ShiroFilterFactoryBean 所创建的 bean 的 id 一样。
<!-- shiro 过滤器 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
五、验证
到这里,shiro 与 SSM 的整合就完成了。接下来我们编写一个页面和 Controller 来测试一下是否真的有用。
1、登录页面 login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="subLogin" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
2、控制层 UserController.java
@RequestMapping(value = "/subLogin",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
@ResponseBody
public String subLogin(Users users){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(users.getUsername(),users.getPassword());
try{
subject.login(token);
}catch (AuthenticationException e){
e.printStackTrace();
return e.getMessage();
}
// 通过代码的方式来判断 当前用户是否有 admin 角色权限
// 角色权限的判断也可以通过注解的方式,参考下面的代码
if( subject.hasRole("admin") ){
return "有admin权限";
}
return "无admin权限";
}
// 通过注解的方式来判断当前用户是否有 user:select 的权限
@RequiresPermissions("user:select")
@RequestMapping(value = "/testRole",method = RequestMethod.GET)
@ResponseBody
public String testRole(){
return "testRole success";
}
启动 tomcat 自己测试下就行了。
@RequiresPermissions 注解的3种用法。
//符合index:hello权限要求
@RequiresPermissions("index:hello")
//必须同时复核index:hello和index:world权限要求
@RequiresPermissions({"index:hello","index:world"})
//符合index:hello或index:world权限要求即可
@RequiresPermissions(value={"index:hello","index:world"},logical=Logical.OR)
推荐阅读
Shiro 跳转不到指定的错误页面解决方法
有什么问题可以在评论区留言!!!