第一部分 什么是Apache Shiro



1、什么是 apache shiro :


Apache Shiro是一个功能强大且易于使用的Java安全框架,提供了认证,授权,加密,和会话管理

如同 Spring security 一样都是是一个权限安全框架,但是与Spring Security相比,在于他使用了和比较简洁易懂的认证和授权方式。

 



2、Apache Shiro 的三大核心组件:


1、Subject :当前用户的操作

2、SecurityManager:用于管理所有的Subject

3、Realms:用于进行权限信息的验证


Subject:即当前用户,在权限管理的应用程序里往往需要知道谁能够操作什么,谁拥 有操作该程序的权利,shiro中则需要通过Subject来提供基础的当前用户信息,Subject 不仅仅代表某个用户,也可以是第三方进程、后台帐户(Daemon Account)或其他类似事物。

SecurityManager:即所有Subject的管理者,这是Shiro框架的核心组件,可以把他看做是一个Shiro框架的全局管理组件,用于调度各种Shiro框架的服务。

Realms:Realms则是用户的信息认证器和用户的权限人证器,我们需要自己来实现Realms来自定义的管理我们自己系统内部的权限规则。

 



3、Authentication 和 Authorization


在shiro的用户权限认证过程中其通过两个方法来实现:

1、Authentication:是验证用户身份的过程。

2、Authorization:是授权访问控制,用于对用户进行的操作进行人证授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等。




4、其他组件:


除了以上几个组件外,Shiro还有几个其他组件:

1、SessionManager :Shiro为任何应用提供了一个会话编程范式。

2、CacheManager :对Shiro的其他组件提供缓存支持。 

 




5、Shiro 完整架构图: 

Springmvc+shiro


图片转自:http://kdboy.iteye.com/blog/1154644


第二部分 Apache Shiro 整合Spring的Web程序构建

 1:shiro的配置,通过maven加入shiro相关jar包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!-- shiro --> 
 <dependency> 
  <groupId>org.apache.shiro</groupId> 
  <artifactId>shiro-core</artifactId> 
  <version>1.2.1</version> 
 </dependency> 
 <dependency> 
  <groupId>org.apache.shiro</groupId> 
  <artifactId>shiro-web</artifactId> 
  <version>1.2.1</version> 
 </dependency> 
 <dependency> 
  <groupId>org.apache.shiro</groupId> 
  <artifactId>shiro-ehcache</artifactId> 
  <version>1.2.1</version> 
 </dependency> 
 <dependency> 
  <groupId>org.apache.shiro</groupId> 
  <artifactId>shiro-spring</artifactId> 
  <version>1.2.1</version> 
 </dependency>

2 :在web.xml中添加shiro过滤器

