shiro简单使用及其集成spring

shiro简单使用及其集成spring

shiro简单的介绍

  • Apache Shiro 是 Java 的一个安全框架。
  • 使用简单。
  • Apache Shiro(轻量级,粗粒度) , Spring security(重量级,细粒度)
  • Shiro 可以帮助我们完成:认证、授权、加密、会话管理、与 Web 集成、缓存等。

shiro的模型图

在这里插入图片描述
四大核心主要功能(需要其他操作百度

  • Authentication(身份认证):身份认证 / 登录,验证用户是不是拥有相应的身份;
  • Authorization(授权):授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;
  • Session Manager(会话管理):会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;
  • Cryptography(密码学):加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;

完成步骤

相关的运行步骤

  • Subject:主体,代表了当前 “用户”,这个用户不一定是一个具体的人,即一个抽象概念;可以把 Subject 认为是一个门面;SecurityManager 才是实际的执行者;
  • SecurityManager:安全管理器;即所有与安全有关的操作都会与 SecurityManager 交互;且它管理着所有 Subject;可以看出它是 Shiro 的核心,它负责与后边介绍的其他组件进行交互
  • Realm:域,Shiro 从从 Realm 获取安全数据(如用户、角色、权限),就是说 SecurityManager 要验证用户身份,那么它需要从 Realm 获取相应的用户进行比较以确定用户身份是否合法

Holle案例

1.1坐标

  <!--使用shiro需要先导包-->
<dependencies>
    <!--shiro的核心包-->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.4.0</version>
    </dependency>
    <!--日志包-->
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <!--测试包-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.9</version>
    </dependency>
</dependencies>

1.2登录 / 退出

1、首先准备一些用户身份 / 凭据(shiro.ini)

[users]
zhang=123
wang=123

此处使用 ini 配置文件,通过 [users] 指定了两个主体:zhang/123、wang/123。

2、测试用例(com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest)

@Test
public void testHelloworld() {
    //1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager  Factory<org.apache.shiro.mgt.SecurityManager> factory =
            new IniSecurityManagerFactory("classpath:shiro.ini");
    //2、得到SecurityManager实例 并绑定给SecurityUtils   org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
    //3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");
    try {
        //4、登录,即身份验证
        subject.login(token);
    } catch (AuthenticationException e) {
        //5、身份验证失败
    }
    Assert.assertEquals(true, subject.isAuthenticated()); //断言用户已经登录
    //subject.hasRole("admin") 判断是什么级别用户
    //subject.isPermitted(相关权限) 判断是否有相关权限
    //6、退出
    subject.logout();
}

自定义Realm域

2.1准备

  • 写一个Realm,继承AuthorizingRealm
  • 提供了两个方法,一个是授权doGetAuthorizationInfo,一个是身份认证 doGetAuthenticationInfo
public class MyRealm extends AuthorizingRealm {
    //授权认证功能就写在这里面
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //从数据库中获取角色并放且放到授权对象中
        Set<String> roles = getRoles();
        authorizationInfo.setRoles(roles);
        //从数据库中获取权限并放且放到授权对象中
        Set<String> perms = getPerms();
        authorizationInfo.setStringPermissions(perms);
        return authorizationInfo;
    }
    /**
     * 假设这里获取到当前用户的角色
     */
    private Set<String> getRoles(){
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        roles.add("it");
        return roles;
    }
    /**
     * 假设这里获取到当前用户的权限
     */
    private Set<String> getPerms(){
        Set<String> perms = new HashSet<>();
        perms.add("employee:index");
        return perms;
    }
    /**
     * 记住:如果这个方法返回null,就代表是用户名错误,shiro就会抛出:UnknownAccountException
     */
    //身份认证(登录)就写在这里面
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.拿到令牌(UsernamePasswordToken)
        UsernamePasswordToken token =  (UsernamePasswordToken)authenticationToken;
        //2.拿到用户名,判断这个用户是否存在
        // 2.1 拿到传过来的用户名
        String username = token.getUsername();
        // 2.2 根据用户名从数据库中拿到密码(以后会拿用户对象)
        String password = this.getUsers(username);
        // 2.3 如果没有拿到密码(没有通过用户名拿到相应的用户->用户不存在)
        if(password==null){
            return null;
        }
        //记住:我们只在正常完成这里的功能,shiro会判断密码是否正确
        //3.返回 AuthenticationInfo这个对象
        /**
         * 咱们创建对象需要传的参数:
         * Object principal:主体(可以乱写) -> 登录成功后,你想把哪一个对象存下来
         * Object credentials:凭证(就是密码) -> 数据库中的密码
         * credentials(密码)Salt:盐值
         * String realmName : realm的名称(可以乱写)
         */
        //拿到咱们的盐值对象(ByteSource)
        ByteSource salt = ByteSource.Util.bytes("itsource");
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,salt,"myRealm");
        return authenticationInfo;
    }
    /**
     * 假设这里是根据用户名进行的查询
     *  MD5:e10adc3949ba59abbe56e057f20f883e
     *  MD5+10次:4a95737b032e98a50c056c41f2fa9ec6
     *  MD5+10次+itsource:831d092d59f6e305ebcfa77e05135eac
     */
    public String getUsers(String username){
        if("admin".equals(username)){
            return "831d092d59f6e305ebcfa77e05135eac";
        }else if("zhang".equals(username)){
            return "123";
        }
        return null;
    }
}

