springmvc+shiro+maven 實(shí)現(xiàn)登錄認(rèn)證與權(quán)限授權(quán)管理
Shiro 是Shiro 是一個(gè) Apache 下的一開源項(xiàng)目項(xiàng)目,旨在簡(jiǎn)化身份驗(yàn)證和授權(quán)。
1:shiro的配置,通過maven加入shiro相關(guān)jar包
<!-- 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過濾器
<!-- 配置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中對(duì)shiro配置
<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對(duì)應(yīng)的bean --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- 管理器,必須設(shè)置 --> <property name="securityManager" ref="securityManager" /> <!-- 攔截到,跳轉(zhuǎn)到的地址,通過此地址去認(rèn)證 --> <property name="loginUrl" value="/admin/login.do" /> <!-- 認(rèn)證成功統(tǒng)一跳轉(zhuǎn)到/admin/index.do,建議不配置,shiro認(rèn)證成功自動(dòng)到上一個(gè)請(qǐng)求路徑 --> <property name="successUrl" value="/admin/index.do" /> <!-- 通過unauthorizedUrl指定沒有權(quán)限操作時(shí)跳轉(zhuǎn)頁面 --> <property name="unauthorizedUrl" value="/refuse.jsp" /> <!-- 自定義filter,可用來更改默認(rèn)的表單名稱配置 --> <property name="filters"> <map> <!-- 將自定義 的FormAuthenticationFilter注入shiroFilter中 --> <entry key="authc" value-ref="formAuthenticationFilter" /> </map> </property> <property name="filterChainDefinitions"> <value> <!-- 對(duì)靜態(tài)資源設(shè)置匿名訪問 --> /images/** = anon /js/** = anon /styles/** = anon <!-- 驗(yàn)證碼,可匿名訪問 --> /validatecode.jsp = anon <!-- 請(qǐng)求 logout.do地址,shiro去清除session --> /admin/logout.do = logout <!--商品查詢需要商品查詢權(quán)限 ,取消url攔截配置,使用注解授權(quán)方式 --> <!-- /items/queryItems.action = perms[item:query] /items/editItems.action = perms[item:edit] --> <!-- 配置記住我或認(rèn)證通過可以訪問的地址 --> /welcome.jsp = user /admin/index.do = user <!-- /** = authc 所有url都必須認(rèn)證通過才可以訪問 --> /** = 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"> <!-- 將憑證匹配器設(shè)置到realm中,realm按照憑證匹配器的要求進(jìn)行散列 --> <!-- <property name="credentialsMatcher" ref="credentialsMatcher" /> --> </bean> <!-- 憑證匹配器 --> <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <!-- 選用MD5散列算法 --> <property name="hashAlgorithmName" value="md5" /> <!-- 進(jìn)行一次加密 --> <property name="hashIterations" value="1" /> </bean> <!-- 自定義form認(rèn)證過慮器 --> <!-- 基于Form表單的身份驗(yàn)證過濾器,不配置將也會(huì)注冊(cè)此過慮器,表單中的用戶賬號(hào)、密碼及l(fā)oginurl將采用默認(rèn)值,建議配置 --> <!-- 可通過此配置,判斷驗(yàn)證碼 --> <bean id="formAuthenticationFilter" class="com.zhijianj.stucheck.shiro.CustomFormAuthenticationFilter "> <!-- 表單中賬號(hào)的input名稱,默認(rèn)為username --> <property name="usernameParam" value="username" /> <!-- 表單中密碼的input名稱,默認(rèn)為password --> <property name="passwordParam" value="password" /> <!-- 記住我input的名稱,默認(rèn)為rememberMe --> <property name="rememberMeParam" value="rememberMe" /> </bean> <!-- 會(huì)話管理器 --> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <!-- session的失效時(shí)長(zhǎng),單位毫秒 --> <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生效時(shí)間30天 --> <property name="maxAge" value="2592000" /> </bean> </beans>
4 :自定義Realm編碼
public class CustomRealm extends AuthorizingRealm { // 設(shè)置realm的名稱 @Override public void setName(String name) { super.setName("customRealm"); } @Autowired private AdminUserService adminUserService; /** * 認(rèn)證 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // token中包含用戶輸入的用戶名和密碼 // 第一步從token中取出用戶名 String userName = (String) token.getPrincipal(); // 第二步:根據(jù)用戶輸入的userCode從數(shù)據(jù)庫查詢 TAdminUser adminUser = adminUserService.getAdminUserByUserName(userName); // 如果查詢不到返回null if (adminUser == null) {// return null; } // 獲取數(shù)據(jù)庫中的密碼 String password = adminUser.getPassword(); /** * 認(rèn)證的用戶,正確的密碼 */ 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; } /** * 授權(quán),只有成功通過<span style="font-family: Arial, Helvetica, sans-serif;">doGetAuthenticationInfo方法的認(rèn)證后才會(huì)執(zhí)行。</span> */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 從 principals獲取主身份信息 // 將getPrimaryPrincipal方法返回值轉(zhuǎn)為真實(shí)身份類型(在上邊的doGetAuthenticationInfo認(rèn)證通過填充到SimpleAuthenticationInfo中身份類型), TAdminUser activeUser = (TAdminUser) principals.getPrimaryPrincipal(); // 根據(jù)身份信息獲取權(quán)限信息 // 從數(shù)據(jù)庫獲取到權(quán)限數(shù)據(jù) TAdminRole adminRoles = adminUserService.getAdminRoles(activeUser); // 單獨(dú)定一個(gè)集合對(duì)象 List<String> permissions = new ArrayList<String>(); if (adminRoles != null) { permissions.add(adminRoles.getRoleKey()); } // 查到權(quán)限數(shù)據(jù),返回授權(quán)信息(要包括 上邊的permissions) SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); // 將上邊查詢到授權(quán)信息填充到simpleAuthorizationInfo對(duì)象中 simpleAuthorizationInfo.addStringPermissions(permissions); return simpleAuthorizationInfo; } // 清除緩存 public void clearCached() { PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals(); super.clearCache(principals); } }
5 緩存配置
ehcache.xml代碼如下:
<ehcache updateCheck="false" name="shiroCache"> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> </ehcache>
通過使用ehache中就避免第次都向服務(wù)器發(fā)送權(quán)限授權(quán)(doGetAuthorizationInfo)的請(qǐng)求。
6.自定義表單編碼過濾器
CustomFormAuthenticationFilter代碼,認(rèn)證之前調(diào)用,可用于驗(yàn)證碼校驗(yàn)
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter { // 原FormAuthenticationFilter的認(rèn)證方法 @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { // 在這里進(jìn)行驗(yàn)證碼的校驗(yàn) // 從session獲取正確驗(yàn)證碼 HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpSession session = httpServletRequest.getSession(); // 取出session的驗(yàn)證碼(正確的驗(yàn)證碼) String validateCode = (String) session.getAttribute("validateCode"); // 取出頁面的驗(yàn)證碼 // 輸入的驗(yàn)證和session中的驗(yàn)證進(jìn)行對(duì)比 String randomcode = httpServletRequest.getParameter("randomcode"); if (randomcode != null && validateCode != null && !randomcode.equals(validateCode)) { // 如果校驗(yàn)失敗,將驗(yàn)證碼錯(cuò)誤失敗信息,通過shiroLoginFailure設(shè)置到request中 httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError"); // 拒絕訪問,不再校驗(yàn)賬號(hào)和密碼 return true; } return super.onAccessDenied(request, response); } }
在此符上驗(yàn)證碼jsp界面的代碼 validatecode.jsp
<%@ 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); //將生成的驗(yàn)證碼存入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.登錄控制器方法
/** * 到登錄界面 * * @return * @throws Exception */ @RequestMapping("login.do") public String adminPage(HttpServletRequest request) throws Exception { // 如果登陸失敗從request中獲取認(rèn)證異常信息,shiroLoginFailure就是shiro異常類的全限定名 String exceptionClassName = (String) request.getAttribute("shiroLoginFailure"); // 根據(jù)shiro返回的異常類路徑判斷,拋出指定異常信息 if (exceptionClassName != null) { if (UnknownAccountException.class.getName().equals(exceptionClassName)) { // 最終會(huì)拋給異常處理器 throw new CustomJsonException("賬號(hào)不存在"); } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) { throw new CustomJsonException("用戶名/密碼錯(cuò)誤"); } else if ("randomCodeError".equals(exceptionClassName)) { throw new CustomJsonException("驗(yàn)證碼錯(cuò)誤 "); } else { throw new Exception();// 最終在異常處理器生成未知錯(cuò)誤 } } // 此方法不處理登陸成功(認(rèn)證成功),shiro認(rèn)證成功會(huì)自動(dòng)跳轉(zhuǎn)到上一個(gè)請(qǐng)求路徑 // 登陸失敗還到login頁面 return "admin/login"; }
8.用戶回顯Controller
當(dāng)用戶登錄認(rèn)證成功后,CustomRealm在調(diào)用完doGetAuthenticationInfo時(shí),通過
AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(adminUser, password, this.getName()); return authcInfo;
SimpleAuthenticationInfo構(gòu)造參數(shù)的第一個(gè)參數(shù)傳入一個(gè)用戶的對(duì)象,之后,可通過Subject subject = SecurityUtils.getSubject();中的subject.getPrincipal()獲取到此對(duì)象。所以需要回顯用戶信息時(shí),我這樣調(diào)用的
@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頁面中控制權(quán)限
先引入shiro的頭文件
<!-- shiro頭引入 --> <%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro"%>
采用shiro標(biāo)簽對(duì)權(quán)限進(jìn)行處理
<!-- 有curd權(quán)限才顯示修改鏈接,沒有該 權(quán)限不顯示,相當(dāng) 于if(hasPermission(curd)) --> <shiro:hasPermission name="curd"> <BR /> 我擁有超級(jí)的增刪改查權(quán)限額 </shiro:hasPermission>
10.在Controller控制權(quán)限
通過@RequiresPermissions注解,指定執(zhí)行此controller中某個(gè)請(qǐng)求方法需要的權(quán)限
@RequestMapping("/queryInfo.do") @RequiresPermissions("q")//執(zhí)行需要"q"權(quán)限 public ModelAndView queryItems(HttpServletRequest request) throws Exception { }
11.MD5加密加鹽處理
這里以修改密碼為例,通過獲取新的密碼(明文)后通過MD5加密+加鹽+3次加密為例
@RequestMapping("updatePassword.do") @ResponseBody public String updateAdminUserPassword(String newPassword) { // 從shiro的session中取activeUser Subject subject = SecurityUtils.getSubject(); // 取身份信息 TAdminUser adminUser = (TAdminUser) subject.getPrincipal(); // 生成salt,隨機(jī)生成 SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator(); String salt = secureRandomNumberGenerator.nextBytes().toHex(); Md5Hash md5 = new Md5Hash(newPassword, salt, 3); String newMd5Password = md5.toHex(); // 設(shè)置新密碼 adminUser.setPassword(newMd5Password); // 設(shè)置鹽 adminUser.setSalt(salt); adminUserService.updateAdminUserPassword(adminUser); return newPassword; }
總結(jié)
以上所述是小編給大家介紹的springmvc+shiro+maven 實(shí)現(xiàn)登錄認(rèn)證與權(quán)限授權(quán)管理,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- SpringMVC實(shí)現(xiàn)文件上傳下載功能
- SpringMVC實(shí)現(xiàn)文件上傳與下載
- springmvc實(shí)現(xiàn)文件上傳功能
- SpringMVC 通過commons-fileupload實(shí)現(xiàn)文件上傳功能
- IDEA實(shí)現(xiàn) springmvc的簡(jiǎn)單注冊(cè)登錄功能的示例代碼
- Spring+SpringMVC+JDBC實(shí)現(xiàn)登錄的示例(附源碼)
- Spring mvc 實(shí)現(xiàn)用戶登錄的方法(攔截器)
- Spring MVC實(shí)現(xiàn)文件上傳及優(yōu)化案例解析
相關(guān)文章
Spring中的ApplicationRunner接口的使用詳解
這篇文章主要介紹了Spring中的ApplicationRunner接口的使用詳解,ApplicationRunner使用起來很簡(jiǎn)單,只需要實(shí)現(xiàn)CommandLineRunner或者ApplicationRunner接口,重寫run方法就行,需要的朋友可以參考下2023-11-11基于spring@aspect注解的aop實(shí)現(xiàn)過程代碼實(shí)例
這篇文章主要介紹了基于spring@aspect注解的aop實(shí)現(xiàn)過程代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03一文教你掌握J(rèn)ava如何實(shí)現(xiàn)判空
實(shí)際項(xiàng)目中我們會(huì)有很多地方需要判空校驗(yàn),如果不做判空校驗(yàn)則可能產(chǎn)生NullPointerException異常。所以本文小編為大家整理了Java中幾個(gè)常見的判空方法,希望對(duì)大家有所幫助2023-04-04spring security登錄成功后通過Principal獲取名返回空問題
這篇文章主要介紹了spring security登錄成功后通過Principal獲取名返回空問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03Java數(shù)據(jù)結(jié)構(gòu)BFS廣搜法解決迷宮問題
廣搜BFS的基本思想是: 首先訪問初始點(diǎn)v并將其標(biāo)志為已經(jīng)訪問。接著通過鄰接關(guān)系將鄰接點(diǎn)入隊(duì)。然后每訪問過一個(gè)頂點(diǎn)則出隊(duì)。按照順序,訪問每一個(gè)頂點(diǎn)的所有未被訪問過的頂點(diǎn)直到所有的頂點(diǎn)均被訪問過。廣度優(yōu)先遍歷類似與層次遍歷2022-04-04