直接進入正文:html
首先是pom文件須要加入這幾個包前端
<!-- 添加shiro相關包 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.3</version> </dependency> <!-- 添加shiro web支持 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.2.3</version> </dependency> <!-- 添加shiro spring支持 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.3</version> </dependency>
實現咱們本身的realmjava
/** * @author panmingshuai * @description * @Time 2018年3月17日 下午5:05:27 * */ public class MyShiroRealm extends AuthorizingRealm { @Autowired private UserService userService; @Override /** * 獲取受權信息,登陸成功後在訪問地址變化時調用 */ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { String userName = (String) principalCollection.fromRealm(getName()).iterator().next(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); if(StringUtils.isNotBlank(userName)){ info.addRoles(userService.getRolesByName(userName));//添加相應角色 info.addStringPermissions(userService.getPermissByName(userName));//添加相應權限 return info; } return null; } @Override /** * 登陸驗證,會先進/login的controller方法驗證登陸,而後在subject.login(token)時進入這個方法判斷。 */ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; // 經過表單接收的用戶名 String userName = token.getUsername(); if(StringUtils.isNotBlank(userName)){ return new SimpleAuthenticationInfo(userName, userService.getUserByName(userName).getPwd(), getName());//這裏的getName方法指的是get如今這個realm類的名字 } return null; } }
接下來是配置文件,web.xmlweb
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!-- 啓動Spring大容器,將Spring容器內的內容歸入到WEB容器中 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-context.xml</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <listener> <description>日誌監聽</description> <display-name>log4jConfigLocation</display-name> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <listener> <description>spring監聽器</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/</url-pattern> </filter-mapping> <!-- 配置前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!-- 在DispatcherServlet中/表明全部,其餘地方都是/* --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 添加shiro過濾器 --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <!-- 該值缺省爲false,表示聲明週期由SpringApplicationContext管理,設置爲true表示ServletContainer管理 --> <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> </web-app>
接下來是:spring-context.xml中有關shiro的配置以下:spring
<!-- 由於shiro的相關登陸信息是存在緩存裏的全部必須配置ehcache --> <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:ehcache.xml" /> </bean> <!-- shiro配置 --> <!-- 自定義Realm --> <bean id="myRealm" class="org.pan.shiro.shiro.MyShiroRealm" /> <!-- 安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm" /> <property name="cacheManager" ref="cacheManager" /> </bean> <aop:config proxy-target-class="true"></aop:config> <!-- Shiro過濾器 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- Shiro的核心安全接口,這個屬性是必須的 --> <property name="securityManager" ref="securityManager" /> <!-- 若是在下面的權限鏈中沒有相應的權限,則跳轉到指定頁面這裏指定的頁面 --> <property name="unauthorizedUrl" value="/user/unauthorized" /> <!-- Shiro鏈接約束配置,即過濾鏈的定義 --> <property name="filterChainDefinitions"> <value> <!-- 表示均可以訪問 --> /user/login*/**=anon <!-- 只有擁有admin角色的用戶纔可訪問,同時須要擁有多個角色的話,用引號引發來,中間用逗號隔開,單個不需引號,可是這是且條件,即要知足這兩個角色才能訪問這個地址 --> /user/student*/**=roles[teacher] <!-- perms表示須要該權限才能訪問的頁面 --> /user/teacher*/**=perms[admin] <!-- authc表示須要認證才能訪問的頁面 --> /**=authc </value> </property> </bean>
上面的roles表示須要相應的角色才能訪問的路徑,而後是登陸controllerapache
@Controller @RequestMapping("user") public class ShiroController { @RequestMapping("/login") public ModelAndView login(String userName, String pwd){ ModelAndView mav = new ModelAndView(); // 這裏須要加上判斷帳號,密碼是否正確的方法 if(StringUtils.isBlank(userName)){ return new ModelAndView("/html/login.html"); } SecurityUtils.getSecurityManager().logout(SecurityUtils.getSubject());//若是原來有的話,就退出 //登陸後存放進shiro token UsernamePasswordToken token=new UsernamePasswordToken(userName, pwd); Subject subject=SecurityUtils.getSubject(); subject.login(token); //若是密碼帳號正確會執行下面的代碼,不然會報錯 mav.setViewName("/html/success.html"); return mav; } @RequestMapping(value = "/teacher") public ModelAndView teacher(){ return new ModelAndView("/html/teacher.html"); } @RequestMapping(value = "/student") public ModelAndView student(){ return new ModelAndView("/html/student.html"); } }
如今能夠運行項目,能夠看到沒有amdin權限的用戶訪問/user/teacher/*這個路徑會調到/user/unauthorized這個路徑去。緩存
接下來是頁面上的問題,安全
上面的作法雖然能從訪問上阻止用戶的訪問,可是頁面上相應的訪問標籤仍是存在的怎麼讓這個標籤在沒有相應權限的人登陸系統以後看不到呢。這就涉及到標籤了,雖然jsp也有相應的標籤,可是我一直在使用layui,因此一直寫的是layui,而後使用了beetl做爲靜態模板,因此這裏介紹beetl的作法,可是jsp和這個如出一轍的,由於beetl是參考jsp作法來弄得。要想使用beetl的權限標籤須要新增一個拓展類session
public class ShiroExt { /** * 驗證當前用戶是否爲「訪客」,即未認證(包含未記住)的用戶。 * * @return */ public boolean isGuest() { return getSubject() == null || getSubject().getPrincipal() == null; } /** * 認證經過或已記住的用戶。 * * @return */ public boolean isUser() { return getSubject() != null && getSubject().getPrincipal() != null; } /** * 已認證經過的用戶。不包含已記住的用戶,這是與user標籤的區別所在。 * * @return */ public boolean isAuthenticated() { return getSubject() != null && getSubject().isAuthenticated(); } /** * 未認證經過用戶,與authenticated標籤相對應。與guest標籤的區別是,該標籤包含已記住用戶。 * @return */ public boolean isNotAuthenticated() { return !isAuthenticated(); } /** * 輸出當前用戶信息,一般爲登陸賬號信息 * * @param map * @return */ public String principal(Map map) { String strValue = null; if (getSubject() != null) { // Get the principal to print out Object principal; String type = map != null ? (String) map.get("type") : null; if (type == null) { principal = getSubject().getPrincipal(); } else { principal = getPrincipalFromClassName(type); } String property = map != null ? (String) map.get("property") : null; // Get the string value of the principal if (principal != null) { if (property == null) { strValue = principal.toString(); } else { strValue = getPrincipalProperty(principal, property); } } } if (strValue != null) { return strValue; } else { return null; } } /** * 驗證當前用戶是否屬於該角色。 * * @param roleName * @return */ public boolean hasRole(String roleName) { return getSubject() != null && getSubject().hasRole(roleName); } /** * 與hasRole標籤邏輯相反,當用戶不屬於該角色時驗證經過。 * * @param roleName * @return */ public boolean lacksRole(String roleName) { boolean hasRole = getSubject() != null && getSubject().hasRole(roleName); return !hasRole; } /** * 驗證當前用戶是否屬於如下任意一個角色。 以逗號分隔 * * @param roleNames * @return */ public boolean hasAnyRole(String roleNames) { boolean hasAnyRole = false; Subject subject = getSubject(); if (subject != null) { // Iterate through roles and check to see if the user has one of the // roles for (String role : roleNames.split(",")) { if (subject.hasRole(role.trim())) { hasAnyRole = true; break; } } } return hasAnyRole; } /** * 驗證當前用戶是否擁有指定權限。 * * @param p * @return */ public boolean hasPermission(String p) { return getSubject() != null && getSubject().isPermitted(p); } /** * 與hasPermission標籤邏輯相反,當前用戶沒有制定權限時,驗證經過。 * * @param p * @return */ public boolean lacksPermission(String p) { return !hasPermission(p); } @SuppressWarnings({ "unchecked" }) private Object getPrincipalFromClassName(String type) { Object principal = null; try { Class cls = Class.forName(type); principal = getSubject().getPrincipals().oneByType(cls); } catch (ClassNotFoundException e) { } return principal; } private String getPrincipalProperty(Object principal, String property) { String strValue = null; try { BeanInfo bi = Introspector.getBeanInfo(principal.getClass()); // Loop through the properties to get the string value of the // specified property boolean foundProperty = false; for (PropertyDescriptor pd : bi.getPropertyDescriptors()) { if (pd.getName().equals(property)) { Object value = pd.getReadMethod().invoke(principal, (Object[]) null); strValue = String.valueOf(value); foundProperty = true; break; } } if (!foundProperty) { final String message = "Property [" + property + "] not found in principal of type [" + principal.getClass().getName() + "]"; throw new RuntimeException(message); } } catch (Exception e) { final String message = "Error reading property [" + property + "] from principal of type [" + principal.getClass().getName() + "]"; throw new RuntimeException(message, e); } return strValue; } protected Subject getSubject() { return SecurityUtils.getSubject(); } }
該類是beetl的做者寫的,出了問題就找他吧。可是註釋是我本身寫的,萬一寫錯了,仍是找他吧。mvc
爲了能在頁面使用還要寫一個beetlconfig類
/** *@description *@auth panmingshuai *@time 2018年3月18日上午1:03:41 *配置權限解析標籤的方法 * */ public class BeetlConfiguration extends BeetlGroupUtilConfiguration { @Override protected void initOther() { groupTemplate.registerFunctionPackage("panshiro", new ShiroExt()); } }
記住這裏的panshiro一會有用,這裏的shiroExt類就是上面的那個類。
最後添加beetl的視圖解析器
<!-- 配置一個試圖解析器ViewResolver(應用控制器) --> <bean name="beetlConfig" class="org.pan.shiro.shiro.BeetlConfiguration" init-method="init"> <property name="configFileResource" value="classpath:beetl.properties" /> </bean> <!-- Beetl視圖解析器1 --> <bean name="beetlViewResolver" class="org.beetl.ext.spring.BeetlSpringViewResolver"> <property name="suffix" value="" /> <property name="contentType" value="text/html;charset=UTF-8" /> <property name="order" value="0" /> <!-- 多GroupTemplate,須要指定使用的bean --> <property name="config" ref="beetlConfig" /> </bean>
這裏面的那個org.pan.shiro.shiro.BeetlConfiguration類就是上面寫的那個beetlconfig類。
怎麼使用呢,看這段代碼
<% if(panshiro.hasPermission("admin")){%><a href="${ctxPath}/user/admin">退出</a><%}%>
這裏的panshiro就是咱們剛纔配的那個panshiro,你那裏寫成啥,這裏就寫啥。這段代碼的意思就是若是登陸人擁有admin權限,裏面的a標籤纔會顯示出來。至於這裏的hasPermisson方法就是shiroExt中的方法,能夠換成其中的方法。意義就和裏面的註解同樣
好了,這樣頁面上也不會讓沒有相應權限的人看到相關的東西了。
但仍是有個問題,隨着功能的不斷完善,可能你須要控制的權限愈來愈多,有的甚至精確到了按鈕,然而咱們仍是在上面的配置文件中配置麼。那太麻煩了,並且配置文件會變得很大,也不利於開發。如今就須要開啓shiro的註解功能了。在spring-servlet.xml中,注意不是spring-context.xml中!添加下面有關於shiro的配置
<!--========================-若是使用註解方式驗證將下面代碼放開,記住由於是訪問controller方法所以這段配置要放在視圖控制器的配置文件中=============================== --> <!-- 保證明現了Shiro內部lifecycle函數的bean執行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"> <property name="proxyTargetClass" value="true" /> </bean> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager" /> </bean> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!--若是沒有註解指定的權限,則調到下面指定的頁面--> <prop key="org.apache.shiro.authz.UnauthorizedException"> redirect:/user/login </prop> </props> </property> </bean>
這樣就能夠在controller中的方法使用shiro的相關注解。權限的註解一共有五個:
@RequiresAuthentication:使用該註解標註的類,實例,方法在訪問或調用時,當前Subject必須在當前session中已通過認證。
@RequiresGuest:使用該註解標註的類,實例,方法在訪問或調用時,當前Subject能夠是「gust」身份,不須要通過認證或者在原先的session中存在記錄。
@RequiresPermissions:當前Subject須要擁有某些特定的權限時,才能執行被該註解標註的方法。若是當前Subject不具備這樣的權限,則方法不會被執行。
@RequiresRoles:當前Subject必須擁有全部指定的角色時,才能訪問被該註解標註的方法。若是當天Subject不一樣時擁有全部指定角色,則方法不會執行還會拋出AuthorizationException異常。
@RequiresUser:當前Subject必須是應用的用戶,才能訪問或調用被該註解標註的類,實例,方法。
完畢