1
2
3
4
5
6
7
8
9
<!-- 配置shiro的核心拦截器 --> 
 <filter> 
  <filter-name>shiroFilter</filter-name> 
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class
 </filter> 
 <filter-mapping> 
  <filter-name>shiroFilter</filter-name> 
  <url-pattern>/admin/*</url-pattern> 
 </filter-mapping>

3: springmvc中对shiro配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
 xsi:schemaLocation="http://www.springframework.org/schema/beans  
  http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  http://www.springframework.org/schema/mvc  
  http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd  
  http://www.springframework.org/schema/context  
  http://www.springframework.org/schema/context/spring-context-3.2.xsd  
  http://www.springframework.org/schema/aop  
  http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
  http://www.springframework.org/schema/tx  
  http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> 
 <!-- web.xml中shiro的filter对应的bean --> 
 <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"
  <!-- 管理器,必须设置 --> 
  <property name="securityManager" ref="securityManager" /> 
  <!-- 拦截到,跳转到的地址,通过此地址去认证 --> 
  <property name="loginUrl" value="/admin/login.do" /> 
  <!-- 认证成功统一跳转到/admin/index.do,建议不配置,shiro认证成功自动到上一个请求路径 --> 
  <property name="successUrl" value="/admin/index.do" /> 
  <!-- 通过unauthorizedUrl指定没有权限操作时跳转页面 --> 
  <property name="unauthorizedUrl" value="/refuse.jsp" /> 
  <!-- 自定义filter,可用来更改默认的表单名称配置 --> 
  <property name="filters"
   <map> 
    <!-- 将自定义 的FormAuthenticationFilter注入shiroFilter中 --> 
    <entry key="authc" value-ref="formAuthenticationFilter" /> 
   </map> 
  </property> 
  <property name="filterChainDefinitions"
   <value> 
    <!-- 对静态资源设置匿名访问 --> 
    /images/** = anon 
    /js/** = anon 
    /styles/** = anon 
    <!-- 验证码,可匿名访问 --> 
    /validatecode.jsp = anon 
    <!-- 请求 logout.do地址,shiro去清除session --> 
    /admin/logout.do = logout 
    <!--商品查询需要商品查询权限 ,取消url拦截配置,使用注解授权方式 --> 
    <!-- /items/queryItems.action = perms[item:query] /items/editItems.action  
     = perms[item:edit] --> 
    <!-- 配置记住我或认证通过可以访问的地址 --> 
    /welcome.jsp = user 
    /admin/index.do = user 
    <!-- /** = authc 所有url都必须认证通过才可以访问 --> 
    /** = authc 
   </value> 
  </property> 
 </bean> 
 <!-- securityManager安全管理器 --> 
 <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"
  <property name="realm" ref="customRealm" /> 
  <!-- 注入缓存管理器 --> 
  <property name="cacheManager" ref="cacheManager" /> 
  <!-- 注入session管理器 --> 
  <!-- <property name="sessionManager" ref="sessionManager" /> --> 
  <!-- 记住我 --> 
  <property name="rememberMeManager" ref="rememberMeManager" /> 
 </bean> 
 <!-- 自定义realm --> 
 <bean id="customRealm" class="com.zhijianj.stucheck.shiro.CustomRealm"
  <!-- 将凭证匹配器设置到realm中,realm按照凭证匹配器的要求进行散列 --> 
  <!-- <property name="credentialsMatcher" ref="credentialsMatcher" /> --> 
 </bean> 
 <!-- 凭证匹配器 --> 
 <bean id="credentialsMatcher" 
  class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"
  <!-- 选用MD5散列算法 --> 
  <property name="hashAlgorithmName" value="md5" /> 
  <!-- 进行一次加密 --> 
  <property name="hashIterations" value="1" /> 
 </bean> 
 <!-- 自定义form认证过虑器 --> 
 <!-- 基于Form表单的身份验证过滤器,不配置将也会注册此过虑器,表单中的用户账号、密码及loginurl将采用默认值,建议配置 --> 
 <!-- 可通过此配置,判断验证码 --> 
 <bean id="formAuthenticationFilter" 
  class="com.zhijianj.stucheck.shiro.CustomFormAuthenticationFilter "
  <!-- 表单中账号的input名称,默认为username --> 
  <property name="usernameParam" value="username" /> 
  <!-- 表单中密码的input名称,默认为password --> 
  <property name="passwordParam" value="password" /> 
  <!-- 记住我input的名称,默认为rememberMe --> 
  <property name="rememberMeParam" value="rememberMe" /> 
 </bean> 
 <!-- 会话管理器 --> 
 <bean id="sessionManager" 
  class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"
  <!-- session的失效时长,单位毫秒 --> 
  <property name="globalSessionTimeout" value="600000" /> 
  <!-- 删除失效的session --> 
  <property name="deleteInvalidSessions" value="true" /> 
 </bean> 
 <!-- 缓存管理器 --> 
 <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"
  <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml" /> 
 </bean> 
 <!-- rememberMeManager管理器,写cookie,取出cookie生成用户信息 --> 
 <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager"
  <property name="cookie" ref="rememberMeCookie" /> 
 </bean> 
 <!-- 记住我cookie --> 
 <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie"
  <!-- rememberMe是cookie的名字 --> 
  <constructor-arg value="rememberMe" /> 
  <!-- 记住我cookie生效时间30天 --> 
  <property name="maxAge" value="2592000" /> 
 </bean> 
</beans>

4 :自定义Realm编码

 
public class CustomRealm extends AuthorizingRealm { 
 // 设置realm的名称 
 @Override 
 public void setName(String name) { 
  super.setName("customRealm"); 
 
 @Autowired 
 private AdminUserService adminUserService; 
 /** 
  * 认证 
  */ 
 @Override 
 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { 
  // token中包含用户输入的用户名和密码 
  // 第一步从token中取出用户名 
  String userName = (String) token.getPrincipal(); 
  // 第二步:根据用户输入的userCode从数据库查询 
  TAdminUser adminUser = adminUserService.getAdminUserByUserName(userName); 
  // 如果查询不到返回null 
  if (adminUser == null) {// 
   return null
  
  // 获取数据库中的密码 
  String password = adminUser.getPassword(); 
  /** 
   * 认证的用户,正确的密码 
   */ 
  AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(adminUser, password, this.getName()); 
    //MD5 加密+加盐+多次加密 
//<span style="color:#ff0000;">SimpleAuthenticationInfo authcInfo = new SimpleAuthenticationInfo(adminUser, password,ByteSource.Util.bytes(salt), this.getName());</span> 
  return authcInfo; 
 
 /** 
  * 授权,只有成功通过<span style="font-family: Arial, Helvetica, sans-serif;">doGetAuthenticationInfo方法的认证后才会执行。</span> 
  */ 
 @Override 
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 
  // 从 principals获取主身份信息 
  // 将getPrimaryPrincipal方法返回值转为真实身份类型(在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型), 
  TAdminUser activeUser = (TAdminUser) principals.getPrimaryPrincipal(); 
  // 根据身份信息获取权限信息 
  // 从数据库获取到权限数据 
  TAdminRole adminRoles = adminUserService.getAdminRoles(activeUser); 
  // 单独定一个集合对象 
  List<String> permissions = new ArrayList<String>(); 
  if (adminRoles != null) { 
   permissions.add(adminRoles.getRoleKey()); 
  
  // 查到权限数据,返回授权信息(要包括 上边的permissions) 
  SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); 
  // 将上边查询到授权信息填充到simpleAuthorizationInfo对象中 
  simpleAuthorizationInfo.addStringPermissions(permissions); 
  return simpleAuthorizationInfo; 
 
 // 清除缓存 
 public void clearCached() { 
  PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals(); 
  super.clearCache(principals); 
 
}

5 缓存配置

ehcache.xml代码如下:

1
2
3
4
5
6
7
8
9
10
11
<ehcache updateCheck="false" name="shiroCache"
 <defaultCache 
   maxElementsInMemory="10000" 
   eternal="false" 
   timeToIdleSeconds="120" 
   timeToLiveSeconds="120" 
   overflowToDisk="false" 
   diskPersistent="false" 
   diskExpiryThreadIntervalSeconds="120" 
   /> 
</ehcache>

通过使用ehache中就避免第次都向服务器发送权限授权(doGetAuthorizationInfo)的请求。

6.自定义表单编码过滤器

CustomFormAuthenticationFilter代码,认证之前调用,可用于验证码校验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter { 
 // 原FormAuthenticationFilter的认证方法 
 @Override 
 protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { 
  // 在这里进行验证码的校验 
   
  // 从session获取正确验证码 
  HttpServletRequest httpServletRequest = (HttpServletRequest) request; 
  HttpSession session = httpServletRequest.getSession(); 
  // 取出session的验证码(正确的验证码) 
  String validateCode = (String) session.getAttribute("validateCode");  
  // 取出页面的验证码 
  // 输入的验证和session中的验证进行对比 
  String randomcode = httpServletRequest.getParameter("randomcode"); 
  if (randomcode != null && validateCode != null && !randomcode.equals(validateCode)) { 
   // 如果校验失败,将验证码错误失败信息,通过shiroLoginFailure设置到request中 
   httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError"); 
   // 拒绝访问,不再校验账号和密码 
   return true
  
  return super.onAccessDenied(request, response); 
 
}

在此符上验证码jsp界面的代码  validatecode.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<%@ page language="java" contentType="text/html; charset=UTF-8" 
 pageEncoding="UTF-8"%> 
<%@ page import="java.util.Random"%> 
<%@ page import="java.io.OutputStream"%> 
<%@ page import="java.awt.Color"%> 
<%@ page import="java.awt.Font"%> 
<%@ page import="java.awt.Graphics"%> 
<%@ page import="java.awt.image.BufferedImage"%> 
<%@ page import="javax.imageio.ImageIO"%> 
<% 
 int width = 60
 int height = 32
 //create the image 
 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
 Graphics g = image.getGraphics(); 
 // set the background color 
 g.setColor(new Color(0xDCDCDC)); 
 g.fillRect(0, 0, width, height); 
 // draw the border 
 g.setColor(Color.black); 
 g.drawRect(0, 0, width - 1, height - 1); 
 // create a random instance to generate the codes 
 Random rdm = new Random(); 
 String hash1 = Integer.toHexString(rdm.nextInt()); 
 // make some confusion 
 for (int i = 0; i < 50; i++) { 
  int x = rdm.nextInt(width); 
  int y = rdm.nextInt(height); 
  g.drawOval(x, y, 0, 0); 
 
 // generate a random code 
 String capstr = hash1.substring(0, 4); 
 //将生成的验证码存入session 
 session.setAttribute("validateCode", capstr); 
 g.setColor(new Color(0, 100, 0)); 
 g.setFont(new Font("Candara", Font.BOLD, 24)); 
 g.drawString(capstr, 8, 24); 
 g.dispose(); 
 //输出图片 
 response.setContentType("image/jpeg"); 
 out.clear(); 
 out = pageContext.pushBody(); 
 OutputStream strm = response.getOutputStream(); 
 ImageIO.write(image, "jpeg", strm); 
 strm.close(); 
%>

7.登录控制器方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/** 
 * 到登录界面 
 
 * @return 
 * @throws Exception 
 */ 
@RequestMapping("login.do"
public String adminPage(HttpServletRequest request) throws Exception { 
 // 如果登陆失败从request中获取认证异常信息,shiroLoginFailure就是shiro异常类的全限定名 
 String exceptionClassName = (String) request.getAttribute("shiroLoginFailure"); 
 // 根据shiro返回的异常类路径判断,抛出指定异常信息 
 if (exceptionClassName != null) { 
  if (UnknownAccountException.class.getName().equals(exceptionClassName)) { 
   // 最终会抛给异常处理器 
   throw new CustomJsonException("账号不存在"); 
  } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) { 
   throw new CustomJsonException("用户名/密码错误"); 
  } else if ("randomCodeError".equals(exceptionClassName)) { 
   throw new CustomJsonException("验证码错误 "); 
  } else
   throw new Exception();// 最终在异常处理器生成未知错误 
  
 
 // 此方法不处理登陆成功(认证成功),shiro认证成功会自动跳转到上一个请求路径 
 // 登陆失败还到login页面 
 return "admin/login"
}

8.用户回显Controller

当用户登录认证成功后,CustomRealm在调用完doGetAuthenticationInfo时,通过

1
2
AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(adminUser, password, this.getName()); 
 return authcInfo;

SimpleAuthenticationInfo构造参数的第一个参数传入一个用户的对象,之后,可通过Subject subject = SecurityUtils.getSubject();中的subject.getPrincipal()获取到此对象。所以需要回显用户信息时,我这样调用的

1
2
3
4
5
6
7
8
9
10
@RequestMapping("index.do"
public String index(Model model) { 
 //从shiro的session中取activeUser 
 Subject subject = SecurityUtils.getSubject(); 
 //取身份信息 
 TAdminUser adminUser = (TAdminUser) subject.getPrincipal(); 
 //通过model传到页面 
 model.addAttribute("adminUser", adminUser); 
 return "admin/index"
}

9.在jsp页面中控制权限

先引入shiro的头文件

1
2
<!-- shiro头引入 --> 
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro"%>

采用shiro标签对权限进行处理

1
2
3
4
5
<!-- 有curd权限才显示修改链接,没有该 权限不显示,相当 于if(hasPermission(curd)) --> 
    <shiro:hasPermission name="curd"
     <BR /> 
     我拥有超级的增删改查权限额 
    </shiro:hasPermission>

10.在Controller控制权限

通过@RequiresPermissions注解,指定执行此controller中某个请求方法需要的权限

1
2
3
@RequestMapping("/queryInfo.do"
 @RequiresPermissions("q")//执行需要"q"权限 
 public ModelAndView queryItems(HttpServletRequest request) throws Exception { }

11.MD5加密加盐处理

这里以修改密码为例,通过获取新的密码(明文)后通过MD5加密+加盐+3次加密为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RequestMapping("updatePassword.do"
 @ResponseBody 
 public String updateAdminUserPassword(String newPassword) { 
  // 从shiro的session中取activeUser 
  Subject subject = SecurityUtils.getSubject(); 
  // 取身份信息 
  TAdminUser adminUser = (TAdminUser) subject.getPrincipal(); 
  // 生成salt,随机生成 
  SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator(); 
  String salt = secureRandomNumberGenerator.nextBytes().toHex(); 
  Md5Hash md5 = new Md5Hash(newPassword, salt, 3); 
  String newMd5Password = md5.toHex(); 
  // 设置新密码 
  adminUser.setPassword(newMd5Password); 
  // 设置盐 
  adminUser.setSalt(salt); 
  adminUserService.updateAdminUserPassword(adminUser); 
  return newPassword; 
 }

相关文章:

  • 2021-11-04
  • 2022-12-23
  • 2021-04-24
  • 2022-01-16
  • 2021-07-13
  • 2021-10-05
  • 2022-03-07
  • 2022-02-14
猜你喜欢
  • 2021-08-16
  • 2022-01-07
  • 2022-03-07
  • 2021-11-27
  • 2021-07-09
相关资源
相似解决方案