SSM + Shiro 整合

2017-08-09  本文已影响0人  Made0107

1.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ssm</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 配置spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>  

    <!-- 配置springmvc -->
    <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/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    
    <!-- shiro过虑器,DelegatingFilterProx会从spring容器中找shiroFilter -->
    <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>
  
    <!-- 转码过滤器 -->
    <filter>
        <filter-name>characterEncodingFilter</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>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

2.创建 RealmCustom继承 AuthorizingRealm

package com.made.md.shiro;

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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class RealmCustom  extends  AuthorizingRealm{

    
    
    /**
     *  返回 权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        // TODO Auto-generated method stub
        
        // 1. 获取 用户名
        String userName = principal.getPrimaryPrincipal().toString();
        
        // 2. 根据 用户名 调用数据库 查看该用户下的角色 以及 权限
        
        // 3. 添加  角色 以及 权限
        SimpleAuthorizationInfo simpleInfo = new SimpleAuthorizationInfo();
        
        simpleInfo.addRole("admin");
        simpleInfo.addStringPermission("ma1");
    
        
        return simpleInfo;
    }

    /**
     * 验证登录信息
     * 返回 登录信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // TODO Auto-generated method stub
        
        // 1.获取 用户名 密码
        String userName = token.getPrincipal().toString();
        String password = new String((char[])token.getCredentials());
        
        // 2. 通过 调用数据库 来验证 登录信息是否正确
        
        // 3. 如果 一切 正确 返回
        SimpleAuthenticationInfo simpleInfo = new SimpleAuthenticationInfo(userName, password, getName());
        
        return simpleInfo;
    }
}  

3.创建 applicationContext-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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    
    <!-- 配置自定义Realm -->
    <bean id="realmCustom" class="com.made.md.shiro.RealmCustom" />

    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="realmCustom" />
    </bean>

    <!-- Shiro过滤器 核心 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- Shiro的核心安全接口,这个属性是必须的 -->
        <property name="securityManager" ref="securityManager" />
        <!-- 登录页面请求地址  -->
        <property name="loginUrl" value="/toLogin" />
        <!-- 登录成功之后的 跳转页面 -->
        <property name="successUrl" value="/toHome"></property>
        <!-- 权限认证失败,则跳转到指定页面 -->
        <property name="unauthorizedUrl" value="/toUnAuthorized" />
        <!-- Shiro连接约束配置,即过滤链的定义 -->
        <property name="filterChainDefinitions">
            <value>
                
                <!--  过滤器链的执行顺序是自上而下依次匹配, 如果能匹配上, 则不再往下匹配  -->
                <!-- roles 和perms只能存在一个 谁在下面谁生效 -->
                <!-- authc:必须要验证 
                    logout:退出 
                    anon:匿名随意访问 
                    roles[xxx]:只有角色是xxx的用户可以访问此路径 
                    perms[xxx]:只有有xxx权限的用户可以访问此路径 
                -->
                <!--静态文件 -->
                /css/* = anon
                /lib/* = anon
                /views/* = anon
                
                /doLogin = anon
                /doLogout = logout
                /toAuthorized = perms[ma]
                /** = authc
                
            </value>
        </property>
    </bean>

    <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

    <!-- 开启Shiro注解 -->
    <!-- <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> -->
    <!-- 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.Controller

package com.made.md.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
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.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sun.corba.se.spi.orbutil.fsm.Guard.Result;
import com.made.md.service.UserService;
import com.made.md.utils.CookieUtils;
import com.made.md.utils.ExceptionUtil;
import com.made.md.utils.MdResult;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登录页面
     * @return
     */
    @RequestMapping("toLogin")
    public String isLogin() {

        return "login";
    }

    /**
     * 正在登录,验证登录
     * @param username
     * @param password
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("doLogin")
    public String doLogin(String username, String password, 
            HttpServletRequest request,HttpServletResponse response, Model model) {
        
        // 1. 获取 subject
        Subject subject = SecurityUtils.getSubject();
        
        // 2. 把 账号密码 传给 token 
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        
        // 3.登录 验证密码
        subject.login(token);
        
        return "redirect: toHome";
    }


    /**
     * 登录之后的首页
     * @return
     */
    @RequestMapping("toHome")
    public String toHome() {

        return "home";
    }
    
    /**
     * 退出
     * @return
     */
    @RequestMapping("doLogout")
    public String logout() {
        
        Subject subject = SecurityUtils.getSubject();
        
        subject.logout();
        
        return "login";
    }
    
    
    @RequestMapping("toAuthorized")
    public String toAuthorized() {
        
        return "authorized";
    }
    /**
     *  没有权限的页面
     * @return
     */
    @RequestMapping("toUnAuthorized")
    public String toUnAuthorized() {
        
        return "unAuthorized";
    }
}

上一篇下一篇

猜你喜欢

热点阅读