2.2测试

 @Test
    public void testMyRealm() throws Exception{
        //一.创建一个SecurityManager对象
        // 1.创建realm对象
        MyRealm myRealm = new MyRealm();
        // 2.创建SecurityManager对象
        DefaultSecurityManager securityManager = new DefaultSecurityManager(myRealm);
        //②.相当于把SecurityManager放到了当前上下文
        SecurityUtils.setSecurityManager(securityManager);
        //③.拿到当前用户
        Subject subject = SecurityUtils.getSubject();

        //Hashed(哈希)Credentials(认证)Matcher(匹配器)
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置哈希算法
        matcher.setHashAlgorithmName("MD5");
        //设置迭代次数
        matcher.setHashIterations(10);
        //把匹配器交给shiro
        myRealm.setCredentialsMatcher(matcher);

        System.out.println("用户是否登录:"+subject.isAuthenticated());
        //④.如果没有登录,让他登录
        if(!subject.isAuthenticated()){
            try {
                UsernamePasswordToken token = new UsernamePasswordToken("admin","123456");
                subject.login(token);
            } catch (UnknownAccountException e) {
                e.printStackTrace();
                System.out.println("用户名错误");
            } catch (IncorrectCredentialsException e) {
                e.printStackTrace();
                System.out.println("密码错误");
            } catch (AuthenticationException e) {
                e.printStackTrace();
                System.out.println("神迷错误");
            }
        }
        System.out.println("用户是否登录:"+subject.isAuthenticated());

        System.out.println("是否是admin角色:"+subject.hasRole("admin"));
        System.out.println("是否是hr角色:"+subject.hasRole("hr"));

        System.out.println("是否有employee:index权限:"+subject.isPermitted("employee:index"));
        System.out.println("是否有employee:save权限:"+subject.isPermitted("employee:save"));
        System.out.println("是否有department:index权限:"+subject.isPermitted("department:index"));
    }

对spring集成

坐标

<!-- shiro(权限框架)的支持包 -->
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-all</artifactId>
  <version>1.4.0</version>
  <type>pom</type>
</dependency>
<!-- shiro与Spring的集成包 -->
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-spring</artifactId>
  <version>1.4.0</version>
</dependency>

web.xml中配置代理过滤器

<!-- shiro的过滤器(帮我们拦截请求)-》什么事情都不做
Delegating:(); (工作、权力等)委托(给下级); 选派(某人做某事)
Proxy:代理 -> 需要通过名称(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>

2.3 准备自定义Realm

public class JpaRealm extends AuthorizingRealm {
    //授权认证功能就写在这里面
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //从数据库中获取角色并放且放到授权对象中
        Set<String> roles = getRoles();
        authorizationInfo.setRoles(roles);
        //从数据库中获取权限并放且放到授权对象中
        Set<String> perms = getPerms();
        authorizationInfo.setStringPermissions(perms);
        return authorizationInfo;
    }

    /**
     * 假设这里获取到当前用户的角色
     */
    private Set<String> getRoles(){
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        roles.add("it");
        return roles;
    }
    /**
     * 假设这里获取到当前用户的权限
     */
    private Set<String> getPerms(){
        Set<String> perms = new HashSet<>();
        perms.add("employee:index");
//        perms.add("user:*");
        return perms;
    }

    /**
     * 记住:如果这个方法返回null,就代表是用户名错误,shiro就会抛出:UnknownAccountException
     */
    //身份认证(登录)就写在这里面
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.拿到令牌(UsernamePasswordToken)
        UsernamePasswordToken token =  (UsernamePasswordToken)authenticationToken;
        //2.拿到用户名,判断这个用户是否存在
        // 2.1 拿到传过来的用户名
        String username = token.getUsername();
        // 2.2 根据用户名从数据库中拿到密码(以后会拿用户对象)
        String password = this.getUsers(username);
        // 2.3 如果没有拿到密码(没有通过用户名拿到相应的用户->用户不存在)
        if(password==null){
            return null;
        }

        //记住:我们只在正常完成这里的功能,shiro会判断密码是否正确
        //3.返回 AuthenticationInfo这个对象
        /**
         * 咱们创建对象需要传的参数:
         * Object principal:主体(可以乱写) -> 登录成功后,你想把哪一个对象存下来
         * Object credentials:凭证(就是密码) -> 数据库中的密码
         * credentials(密码)Salt:盐值
         * String realmName : realm的名称(可以乱写)
         */
        //拿到咱们的盐值对象(ByteSource)
        ByteSource salt = ByteSource.Util.bytes("itsource");
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,salt,"myRealm");
        return authenticationInfo;
    }

    /**
     * 假设这里是根据用户名进行的查询
     *  MD5:e10adc3949ba59abbe56e057f20f883e
     *  MD5+10次:4a95737b032e98a50c056c41f2fa9ec6
     *  MD5+10次+itsource:831d092d59f6e305ebcfa77e05135eac
     */
    public String getUsers(String username){
        if("admin".equals(username)){
            return "831d092d59f6e305ebcfa77e05135eac";
        }else if("zhang".equals(username)){
            return "123";
        }
        return null;
    }
}

