zoukankan      html  css  js  c++  java
  • shrio

    最近做的项目需要加上权限控制, 最后选型用的是shiro,这个是用确实比较简单。配置文件说明

    web.xml

    Xml代码  收藏代码
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    3.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
    4.     version="2.5">  
    5.     <display-name>pscms</display-name>  
    6.       
    7.     <!-- Spring ApplicationContext配置文件的路径,可使用通配符,多个路径用,号分隔  
    8.         此参数用于后面的Spring Context Loader -->  
    9.     <context-param>  
    10.         <param-name>contextConfigLocation</param-name>  
    11.         <param-value>  
    12.             classpath*:/applicationContext*.xml  
    13.         </param-value>  
    14.     </context-param>  
    15.       
    16.     <!-- 設定Spring Context的默认Profile -->  
    17.     <context-param>  
    18.         <param-name>spring.profiles.default</param-name>  
    19.         <param-value>production</param-value>  
    20.     </context-param>  
    21.       
    22.     <!--Spring的ApplicationContext 载入 -->  
    23.     <listener>  
    24.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    25.     </listener>  
    26.   
    27.     <!-- Filter 定义  -->  
    28.     <!-- Character Encoding filter -->  
    29.     <filter>  
    30.         <filter-name>encodingFilter</filter-name>  
    31.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
    32.         <init-param>  
    33.             <param-name>encoding</param-name>  
    34.             <param-value>UTF-8</param-value>  
    35.         </init-param>  
    36.         <init-param>  
    37.             <param-name>forceEncoding</param-name>  
    38.             <param-value>true</param-value>  
    39.         </init-param>  
    40.     </filter>  
    41.     <filter-mapping>  
    42.         <filter-name>encodingFilter</filter-name>  
    43.         <url-pattern>/*</url-pattern>  
    44.     </filter-mapping>  
    45.       
    46.     <!-- Shiro Security filter-->  
    47. <span style="background-color: #ffffff; color: #ff0000;">   <filter>  
    48.         <filter-name>shiroFilter</filter-name>  
    49.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
    50.             <init-param>  
    51.                 <param-name>targetFilterLifecycle</param-name>  
    52.                 <param-value>true</param-value>  
    53.             </init-param>  
    54.     </filter></span>  
    55.     <filter-mapping>  
    56.         <filter-name>shiroFilter</filter-name>  
    57.         <url-pattern>/*</url-pattern>  
    58.     </filter-mapping>   
    59.   
    60.     <!-- SiteMesh Web-Page Layout filter-->  
    61.     <filter>  
    62.         <filter-name>sitemeshFilter</filter-name>  
    63.         <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>  
    64.     </filter>  
    65.     <filter-mapping>  
    66.         <filter-name>sitemeshFilter</filter-name>  
    67.         <url-pattern>/*</url-pattern>  
    68.     </filter-mapping>  
    69.     
    70.     <!-- Spring MVC Servlet -->  
    71.     <servlet>  
    72.         <servlet-name>springServlet</servlet-name>  
    73.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    74.         <init-param>  
    75.             <param-name>contextConfigLocation</param-name>  
    76.             <param-value>/WEB-INF/spring-mvc.xml</param-value>  
    77.         </init-param>  
    78.         <load-on-startup>1</load-on-startup>  
    79.     </servlet>  
    80.     <servlet-mapping>  
    81.         <servlet-name>springServlet</servlet-name>  
    82.         <url-pattern>/</url-pattern>  
    83.     </servlet-mapping>  
    84.       
    85.     <servlet>  
    86.         <servlet-name>captcha</servlet-name>  
    87.         <servlet-class>com.surfilter.pscms.web.CaptchaController</servlet-class>  
    88.     </servlet>  
    89.     <servlet-mapping>  
    90.         <servlet-name>captcha</servlet-name>  
    91.         <url-pattern>/captcha</url-pattern>  
    92.     </servlet-mapping>  
    93.   
    94.     <!-- session超时定义,单位为分钟 -->  
    95.     <session-config>  
    96.         <session-timeout>20</session-timeout>  
    97.     </session-config>  
    98.       
    99.     <!-- 出错页面定义 -->  
    100.     <error-page>  
    101.         <exception-type>java.lang.Throwable</exception-type>  
    102.         <location>/WEB-INF/views/error/500.jsp</location>  
    103.     </error-page>  
    104.     <error-page>  
    105.         <error-code>500</error-code>  
    106.         <location>/WEB-INF/views/error/500.jsp</location>  
    107.     </error-page>  
    108.     <error-page>  
    109.         <error-code>404</error-code>  
    110.         <location>/WEB-INF/views/error/404.jsp</location>  
    111.     </error-page>  
    112. </web-app>  

     applicationContext-shiro.xml

    Xml代码  收藏代码
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    3.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"  
    4.     default-lazy-init="true">  
    5.   
    6.     <description>Shiro Configuration</description>  
    7.   
    8.     <!-- Shiro's main business-tier object for web-enabled applications -->  
    9.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
    10.         <property name="realm" ref="shiroDbRealm" />  
    11.         <property name="cacheManager" ref="cacheManager" />  
    12.     </bean>  
    13.   
    14.     <!-- 項目自定义的Realm -->  
    15.     <bean id="shiroDbRealm" class="com.surfilter.pscms.service.account.ShiroDbRealm"  depends-on="userDao,groupDao">  
    16.         <property name="accountManager" ref="accountManager"/>  
    17.     </bean>  
    18.   
    19.     <!-- Shiro Filter -->  
    20.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
    21.         <property name="securityManager" ref="securityManager" />  
    22.         <property name="loginUrl" value="/loginpw" />  
    23.         <property name="successUrl" value="/main/" />  
    24.         <property name="filters">   
    25.             <map>   
    26.                 <entry key="authc" value-ref="authc"></entry>   
    27.             </map>  
    28.         </property>  
    29.         <property name="filterChainDefinitions">  
    30.             <value>  
    31.                 /loginpw = authc  
    32.                 /logoutlogout = logout  
    33.                 /captcha = anon  
    34.                 /static/** = anon  
    35.                 /mobile/** = anon  
    36.                 /** = user  
    37.             </value>  
    38.         </property>  
    39.     </bean>  
    40.       
    41.     <bean id="authc" class="com.surfilter.pscms.service.captcha.CaptchaFormAuthenticationFilter"></bean>  
    42.       
    43.       
    44.     <!-- 用户授权信息Cache -->  
    45.     <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />  
    46.       
    47.     <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->  
    48.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  
    49.       
    50.     <!-- AOP式方法级权限检查  -->  
    51.     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">  
    52.         <property name="proxyTargetClass" value="true" />  
    53.     </bean>  
    54.       
    55.     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
    56.         <property name="securityManager" ref="securityManager"/>  
    57.     </bean>  
    58. </beans>  

    spring-mvc.xml

    Xml代码  收藏代码
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"  
    3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    4.     xmlns:context="http://www.springframework.org/schema/context"  
    5.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
    6.     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd  
    7.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
    8.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">  
    9.   
    10.     <!-- 自动扫描且只扫描@Controller -->  
    11.     <context:component-scan base-package="com.surfilter.pscms" use-default-filters="false">  
    12.         <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
    13.     </context:component-scan>  
    14.     <bean id="permission" class="com.surfilter.pscms.entity.account.Permission" init-method="initialize"/>   
    15.     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">    
    16.         <property name="messageConverters">     
    17.             <list>     
    18.                 <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />    
    19.                 <bean class="org.springframework.http.converter.StringHttpMessageConverter">     
    20.                     <property name="supportedMediaTypes">     
    21.                         <list><value>text/plain;charset=UTF-8</value></list>     
    22.                     </property>     
    23.                 </bean>     
    24.                 <bean class="org.springframework.http.converter.ResourceHttpMessageConverter" />     
    25.                 <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />    
    26.                 <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />    
    27.                 <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />    
    28.             </list>     
    29.         </property>     
    30.     </bean>  
    31.     <mvc:annotation-driven />  
    32.     <mvc:default-servlet-handler/>  
    33.       
    34.     <!-- 定义首页 -->  
    35.     <mvc:view-controller path="/" view-name="redirect:/main/"/>  
    36.   
    37.     <!-- 定义JSP -->   
    38.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
    39.         <property name="prefix" value="/WEB-INF/views/"/>  
    40.         <property name="suffix" value=".jsp"/>  
    41.     </bean>  
    42.     <!-- View resolvers can also be configured with ResourceBundles or XML files.      
    43.         If you need different view resolving based on Locale, you have to use the      
    44.         resource bundle resolver. -->     
    45.     <!-- 这个是针对返回视图还是json值的视图配置   来分别处理同步和异步请求 -->     
    46.     <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">     
    47.          <property name="mediaTypes">     
    48.              <map>     
    49.                  <entry key="html" value="text/html" />     
    50.                  <entry key="json" value="application/json" />     
    51.              </map>     
    52.          </property>     
    53.          <property name="favorParameter" value="true" />     
    54.          <property name="viewResolvers">     
    55.              <list>     
    56.                  <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />     
    57.                  <bean id="viewResolver"    
    58.                      class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">     
    59.                      <property name="cache" value="true" />     
    60.                      <property name="prefix" value="" />     
    61.                      <property name="suffix" value=".ftl" />     
    62.                      <property name="contentType" value="text/html;charset=UTF-8"></property>     
    63.                      <property name="requestContextAttribute" value="request" />     
    64.                      <property name="exposeSpringMacroHelpers" value="true" />     
    65.                      <property name="exposeRequestAttributes" value="true" />     
    66.                      <property name="exposeSessionAttributes" value="true" />     
    67.                  </bean>     
    68.              </list>     
    69.          </property>     
    70.          <property name="defaultContentType" value="text/html" />     
    71.     </bean>  
    72.   
    73.     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
    74.         <property name="maxUploadSize">    
    75.             <value>10485760</value>    
    76.         </property>    
    77.         <property name="maxInMemorySize">    
    78.             <value>5120</value>    
    79.         </property>    
    80.     </bean>    
    81.       
    82.     <!-- 支持 Shiro对Controller的方法级AOP安全控制 begin-->  
    83.     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">  
    84.         <property name="proxyTargetClass" value="true" />  
    85.     </bean>  
    86.       
    87.     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
    88.         <property name="securityManager" ref="securityManager"/>  
    89.     </bean>  
    90.       
    91.     <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">    
    92.         <property name="exceptionMappings">    
    93.             <props>    
    94.                 <prop key="org.apache.shiro.authz.UnauthorizedException">error/403</prop>    
    95.             </props>    
    96.         </property>    
    97.     </bean>    
    98.     <!-- end -->  
    99.       
    100.     <!-- 初始化加载板块列表 -->  
    101.     <bean id="showBoards" class="com.surfilter.pscms.bean.ShowBoards" init-method="init"></bean>  
    102.       
    103. </beans>  

    ShiroDbRealm.java继承AuthorizingRealm 重新认证和鉴权的方法

    Java代码  收藏代码
    1. package com.surfilter.pscms.service.account;  
    2.   
    3. import java.io.Serializable;  
    4.   
    5. import org.apache.shiro.SecurityUtils;  
    6. import org.apache.shiro.authc.AuthenticationException;  
    7. import org.apache.shiro.authc.AuthenticationInfo;  
    8. import org.apache.shiro.authc.AuthenticationToken;  
    9. import org.apache.shiro.authc.SimpleAuthenticationInfo;  
    10. import org.apache.shiro.authz.AuthorizationInfo;  
    11. import org.apache.shiro.authz.SimpleAuthorizationInfo;  
    12. import org.apache.shiro.cache.Cache;  
    13. import org.apache.shiro.realm.AuthorizingRealm;  
    14. import org.apache.shiro.subject.PrincipalCollection;  
    15. import org.apache.shiro.subject.SimplePrincipalCollection;  
    16. import org.springframework.beans.factory.annotation.Autowired;  
    17.   
    18. import com.surfilter.pscms.entity.account.User;  
    19. import com.surfilter.pscms.service.captcha.CaptchaUsernamePasswordToken;  
    20. import com.surfilter.pscms.service.captcha.IncorrectCaptchaException;  
    21.   
    22. /** 
    23.  * 自实现用户与权限查询. 演示关系,密码用明文存储,因此使用默认 的SimpleCredentialsMatcher. 
    24.  */  
    25. public class ShiroDbRealm extends AuthorizingRealm {  
    26.   
    27.     private AccountManager accountManager;  
    28.   
    29.     /** 
    30.      * 认证回调函数, 登录时调用. 
    31.      */  
    32.     @Override  
    33.     protected AuthenticationInfo doGetAuthenticationInfo(  
    34.             AuthenticationToken authcToken) throws AuthenticationException {  
    35.         CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken;  
    36.         // 验证码 验证  
    37.         String captcha = null;  
    38.         Object obj_captcha = SecurityUtils.getSubject().getSession()  
    39.                 .getAttribute("RandomCode");  
    40.         if (obj_captcha instanceof String)  
    41.             captcha = (String) obj_captcha;  
    42.   
    43.         if (captcha != null && !captcha.equalsIgnoreCase(token.getCaptcha())) {  
    44.             throw new IncorrectCaptchaException("验证码错误!");  
    45.         }  
    46.   
    47.         // 用户名密码验证  
    48.         User user = accountManager.findUserByLoginName(token.getUsername());  
    49.         if (user != null) {  
    50.             SecurityUtils.getSubject().getSession().setAttribute(  
    51.                     "loginUserInfo", user);  
    52.             return new SimpleAuthenticationInfo(new ShiroUser(user  
    53.                     .getLoginName(), user.getName()), user.getPassword(),  
    54.                     getName());  
    55.         } else {  
    56.             return null;  
    57.         }  
    58.     }  
    59.   
    60.     /** 
    61.      * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. 
    62.      */  
    63.     @Override  
    64.     protected AuthorizationInfo doGetAuthorizationInfo(  
    65.             PrincipalCollection principals) {  
    66.         ShiroUser shiroUser = (ShiroUser) principals.fromRealm(getName())  
    67.                 .iterator().next();  
    68.         User user = accountManager  
    69.                 .findUserByLoginName(shiroUser.getLoginName());  
    70.         if (user != null) {  
    71.             SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
    72.             info.addStringPermissions(accountManager.getUserPermissions(user.getId()));  
    73.             return info;  
    74.         } else {  
    75.             return null;  
    76.         }  
    77.     }  
    78.   
    79.     /** 
    80.      * 更新用户授权信息缓存. 
    81.      */  
    82.     public void clearCachedAuthorizationInfo(String principal) {  
    83.         SimplePrincipalCollection principals = new SimplePrincipalCollection(  
    84.                 principal, getName());  
    85.         clearCachedAuthorizationInfo(principals);  
    86.     }  
    87.   
    88.     /** 
    89.      * 清除所有用户授权信息缓存. 
    90.      */  
    91.     public void clearAllCachedAuthorizationInfo() {  
    92.         Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();  
    93.         if (cache != null) {  
    94.             for (Object key : cache.keys()) {  
    95.                 cache.remove(key);  
    96.             }  
    97.         }  
    98.     }  
    99.   
    100.     @Autowired  
    101.     public void setAccountManager(AccountManager accountManager) {  
    102.         this.accountManager = accountManager;  
    103.     }  
    104.   
    105.     /** 
    106.      * 自定义Authentication对象,使得Subject除了携带用户的登录名外还可以携带更多信息. 
    107.      */  
    108.     public static class ShiroUser implements Serializable {  
    109.   
    110.         private static final long serialVersionUID = -1748602382963711884L;  
    111.         private String loginName;  
    112.         private String name;  
    113.   
    114.         public ShiroUser(String loginName, String name) {  
    115.             this.loginName = loginName;  
    116.             this.name = name;  
    117.         }  
    118.   
    119.         public String getLoginName() {  
    120.             return loginName;  
    121.         }  
    122.   
    123.         /** 
    124.          * 本函数输出将作为默认的<shiro:principal/>输出. 
    125.          */  
    126.         @Override  
    127.         public String toString() {  
    128.             return loginName;  
    129.         }  
    130.   
    131.         public String getName() {  
    132.             return name;  
    133.         }  
    134.     }  
    135. }  
  • 相关阅读:
    mysql判断一个字符串是否包含某几个字符
    mysql动态sql 整理多个字段
    mysql 把表中某一列的内容合并为一行
    linux基础
    shell基础
    香港主机Squid+Stunnel代理搭建
    mysql字符串根据指定字符分割
    tomcat项目快速启动设置
    Linux系统内存占用90%以上——解决方法
    redis常用命令
  • 原文地址:https://www.cnblogs.com/eggbucket/p/2954197.html
Copyright © 2011-2022 走看看