shiro(三)ssh的集成

1、項目目錄結構java

2、pom文件web

<!-- shiro -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.2.3</version>
  </dependency>
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.2.3</version>
  </dependency>
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>1.2.3</version>
  </dependency>
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</artifactId>
    <version>1.2.3</version>
  </dependency>

3、spring-shiro.xml文件spring

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <!-- Shiro's main business-tier object for web-enabled applications -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myShiroRealm" />
        <property name="cacheManager" ref="cacheManager" />
    </bean>

    <!-- 項目自定義的Realm -->
    <bean id="myShiroRealm" class="com.shiro.realm.MyShiroRealm">
        <property name="cacheManager" ref="cacheManager" />
    </bean>


    <!-- shiro-all.jar
     filterChainDefinitions:apache
     shiro經過filterChainDefinitions參數來分配連接的過濾,
     資源過濾有經常使用的如下幾個參數:
     authc 表示須要認證的連接
     perms[/url] 表示該連接須要擁有對應的資源/權限才能訪問
     roles[admin] 表示須要對應的角色才能訪問
     perms[admin:url] 表示須要對應角色的資源才能訪問

     -->
    <!-- Shiro Filter -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- 安全管理器 -->
        <property name="securityManager" ref="securityManager" />
        <!-- 未認證,跳轉到哪一個頁面      -->
        <property name="loginUrl" value="/views/shiro/login.jsp" />
        <!-- 登陸成功跳轉頁面    -->
        <property name="successUrl" value="/views/shiro/success.jsp" />
        <!-- 認證後,沒有權限跳轉頁面 -->
        <property name="unauthorizedUrl" value="/views/shiro/error.jsp" />
        <!-- shiro URL控制過濾器規則
       anon未認證能夠訪問
authc認證後能夠訪問
perms須要特定權限才能訪問
roles須要特定角色才能訪問
user須要特定用戶才能訪問
port須要特定端口才能訪問(不經常使用)
rest根據指定HTTP請求才能訪問(不經常使用)
   *文件夾中的所有文件
   **  文件夾中的所有文件(含子文件夾)
       -->
        <property name="filterChainDefinitions">
            <value>

                <!-- 對靜態資源設置匿名訪問 -->
                /static/** = anon
                /shiro/login.jsp = anon
                /shiro/checkLogin** = anon
                /shiro/success.jsp = anon
                /** = authc

            </value>
        </property>
    </bean>

    <!-- 用戶受權信息Cache -->
    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />

    <!-- 保證明現了Shiro內部lifecycle函數的bean執行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

    <!-- AOP式方法級權限檢查 -->
    <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>
</beans>

4、將spring-shiro.xml引入application裏sql

5、web.xml里加入shiro過濾器(注意:shiro過濾器要放在springmvc的前面!!!)數據庫

<!-- shiro-start -->
  <!-- 讀取spring和shiro配置文件  shiro過濾器要放在springmvc前面-->
  <!-- shiro過濾器 -->
  <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <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-->

6、編寫控制層(前臺登錄時 提交給checkLogin進行登錄操做)apache

package com.shiro.controller;


import com.shiro.pojo.User;
import com.shiro.service.AccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


import javax.annotation.Resource;

@Controller
@RequestMapping(value = "/shiro")
public class shiroController {
    @Autowired
    private AccountService accountService;

    @RequestMapping(value = "/checkLogin",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView checkLogin(String username,
                                   String password)
    {
        ModelAndView mav = new ModelAndView();
        User user = accountService.getUserByName(username);
        if (user == null) {
            mav.setViewName("/shiro/login");
            mav.addObject("msg", "用戶不存在");
            return mav;
        }
        if (!user.getPassword().equals(password)) {
            mav.setViewName("/shiro/error");
            mav.addObject("msg", "賬號密碼錯誤");
            return mav;
        }
        SecurityUtils.getSecurityManager().logout(SecurityUtils.getSubject());
        // 登陸後存放進shiro token
        UsernamePasswordToken token = new UsernamePasswordToken(
                user.getUsername(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();

        subject.login(token);
        // 登陸成功後會跳轉到successUrl配置的連接,不用管下面返回的連接。
        mav.setViewName("/shiro/success");
        return mav;
    }

        @RequestMapping(value = "/logout",method = RequestMethod.POST)
        public String logout(RedirectAttributes redirectAttributes)
        {
            SecurityUtils.getSubject().logout();
            redirectAttributes.addFlashAttribute("message","已安全退出");
            return "redirect:/shiro/login";
        }

}

7、編寫(自定義)shiroRealm安全

package com.shiro.realm;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.shiro.pojo.Role;
import com.shiro.pojo.User;
import com.shiro.service.AccountService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;


public class MyShiroRealm extends AuthorizingRealm {



    @Resource
    private AccountService accountService;


    /*
     * 權限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //獲取登陸時輸入的用戶名
        String loginName=(String) principals.fromRealm(getName()).iterator().next();
        //到數據庫查是否有此對象
        User user=accountService.getUserByName(loginName);
        List<String> roleList =accountService.getRoleByUserName(loginName);
        List<String> permList = new ArrayList<String>();
        System.out.println("對當前用戶:["+loginName+"]進行受權!");
        if (user!=null)
        {
            //權限信息對象info,用來存放查出的用戶的全部的角色(role)及權限(permission)
            SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
            //用戶的角色集合
            info.addRoles(roleList);

        }


        return null;
    }

    /*
     * 登陸驗證
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String username=token.getUsername();
        if (username!=null && !"".equals(username)){
        User user=accountService.getUserByName(username);
        if(user!=null)
        {
                return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
        }
        }
        return null;
    }


}

8、dao層和service層省略mvc

getUserByName的sql:app

from User where username='"+username+"'

getRoleByUsernaem的sql:jsp

SELECT
 t_role.rolename
from
t_role,t_user,t_user_role
where
t_role.id = t_user_role.role_id
and t_user.id = t_user_role.user_id
AND t_user.username='"+loginName+"'

9、login.jsp

相關文章
相關標籤/搜索