4.4 准备工厂返回权限

  • 返回的Map值是有顺序的
  • 修改后要重启(热启动无效)
/**
 * 用于返回下面的这些值(这里的值是有顺序的:LinkedHashMap)
 *   <value>
         /login = anon
         /s/permission.jsp = perms[user:index]
         /** = authc
    </value>
    这里修改后要重新启动tomcat
 */
public class ShiroFilterMapFactory {

    public Map<String,String> createMap(){
        Map<String,String> map = new LinkedHashMap<>();
        //anon:需要放行的路径
        map.put("/login","anon");
        //perms:权限拦截
        map.put("/s/permission.jsp","perms[employee:index]");
        //authc:拦截
        map.put("/**","authc");
        return map;
    }
}

4.5 applicationContext-shiro.xml的配置

  • 先在 applicationContext.xml 中引入它 <importresource=“classpath: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-3.0.xsd">


    <!--
        Shiro的核心对象(权限管理器)
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(jpaRealm)
    -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="jpaRealm"/>
    </bean>

    <!--
        JpaRealm jpaRealm = new JpaRealm();
        配置咱们的自定义realm
     -->
    <bean id="jpaRealm" class="cn.itsource.aisell.web.shiro.JpaRealm">
        <!--Realm的名称-->
        <property name="name" value="jpaRealm"/>
        <property name="credentialsMatcher">
            <!-- 配置哈希密码匹配器 -->
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!--加密方式:MD5-->
                <property name="hashAlgorithmName" value="MD5"/>
                <!--迭代次数-->
                <property name="hashIterations" value="10" />
            </bean>
        </property>
    </bean>

    <!-- 这三个配置好,可以支持注解权限 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    <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>



    <!--
        shiro真正的过滤器(功能就是它完成的)
            这个bean的名称必需和web.xml里的的代理过滤器名字相同
     -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!--必需要用到权限管理器-->
        <property name="securityManager" ref="securityManager"/>
        <!--如果你没有登录,你会进入这个页面-->
        <property name="loginUrl" value="/s/login.jsp"/>
        <!--登录成功后,进入的页面(一般没什么用)-->
        <property name="successUrl" value="/s/main.jsp"/>
        <!--如果你没有权限,你会进入这个页面-->
        <property name="unauthorizedUrl" value="/s/unauthorized.jsp"/>
        <!-- 过滤描述
            anon:不需要登录也可以访问
            authc:登录与权限的拦截
            perms:如果你有user:index的权限,你就可以访问:/s/permission.jsp
        -->
        <!--
        <property name="filterChainDefinitions">
            <value>
                /login = anon
                /s/permission.jsp = perms[user:index]
                /** = authc
            </value>
        </property>
        -->
        <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap" />
    </bean>

    <!--
        以前在四个创建Bean的方法中讲过
        ShiroFilterMapFactory shiroFilterMapFactory = new shiroFilterMapFactory();
        Map filterChainDefinitionMap=shiroFilterMapFactory.createMap();
    -->
    <!--拿到shiroFilterMapFactory里面的createMap方法的值 -->
    <bean id="filterChainDefinitionMap" factory-bean="shiroFilterMapFactory" factory-method="createMap" />
    <!--配置返回shiro权限拦截的bean-->
    <bean id="shiroFilterMapFactory" class="cn.itsource.aisell.web.shiro.ShiroFilterMapFactory"/>
</beans>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值