Shiro整合springmvc

1 篇文章 0 订阅

1.web.xml

配置核心filter:DelegatingFilterProxy进行过滤

<?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_2_5.xsd"
         version="2.5">

    <!--spring mvc -->
    <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:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--spring -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext*.xml</param-value>
    </context-param>

    <!-- shiro-->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

2.applicationcontext.xml

核心步骤5部:

  1. 创建DefaultWebSecurityManager,关联缓存和realm
  2. 创建缓存EhCacheManager,关联缓存配置文件
  3. 创建自定义realm
  4. shiroFliter的具体配置(id名必须和web.xml中的filter同名)
  5. 若有注解必配:LifecycleBeanPostProcessor;
    DefaultAdvisorAutoProxyCreator;
    AuthorizationAttributeSourceAdvisor
      <?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:context="http://www.springframework.org/schema/context"
               xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
            <!-- shiro核心:设置缓存和realm-->
            <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
                <property name="cacheManager" ref="cacheManager"/>
                <property name="realm" ref="myrealm"/>
            </bean>
        
            <!--配置缓存管理 -->
            <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
                <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
            </bean>
        
            <!-- 自定义realm-->
            <bean id="myrealm" class="com.relam.UserRealm"/>
        
            <!--shiro对象注解在spring容器中生效 -->
            <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
            <bean id="defaultAdvisorAutoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
            <bean id="authorizationAttributeSourceAdvisor" class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
                <property name="securityManager" ref="securityManager"/>
            </bean>
        
            <!-- shiro filter-->
            <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="/index.jsp"/>
                <property name="unauthorizedUrl" value="/unauthorizaed.jsp"/>
                <property name="filterChainDefinitions">
                    <value>
                        /static/**=anon
                        /login=anon
                        /user/list=perms[sys:user:select]
                        /user/**=roles["讲师","管理员"]
                        /**=authc
                    </value>
                </property>
            </bean>
        </beans>  

3.自定义realm

    package com.relam;
    import com.entity.User;
    import com.service.MenuService;
    import com.service.UserService;
    import org.apache.shiro.authc.*;
    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 javax.annotation.Resource;
    import java.util.List;
    public class UserRealm extends AuthorizingRealm {
        @Resource(name="userService")
        private UserService userService;
        @Resource
        private MenuService menuService;
    
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            System.out.println("授权--doGetAuthorizationInfo");
            //得到当前用户
            User user=(User) principalCollection.getPrimaryPrincipal();
            //得到当前用户的角色和权限
            List<String> roles = userService.showRolesById(user.getId());
            List<String> perms = menuService.showPermsByUserId(user.getId());
            //创建authorizationInfo对象
            SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
            info.addRoles(roles);
            info.addStringPermissions(perms);
            return info;
        }
    
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            System.out.println("认证--doGetAuthenticationInfo");
            String uname=(String) authenticationToken.getPrincipal();
            String passw=new String((char[])authenticationToken.getCredentials());
            System.out.println(uname+"\t"+passw);
            User user=userService.login(uname);
            if(user==null){
                throw new UnknownAccountException("用户不存在!");
            }
            if(!user.getPassword().equals(passw)){
                throw new IncorrectCredentialsException("密码输入不正确");
            }
            if(user.getStatus()==0){
                throw new LockedAccountException("账号已被锁定,请与管理员联系!");
            }
            AuthenticationInfo info=new SimpleAuthenticationInfo(user,passw,this.getName());
            return info;
        }
    }

4.登陆

 @Controller
public class UserController {
    @Resource
    private UserService userService;

   @RequestMapping("/login")
    public String login(String username, String password,boolean remenber, Model model){

        password=new Md5Hash(password,username,1024).toString();
        UsernamePasswordToken user=new UsernamePasswordToken(username,password);
        Subject subject=SecurityUtils.getSubject();

        try{
            if(remenber){
                user.setRememberMe(true);
            }
            subject.login(user);

            return "redirect:/user/list";
        }catch(Exception e){
            e.printStackTrace();
            model.addAttribute(e.getMessage());
        }
        return "login";
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值