Shiro 六 自定义realm检查用户角色权限

整体目录:

pom文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.study</groupId>
  <artifactId>shiro</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>shiro</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>


    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.3</version>
    </dependency>

    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>1.2.2</version>
    </dependency>

  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

步骤:

1.自定义PermissionRealm继承 AuthorizingRealm 重写三个方法 getName()、doGetAuthorizationInfo()、doGetAuthenticationInfo()。

PermissionRealm类

package com.study.shiro.realm;

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 java.util.ArrayList;
import java.util.List;


public class PermissionRealm extends AuthorizingRealm {
    @Override
    public String getName() {

        return "MyRealm";
    }

    /**
     * 授权操作
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        // 当前等录用户名信息:用户凭证
        String username = (String) principals.getPrimaryPrincipal();
        // 模拟数据库查询:查询用户实现指定角色,以及用户权限
        // 角色集合
        List<String> roles = new ArrayList<String>();
        // 权限集合
        List<String> permissions = new ArrayList<String>();
        // 假设用户有role1,role2角色
        roles.add("role1");
        roles.add("role2");
        // 假设用户有user:delete,user:update权限
        permissions.add("user:delete");
        permissions.add("user:update");

        // 返回用户在数据库中的权限与角色
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);

        return info;
    }

    /**
     * 认证操作
     * @param token 表示登录时包装的usernamePasswordToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 通过用户名查找用户信息,封装成一个AuthenticationInfo对象返回,方便认证器进行对比
        // 获取token中的用户名
        String username = (String) token.getPrincipal();
        // 通过用户名查询数据库,将该用户对应的信息查询出来:账号,密码
        if(!"zhangsan".equals(username)){
            return null;
        }
        String password = "666";
        // info对象表示realm登录对比信息:参数1用户信息,参数2,:密码,参数3:当前realm的名字
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, getName());
        return simpleAuthenticationInfo;

    }
}

2.配置文件

shiro-permission-realm.ini

[main]
#声明一个realm
myRealm=com.study.shiro.realm.PermissionRealm
#指定securityManager.realms的realms实现
securityManager.realms=$myRealm

3.加载配置文件,完成测试

 @Test
    public void testPermission() throws Exception{
        // 1.创建SecurityManager工厂对象,加载配置文件,创建
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-permission-realm.ini");
        // 2.通过工厂对象,创建Securitymanage对象
        SecurityManager securityManager = factory.getInstance();
        // 3.将securitymanage绑定到当前运行环境中,让系统随时随地的都可以访问securityManager对象
        SecurityUtils.setSecurityManager(securityManager);
        // 4:创建当前登录的主体,注意;此时主体没有经过认证
        Subject subject = SecurityUtils.getSubject();
        // 5:绑定主体登录的身份、凭证,即账号密码
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan","666");
        try {
            // 6.主体登录
            subject.login(token);
            // 进行授权操作的前提:用户必须通过认证
            System.out.println(subject.isPermitted("user:delete"));
            //判断当前用户是否拥有某个角色:返回true表示拥有,false表示没有
            System.out.println(subject.hasRole("role1"));

        }catch (IncorrectCredentialsException incorrectCredentialsException){
            System.out.println("密码错误!");
        }catch (UnknownAccountException UnknownAccountException){
            System.out.println("用户名错误!");
        }
        // 7:判断是否登录成功
        System.out.println("验证是否登录1:" + subject.isAuthenticated());
        // 8:登出
        subject.logout();
        System.out.println("验证是否登录2:" + subject.isAuthenticated());
    }
发布了123 篇原创文章 · 获赞 29 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/m0_38044453/article/details/89920090