shiro整合SSM

1.导入POM文件

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.4.0</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>1.4.0</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</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

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>Archetype Created Web Application</display-name>

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

    <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-context.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>
    <--! DelegatingFilterProxy 作用是自动到 Spring容器查找名字为 shiroFilter(filter-name)
    的 bean 并把所有 Filter的操作委托给它 -->
    <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>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

注:DelegatingFilterProxy的filter-name要和spring-shiro中的shiroFilterFactoryBean中的id相同,否则报错,或者使用以下方法(在DelegatingFilterProxy中加入<init-param>)

<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>
        <init-param>
             <param-name>targetBeanName</param-name>
             <param-value>name</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

此时spring-shiro中的shiroFilterFactoryBean中的id和param-value相同,即name

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

    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean>

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"></property>
        <property name="authenticator" ref="authenticator"></property>
        <property name="rememberMeManager" ref="rememberManager"></property>
        <property name="realms">
            <list>
                <ref bean="firstRealm"></ref>
                <ref bean="secondRealm"></ref>
            </list>

        </property>
    </bean>

    <!--配置realm认证策略-->
    <bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
        <property name="authenticationStrategy">
            <!-- <bean class="org.apache.shiro.authc.pam.FirstSuccessfulStrategy"></bean>-->
            <bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
            <!--<bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"></bean>-->
        </property>

    </bean>

    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"></property>
        <property name="loginUrl" value="/login"></property>
        <property name="successUrl" value="/success"></property>
        <property name="unauthorizedUrl" value="/error"></property>

        <!--filterChainDefinitionMap和filterChainDefinitions只能存在一个-->
        <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property>

       <!-- <property name="filterChainDefinitions">
            <value>
                /logout=logout
                /doLogin=anon
                /admin=roles[admin]
                /user=roles[user]
                /vip=roles[vip]
                /**=authc
            </value>

        </property>-->

    </bean>

    <!--设置cookie-->
    <bean id="rememberCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg value="jizhuwo"></constructor-arg>
        <property name="httpOnly" value="true"></property>
        <property name="maxAge" value="100"></property>
    </bean>
    <!--记住我配置-->
    <bean id="rememberManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
        <property name="cookie" ref="rememberCookie"></property>
    </bean>

    <bean id="firstRealm" class="com.shiro.realms.FirstRealm">
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!--加密算法-->
                <property name="hashAlgorithmName" value="MD5"></property>
                <!--加密次数-->
                <property name="hashIterations" value="1024"></property>
            </bean>
        </property>

    </bean>

    <bean id="secondRealm" class="com.shiro.realms.SecondRealm">
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashAlgorithmName" value="SHA1"></property>
                <property name="hashIterations" value="1024"/>
            </bean>
        </property>
    </bean>

    <!--注解生效-->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    <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>

    <!--buildFilterChainDefinitionMap实例工厂-->
    <bean id="filterChainDefinitionMapFactory" class="com.shiro.factory.FilterChainDefinitionMapFactory"></bean>

    <bean id="filterChainDefinitionMap" factory-bean="filterChainDefinitionMapFactory"
          factory-method="buildFilterChainDefinitionMap"></bean>

</beans>

4.Controller

    @RequestMapping("/doLogin")
    public String doLogin(String username, String password) {
        System.out.println("doLogin.............");
        Subject subject= SecurityUtils.getSubject();


        if(!subject.isAuthenticated()){
            UsernamePasswordToken token=new UsernamePasswordToken(username,password,true);
            try {
                subject.login(token);
            } catch (AuthenticationException e) {
                System.out.println("认证失败。");
            }
        }
        return "redirect:success";
    }

5.realm

public class FirstRealm extends AuthorizingRealm{

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken uptoken=(UsernamePasswordToken) token;
        String username = uptoken.getUsername();
        String credentials=null;

        if("zhangsan".equals(username)){
            credentials="2a0d136ceacafe198ea64ac09daaf1b6";
        }else if("lisi".equals(username)){
            credentials = "8c702ae443795331c91cfab48f3f3833";
        }
        ByteSource byteSource=new ByteSource.Util().bytes(username);
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, credentials, byteSource, getName());
       // new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
        return authenticationInfo;
    }

    public static void main(String[] args) {
        String hashAlgorithmName = "MD5";
        Object credentials = "123456";
        Object salt = ByteSource.Util.bytes("lisi");;
        int hashIterations = 1024;

        Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
        System.out.println(result);
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        System.out.println("FirstRealm..2222.........");
        Object primaryPrincipal = principals.getPrimaryPrincipal();

        Set<String> roles = new HashSet<>();
        if("zhangsan".equals(primaryPrincipal)){
            roles.add("user");
            roles.add("vip");
        }else if("abc".equals(primaryPrincipal)){
            roles.add("user");
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);

        return simpleAuthorizationInfo;
    }
}
public class SecondRealm extends AuthorizingRealm{

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken uptoken=(UsernamePasswordToken) token;

        String username = uptoken.getUsername();
        String credentials=null;

        if("abc".equals(username)){
            credentials="31420b87dd2e42f39d7dc7bdc3a7ee12e4053de8";
        }else if("qwe".equals(username)){
            credentials = "466c492b84308fb956c6d1acf4301743cbc19037";
        }
        ByteSource byteSource=new ByteSource.Util().bytes(username);
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, credentials, byteSource, getName());
       // new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
        return authenticationInfo;
    }

    public static void main(String[] args) {
        String hashAlgorithmName = "SHA1";
        Object credentials = "123";
        Object salt = ByteSource.Util.bytes("qwe");;
        int hashIterations = 1024;

        Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
        System.out.println(result);
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        System.out.println("secondRealm...。。。..........");
        Object primaryPrincipal = principals.getPrimaryPrincipal();

        Set<String> roles = new HashSet<>();
        if("zhangsan".equals(primaryPrincipal)){
            roles.add("admin");
        }else if("abc".equals(primaryPrincipal)){
            roles.add("admin");
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roles);


        return simpleAuthorizationInfo;
    }
}
  • 自定义的realm继承AuthorizingRealm就可以实现认证和授权方法,AuthorizingRealm继承自AuthenticatingRealm,AuthenticatingRealm中有doGetAuthenticationInfo方法,AuthorizingRealm中有doGetAuthorizationInfo
  • realm的认证策略:
    • FirstSuccessfulStrategy:只要有一个 Realm 验证成功即可,只返回第一个 Realm 身份验证成功的认证信息,其他的忽略;
    • AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和FirstSuccessfulStrategy 不同,将返回所有Realm身份验证成功的认证信息;(默认策略)
    • AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有Realm身份验证成功的认证信息,如果有一个失败就失败了。
  • 因为缓存:先去第一个realm寻找role,如果第一个realm有放入当前页面的权限就不继续访问下一个realm,当继续访问其他页面而第一个realm没有放入当前页面的role,则去第二个realm寻找。(不会重复访问,不配置缓存就会重复访问)
  • filterChainDefinitionMap工厂(filterChainDefinitionMap和filterChainDefinitions只能存在一个)
public class FilterChainDefinitionMapFactory {

    public LinkedHashMap<String,String> buildFilterChainDefinitionMap(){
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        
        map.put("/doLogin", "anon");
        map.put("/logout", "logout");
        map.put("/admin", "authc,roles[admin]");
        map.put("/user", "roles[user]");
        map.put("/test", "user");
        map.put("/vip", "user");
        map.put("/success", "user");
        map.put("/**", "authc");
        return map;
    }
}

rememberMe功能如果要认证才可以操作的的除了加权限还要加authc 例如:map.put("/admin", "authc,roles[admin]");否则可以通过记住我直接访问/admin

shiro权限注解

  • @RequiresAuthentication:表示当前Subject已经通过login进行了身份验证;即 Subject. isAuthenticated() 返回 true
  • @RequiresUser:表示当前 Subject 已经身份验证或者通过记住我登录的。
  • @RequiresGuest:表示当前Subject没有身份验证或通过记住我登录过,即是游客身份。
  • @RequiresRoles(value={“admin”, “user”}, logical= Logical.AND):表示当前 Subject 需要角色 admin 和user,@RequiresRoles(value={“admin”, “user”}, logical= Logical.OR):表示当前 Subject 需要角色 admin 或user中的其中一个
  • @RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR):表示当前 Subject 需要权限 user:a 或user:b。
@RequiresRoles(value = {"admin","vip"},logical = Logical.AND)
    @RequestMapping(value = {"/testAnnotation2"})
    public String testAnnotation2(){
        System.out.println("testAnnotation2222。");
        return "success";
    }

如果要在Controller层使用注解,要在springmvc.xml中添加

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<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>

如果要在service中使用,在spring-shiro中即可

httpsession和SecurityUtils.getSubject().getSession()可以互相改,可以在service调用session

session也有会话监听器用于监听会话创建、过期及停止事件onStart,onStop,onexpiration

shiro验证码

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,277评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,689评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,624评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,356评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,402评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,292评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,135评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,992评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,429评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,636评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,785评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,492评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,092评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,723评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,858评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,891评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,713评论 2 354

推荐阅读更多精彩内容