在ssm框架中嵌入shiro安全框架


1.需要相关的shiro的jar包

  <!-- shiro -->
    <dependency>  
    <groupId>com.alibaba</groupId>  
    <artifactId>fastjson</artifactId>  
    <version>1.1.32</version>  
    </dependency>  
    <dependency>  
    <groupId>org.apache.shiro</groupId>  
    <artifactId>shiro-core</artifactId>  
    <version>1.2.2</version>  
</dependency>  
<dependency>  
    <groupId>org.apache.shiro</groupId>  
    <artifactId>shiro-web</artifactId>  
    <version>1.2.2</version>  
</dependency>  
<dependency>  
    <groupId>org.apache.shiro</groupId>  
    <artifactId>shiro-spring</artifactId>  
    <version>1.2.2</version>  
</dependency>  
<dependency>  
    <groupId>org.apache.shiro</groupId>  
    <artifactId>shiro-ehcache</artifactId>  
    <version>1.2.2</version>  
</dependency>  

2.需要在web.xml中进行配置

 <!-- 配置  Shiro 的 Filter -->  
         <filter>  
          <description>shiro 权限拦截</description>  
          <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>


3.在spring-mvc.xml中进行配置

<!-- shiro配置 -->
   <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
        <property name="securityManager" ref="securityManager"/>  

    </bean> 


4.在applicationContex.xml中进行导入xml

 <!-- 开启自动扫描 -->
     <context:component-scan base-package="com.yimao"/>
     <import resource="/spring.xml/spring-shiro.xml"/>
     <import resource="/spring.xml/spring-dao.xml"/>
     <import resource="/spring.xml/spring-db.xml"/>
     <import resource="/spring.xml/spring-tx.xml"/>
     <import resource="/spring.xml/spring-redis.xml"/>

5.添加一个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:p="http://www.springframework.org/schema/p"    
    xmlns:context="http://www.springframework.org/schema/context"    
    xmlns:mvc="http://www.springframework.org/schema/mvc"    
    xsi:schemaLocation="http://www.springframework.org/schema/beans      
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd      
                        http://www.springframework.org/schema/context      
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd      
                        http://www.springframework.org/schema/mvc      
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
                        
                        <!-- ================ Shiro start ================ -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="ShiroRealm"/>
        <!-- 缓存 配置(暂不用)
        <property name="cacheManager" ref="cacheManager"/> -->
    </bean>

    <!-- <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/>
    </bean> -->

    <bean id="ShiroRealm" class="com.yimao.shiro.ShiroRealm"></bean>

   <!-- 第一种放行配置 -->
    <!-- <bean id="chainDefinitionSectionMetaSource"
          class="com.yimao.shiro.ChainDefinitionSectionMetaSource">

        <property name="filterChainDefinitions">
            <value>
                /static/** = anon
                /docs/** = anon
                /favicon.ico = anon
                /login_login = anon
                /oaAdmin.jsp = anon
                /code.do  = anon
                /oa_admin_login = anon
                /index.jsp = anon
                /login_toLogin = anon
                /              = anon
                /testUploadImage = anon
                /reg/* = anon
                /test/* = anon
                /app/* = anon
                /web/login/enterpriseUserChangePWDByMail = anon
                /web/login/enterpriseUserChangePWDByMail.jsp = anon
                /getRuleDescriotionByType = anon
                /rule/appRuleDescription.jsp = anon
                /jiuzhousupin/upload/** = anon
                /upload/** = anon
                /Invitation/** = anon
                /invitationToUser = anon
                /userRegister = anon
                /mobileinvitation = anon
                /download = anon
                /fileDownload/** = anon
                /conUserLogin = anon
                /bauUserLogin = anon
            </value>
        </property>
    </bean> -->
    
      <!-- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>

        <property name="loginUrl" value="/logout.jsp"/>

        <property name="successUrl" value="/main/index"/>

        <property name="unauthorizedUrl" value="/logout.jsp"/>
                     添加各种验证过滤器
         <property name="filters">
            <map>
                <entry key="custom">
                    <bean class="com.yimao.shiro.ShiroCustom">
                    </bean>
                </entry>
            </map>
        </property>
                   访问权限配置
        <property name="filterChainDefinitionMap" ref="chainDefinitionSectionMetaSource"/>
    </bean> -->
    <!-- ================ Shiro end ================ -->
    
    
    
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        
        <property name="loginUrl" value="/login.jsp"/>
        <property name="successUrl" value="/success.jsp"/>
         <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
        <!-- 添加各种验证过滤器  <property name="filters">  
            <map>  
                <entry key="roleOrFilter" value-ref="roleOrFilter"/>  
            </map>  
        </property> -->
        <!-- 第二种放行配置 -->
        <property name="filterChainDefinitions">
            <value>
                <!-- 静态资源允许访问
                /app/** = anon
                /assets/** = anon
                /static/** = anon-->
                <!-- 登录页允许访问 -->
                /html/** = anon
                /login.jsp = anon
                /yimao = anon
                /login = anon
                /user/login.do = anon
                /user/admin* = anon
                /user/student*/** = roles[teacher]
                /user/teacher*/** = perms["user:create"]
                
               <!--  /rest/user/login = anon
                /rest/user/registerCustomer = anon
                /rest/user/findPwd = anon
                /rest/user/getUserByName = anon -->
                <!-- 其他资源需要认证 -->
               <!--  /** = authc -->
                 /** = authc
            </value>
        </property>
    </bean>

 

    </beans>

6.配置shiro的安全认证的类(认证规则)

package com.yimao.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;
import org.springframework.beans.factory.annotation.Autowired;

import com.yimao.entity.User;
import com.yimao.service.UserService;

public class ShiroRealm extends AuthorizingRealm{

    @Autowired
    private UserService UserService;
    
    /**
     *  为当前登陆成功的用户授予权限和角色,已经登陆成功了
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal(); //获取用户名
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(UserService.getRoles(username));
        authorizationInfo.setStringPermissions(UserService.getPermissions(username));
        return authorizationInfo;
    }

    /**
     * 验证登录前的
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal(); // 获取用户名
        User user = UserService.getByUsername(username);
        if(user != null) {
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUname(), user.getPwd(), "myRealm");
            return authcInfo;
        } else {
            return null;
        }       
    }

    

}

7.controller的相关调用

@Controller
@RequestMapping("/user")
public class TestController {
    @Autowired
    private TestService tests;
    @Autowired
    private RedisBaiseTakes redis;
    /*@RequestMapping("/test.do")
    void test(@ModelAttribute User u){
        System.out.println("hello:"+u.toString());
    }*/
    
    //用户登录
    @RequestMapping("/login.do")
    public String login(User user, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUname(), user.getPwd());
        try{
            subject.login(token);//会跳到我们自定义的realm中
            request.getSession().setAttribute("user", user);
            redis.add("rb", user.getUname());
            System.out.println(redis.get("rb"));
            return "success";
        }catch(Exception e){
            e.printStackTrace();
            request.getSession().setAttribute("user", user);
            request.setAttribute("error", "用户名或密码错误!");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "index";
    }   

    @RequestMapping("/admin")
    public String admin(HttpServletRequest request) {
        return "success";
    }

    @RequestMapping("/student")
    public String student(HttpServletRequest request) {
        return "success";
    }   

    @RequestMapping("/teacher")
    public String teacher(HttpServletRequest request) {
        return "success";
    }   

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值