IDEA+Mavan:Shiro基于SpringMVC+Myba

作者: Wocus | 来源:发表于2018-03-23 11:52 被阅读77次

    简介

    Shiro是一个强大的简单易用的Java安全框架,主要用来更便捷的认证,授权,加密,会话管理。Shiro首要的和最重要的目标就是容易使用并且容易理解。

    Shiro是一个有许多特性的全面的安全框架,下面这幅图可以了解Shiro的特性:


    Shiro框架

    数据库表结构


    权限表

    使用

    1.导入shiro第三方jar包
    <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-core</artifactId>
          <version>1.4.0</version>
        </dependency>
        <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-spring</artifactId>
          <version>1.4.0</version>
        </dependency>
    
    2.web.xml配置过滤
    <!-- shiro 过滤器 start -->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-context.xml,classpath:spring-shiro.xml</param-value>
      </context-param>
      <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <!-- 设置true由servlet容器控制filter的生命周期 -->
        <init-param>
          <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>
      <!-- shiro 过滤器 end -->
    
    3.自定义Realm 继承AuthorizingRealm 重写 AuthorizationInfo(授权) 和 AuthenticationInfo(认证)
    import java.util.HashSet;
    import java.util.Set;
    
    public class MyRealm extends AuthorizingRealm {
    
        @Autowired
        private ITAdminService iTAdminService;
    
        @Autowired
        private ITPermissionService iTPermissionService;
    
        @Autowired
        private ITRoleService iTRoleService;
    
        /**
         * 账号授权
         * @param principalCollection
         * @return
         */
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            String account=principalCollection.getPrimaryPrincipal().toString();
            SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
            //取得这个人的权限
            Set<String> list_permission=iTPermissionService.selectPermission(account);
            //取得这个人的角色信息
            String roleName=iTRoleService.selectByPrimaryKey(iTAdminService.selectTAdmin(account).getRoleId()).getRoleName();
            Set<String> set_role=new HashSet<String>();
            set_role.add(roleName);
            //授予角色信息
            authorizationInfo.setRoles(set_role);
            //授予权限信息
            authorizationInfo.setStringPermissions(list_permission);
            return authorizationInfo;
        }
    
        /**
         * 账号认证
         * @param authenticationToken
         * @return
         * @throws AuthenticationException
         */
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    
            //获取账号信息
            String account=authenticationToken.getPrincipal().toString();
    
            try{
                TAdmin admin=iTAdminService.selectTAdmin(account);
                if (admin!=null){
                    AuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(account,admin.getPassword(),getName());
                    return authenticationInfo;
                }else{
                    return null;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }
    }
    
    
    
    4.spring_shiro.xml配置
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
        <description>Shiro 配置</description>
        <!--自定义Realm 继承自AuthorizingRealm -->
        <bean id="monitorRealm" class="com.sansence.wine.realm.MyRealm"></bean>
        <bean id="iTAdminService" class="com.sansence.wine.service.impl.TAdminServiceImpl"></bean>
        <bean id="iTPermissionService" class="com.sansence.wine.service.impl.TPermissionServiceImpl"></bean>
        <bean id="iTRoleService" class="com.sansence.wine.service.impl.TRoleServiceImpl"></bean>
    
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
            <!--设置自定义realm -->
            <property name="realm" ref="monitorRealm" />
        </bean>
    
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" depends-on="iTAdminService,iTPermissionService,iTRoleService">
            <property name="securityManager" ref="securityManager" />
            <!--设置未授权跳转的界面 -->
            <property name="loginUrl" value="/index.jsp" />
            <property name="successUrl" value="/" />
    
            <property name="filterChainDefinitions">
                <value>
                    /index.jsp=anon
                    <!--/getAdminlogin.do=anon
                    /ship/checkid.do=anon
                    /palycrad/insert.do=anon
                    /palycrad/*.do =authc,roles[user]
                    /employee/*.do =authc,roles[user]
                    /ship/*.do =authc,roles[user]
                    /shiptype/*.do =authc,roles[user]
                    /*.do=authc,roles[user]
                    /*.jsp =authc,roles[user]-->
                </value>
            </property>
        </bean>
    
        <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
    
    
        <!-- securityManager -->
        <bean
                class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
            <property name="staticMethod"
                      value="org.apache.shiro.SecurityUtils.setSecurityManager" />
            <property name="arguments" ref="securityManager" />
        </bean>
    
        <!-- Enable Shiro Annotations for Spring-configured beans. Only run after -->
        <!-- the lifecycleBeanProcessor has run: -->
        <bean
                class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
                depends-on="lifecycleBeanPostProcessor" />
        <bean
                class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
            <property name="securityManager" ref="securityManager" />
    
        </bean>
    
    </beans>
    

    以下提供一些过滤器仅供参考


    过滤器

    roles[user]代表只有角色为user的才可以访问多个用逗号隔开
    perms[user:select]代表需要权限user:select才可以访问,多个用逗号隔开

    登录登出

    '''java
    @Controller
    @RequestMapping("adminController")
    public class AdminController {

    /**
     * 登录
     * @param admin
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/login",method = {RequestMethod.POST})
    public ModelAndView getLogin(TAdmin admin, HttpServletRequest request, HttpServletResponse response){
        ModelAndView modelAndView=new ModelAndView("index");
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(admin.getAccount(), MD5Util.MD5Encode(admin.getPassword()));
        token.setRememberMe(true);
        try {
            subject.login(token);
        }catch (Exception e){
            e.printStackTrace();
        }
        return modelAndView;
    }
    
    /**
     * 登出
     * @return
     */
    @RequestMapping(value = "/logout",method = {RequestMethod.GET})
    public ModelAndView getLogout(){
        ModelAndView modelAndView=new ModelAndView();
        SecurityUtils.getSubject().logout();
        return modelAndView;
    }
    

    '''

    相关文章

      网友评论

      • IT人故事会:贵在坚持,么么哒!我也是个爱写文章的人

      本文标题:IDEA+Mavan:Shiro基于SpringMVC+Myba

      本文链接:https://www.haomeiwen.com/subject/opxaqftx.html