Shiro 是Shiro 是一個 Apache 下的一開源項目項目,旨在簡化身份驗證和授權。
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
|
<beans xmlns= "http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc= "http://www.springframework.org/schema/mvc" xmlns:context= "http://www.springframework.org/schema/context" xmlns:aop= "http://www.springframework.org/schema/aop" xmlns:tx= "http://www.springframework.org/schema/tx" 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編碼
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
|
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; } |
總結
以上所述是小編給大家介紹的springmvc+shiro+maven 實現登錄認證與權限授權管理,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/fanfanzk1314/article/details/77929787