轻量级的权限框架shiro

一.认识shiro

  • 轻量级的权限框架
  • shiro(轻量级,粗粒度) , Spring security(细粒度)
  • RBAC:权限(登录,授权) 用户(n)-角色(n)-权限(n)(资源)

1.1 shiro的四大基石

  1. 身份认证(登录) Authentication
  2. 授权(权限) Authorization
  3. 密码学 Cryptography
  4. 会话管理 Session Management

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uw3WalEy-1574948938978)(2D0B1C86E6744794A391A8604DF8282F)]

1.2 重要的对象

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m5CuUtbp-1574948938980)(992CEC5F32AD40448EC7F03EB23A22CF)]

二.Hello案例

建一个普通的maven项目

2.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>

2.2 ini文件

文件中有咱们的用户角色权限

# ini文件里面放的就是咱们的用户,角色,权限,资源

# -----------------------------------------------------------------------------
#  users:用户
#   root:用户名  123456:密码  admin:角色
# -----------------------------------------------------------------------------
[users]
root = 123456, admin
guest = guest, it

# -----------------------------------------------------------------------------
# roles:角色
#   admin = * :admin这个用户拥有所有权限
#   it = employee:* :it这个角色拥有员工的所有权限
#   hr = employee:save :hr这个角色拥有员工添加权限
# -----------------------------------------------------------------------------
[roles]
admin = *
it = employee:*
hr = employee:save

2.3 功能测试

主要测试登录,权限认证

@Test
public void testHello() throws Exception{
    //①.拿到权限管理对象
    /**
     * 读取了shiro.ini的文件(隐藏了realm) -> 隐藏了iniRealm
     * SecurityManager:权限管理器,shiro的所有功能都放在里面
     */
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    //②.相当于把SecurityManager放到了当前上下文
    /**
     * 可以让我们在当前系统的任何位置都可以拿到SecurityManager对象
     */
    SecurityUtils.setSecurityManager(securityManager);
    //③.拿到当前用户(没有登录就是游客)
    Subject currentUser = SecurityUtils.getSubject();
    System.out.println("用户是否登录:"+currentUser.isAuthenticated());

    //④.如果没有登录,让他进行登录
    if(!currentUser.isAuthenticated()){
        //ctrl+alt+t :包含代码
        try {
            //4.1 准备令牌(对象) 用户名密码令牌
            UsernamePasswordToken token = new UsernamePasswordToken("guest","guest");
            //4.2 进行登录功能
            currentUser.login(token);
        } catch (UnknownAccountException e) {
            //Unknown(未知)Account(账号)Exception:用户名不存在
            e.printStackTrace();
            System.out.println("哥,你是傻子嘛?");
        }catch (IncorrectCredentialsException e){
            //Incorrect(不正确)Credentials(凭证)Exception:密码错误
            e.printStackTrace();
            System.out.println("哥,密码错误了?");
        }catch (AuthenticationException e){
            //AuthenticationException:登录中最大的那个异常
            e.printStackTrace();
            System.out.println("发生了一个神秘的错误!!!");
        }
    }
    System.out.println("用户是否登录:"+currentUser.isAuthenticated());

    System.out.println("是否是管理员角色:"+currentUser.hasRole("admin"));
    System.out.println("是否是IT角色:"+currentUser.hasRole("it"));

    System.out.println("是否可以操作employee:save权限:"+currentUser.isPermitted("employee:save"));
    System.out.println("是否可以操作employee:index权限:"+currentUser.isPermitted("employee:index"));
    System.out.println("是否可以操作department:index权限:"+currentUser.isPermitted("department:index"));

    //⑤.还可以登出(注销)
    currentUser.logout();
    System.out.println("用户是否登录:"+currentUser.isAuthenticated());
}

三.自定义Realm

3.1 准备自定义Realm

  • 写一个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;
    }
}

3.2 测试自定义Realm

 @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

需要有Spring的环境 ssj/项目

4.1 导包

<!-- 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>

4.2 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>

4.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 中引入它
    <import resource="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>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值