shiro学习——beetl整合shiro


声明:本文转载自https://my.oschina.net/u/3534905/blog/1785866,转载目的在于传递更多信息,仅供学习交流之用。如有侵权行为,请联系我,我会及时删除。

直接进入正文:

首先是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>

实现我们自己的realm

/**  * @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.xml

<?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的配置如下:

<!-- 因为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表示需要相应的角色才能访问的路径,然后是登录controller

@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的权限标签需要新增一个拓展类

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的作者写的,出了问题就找他吧。但是注释是我自己写的,万一写错了,还是找他吧。

为了能在页面使用还要写一个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必须是应用的用户,才能访问或调用被该注解标注的类,实例,方法。

完毕

本文发表于2018年03月27日 22:38
(c)注:本文转载自https://my.oschina.net/u/3534905/blog/1785866,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如有侵权行为,请联系我们,我们会及时删除.

阅读 1930 讨论 0 喜欢 0

抢先体验

扫码体验
趣味小程序
文字表情生成器

闪念胶囊

你要过得好哇,这样我才能恨你啊,你要是过得不好,我都不知道该恨你还是拥抱你啊。

直抵黄龙府,与诸君痛饮尔。

那时陪伴我的人啊,你们如今在何方。

不出意外的话,我们再也不会见了,祝你前程似锦。

这世界真好,吃野东西也要留出这条命来看看

快捷链接
网站地图
提交友链
Copyright © 2016 - 2021 Cion.
All Rights Reserved.
京ICP备2021004668号-1