一、SimpleAccountRealm

public class AuthenticationTest {
    
    SimpleAccountRealm sar=new SimpleAccountRealm();
    
    @Before
    public void addUser() {
        sar.addAccount("mark", "123456","admin","user");
    }
    
    @Test
    public void testAuthentication() {
        //1.构建seruritymanager环境
        DefaultSecurityManager dsm=new DefaultSecurityManager();
        dsm.setRealm(sar);
        
        //2.主题提交认证请求
        SecurityUtils.setSecurityManager(dsm);
        Subject subject=SecurityUtils.getSubject();
        
        UsernamePasswordToken token=new UsernamePasswordToken("mark","123456");
        subject.login(token);
        
        System.out.println("isAuthenticated:"+subject.isAuthenticated());
        
        subject.checkRoles("admin","user");

}

 

二.IniRealm

public class IniRealmTest {
 
    
    @Test
    public void testIniRealm() {
        IniRealm realm=new IniRealm("classpath:user.ini");
        DefaultSecurityManager defaultSerurityManager=new DefaultSecurityManager();
        defaultSerurityManager.setRealm(realm);
        
        SecurityUtils.setSecurityManager(defaultSerurityManager);
        Subject subject = SecurityUtils.getSubject();
        
        UsernamePasswordToken upt=new UsernamePasswordToken("mark","123456");
        
        subject.login(upt);
        
        System.out.println("isAuthentication:"+subject.isAuthenticated());
        
        subject.checkRole("admin");
        
        subject.checkPermission("user:update");
        
    }
}

三、JDBCRealm

public class JDBCRealmTest {
    
    DruidDataSource dataSource=new DruidDataSource();
    {
        dataSource.setUrl("jdbc:mysql://localhost:3306/xxxx");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
    }
    
    @Test
    public void testJDBCRealm() {
        JdbcRealm realm=new JdbcRealm();
        realm.setDataSource(dataSource);
        realm.setPermissionsLookupEnabled(true);
        //如果不用自己的sql,数据库表名必须与shiro默认的查询语句中的一致,一般情况下都是使用自定义的sql,如下:
        String sql="select password from test_user where user_name=?";
        realm.setAuthenticationQuery(sql);
        String roleSql="select role_name from test_user_roles where user_name=?";
        realm.setUserRolesQuery(roleSql);
        String permissionSql="select permission from test_roles_permissions where role_name=?";
        realm.setPermissionsQuery(permissionSql);
        
        DefaultSecurityManager dsm=new DefaultSecurityManager();
        dsm.setRealm(realm);
        
        SecurityUtils.setSecurityManager(dsm);
        Subject subject = SecurityUtils.getSubject();
        
        UsernamePasswordToken token=new UsernamePasswordToken("xm","123");
        subject.login(token);
        
        System.out.println("isAuthencation:"+subject.isAuthenticated());
        
        subject.checkRole("admin");
        subject.checkRoles("admin","user");
        subject.checkPermission("user:delete");
    }
 
}

四、自定义Realm

public class customRealmTest {
    
    @Test
    public void testCustomRealm() {
        CustomRealm realm=new CustomRealm();
        
        DefaultSecurityManager sdm=new DefaultSecurityManager();
        sdm.setRealm(realm);
        
        HashedCredentialsMatcher hcm=new HashedCredentialsMatcher();
        hcm.setHashAlgorithmName("md5");
        hcm.setHashIterations(1);
        
        realm.setCredentialsMatcher(hcm);
        
        SecurityUtils.setSecurityManager(sdm);
        Subject subject = SecurityUtils.getSubject();
        
        UsernamePasswordToken token=new UsernamePasswordToken("mark","123456");
        subject.login(token);
        System.out.println("isAuthencation:"+subject.isAuthenticated());
        
        subject.checkRole("admin");
        subject.checkRoles("admin","user");
        
        subject.checkPermission("user:delete");
    }
 

}

 
public class CustomRealm extends AuthorizingRealm {
    
    Map<String, String> userMap=new HashMap<>();
    
    {
        //模拟数据库中查询出的数据
        userMap.put("mark", "73bea81c6c06bacab41a995495239545");
        super.setName("customReal");
    }
 
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
 
        String userName = (String) principals.getPrimaryPrincipal();
        //通过用户名获取数据库或缓存中的角色
        Set<String> roles=getRolesByUserName(userName);
        Set<String> premissions=getpremissionsByUserName(userName);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setStringPermissions(premissions);
        info.setRoles(roles);
        return info;
    }
 
    private Set<String> getpremissionsByUserName(String userName) {
        Set<String> permission=new HashSet<>();
        permission.add("user:delete");
        return permission;
    }
 
    private Set<String> getRolesByUserName(String userName) {
        Set<String> roles=new HashSet<>();
        roles.add("admin");
        roles.add("user");
        return roles;
    }
 
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1.通过主体传过来的信息获取用户名
        String userName=(String) token.getPrincipal();
        //2.通过用户名去数据库获取凭证
        String password=getPassowrdByUserName(userName);
        if(password==null) {
            return null;
        }
        
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo("mark",password,"customReal");
        //加盐--如果数据库中密码是加盐密文,此处应该设置盐的值
        info.setCredentialsSalt(ByteSource.Util.bytes("mark"));
        return info;
    }
 
    private String getPassowrdByUserName(String userName) {
        //实际中去查数据库   这个方便演示
        return userMap.get(userName);
    }
 
    public static void main(String[] args) {
        System.out.println((int)(1+Math.random()*10));
//        Md5Hash hsh=new Md5Hash("123456");  //md5加密
        Md5Hash hsh=new Md5Hash("123456","mark");  //MD5加密并加盐    更安全
        System.out.println(hsh);
    }
    
 

}

shiro权限认证Realm的四大用法的更多相关文章

  1. Shiro入门之一 -------- Shiro权限认证与授权

    一  将Shirojar包导入web项目 二 在web.xml中配置shiro代理过滤器 注意: 该过滤器需要配置在struts2过滤器之前 <!-- 配置Shiro的代理过滤器 -->  ...

  2. 学习Spring Boot:(十三)配置 Shiro 权限认证

    经过前面学习 Apache Shiro ,现在结合 Spring Boot 使用在项目里,进行相关配置. 正文 添加依赖 在 pom.xml 文件中添加 shiro-spring 的依赖: <d ...

  3. shiro权限认证与授权

    什么是shiro? Shiro是apache旗下一个开源框架,它将软件系统的安全认证相关的功能抽取出来,实现用户身份认证,权限授权.加密.会话管理等功能,组成了一个通用的安全认证框架. 为什么要用sh ...

  4. springboot+mybatis+shiro——登录认证和权限控制

    转载:https://z77z.oschina.io/ 一.引入依赖 shiro-all包含shiro所有的包.shiro-core是核心包.shiro-web是与web整合.shiro-spring ...

  5. spring-boot整合shiro作权限认证

    spring-shiro属于轻量级权限框架,即使spring-security更新换代,市场上大多数企业还是选择shiro 废话不多说  引入pom文件 <!--shiro集成spring--& ...

  6. 十、 Spring Boot Shiro 权限管理

    使用Shiro之前用在spring MVC中,是通过XML文件进行配置. 将Shiro应用到Spring Boot中,本地已经完成了SpringBoot使用Shiro的实例,将配置方法共享一下. 先简 ...

  7. Spring Boot Shiro 权限管理 【转】

    http://blog.csdn.net/catoop/article/details/50520958 主要用于备忘 本来是打算接着写关于数据库方面,集成MyBatis的,刚好赶上朋友问到Shiro ...

  8. 4.SSM配置shiro权限管理

    作者QQ:1095737364    QQ群:123300273     欢迎加入! 1.搭建SSM项目: http://www.cnblogs.com/yysbolg/p/6909021.html ...

  9. Spring Boot Shiro 权限管理

    Spring Boot Shiro 权限管理 标签: springshiro 2016-01-14 23:44 94587人阅读 评论(60) 收藏 举报 .embody{ padding:10px ...

随机推荐

  1. 八使用Shell函数

    在Shell脚本中,将一些需要重复使用的操作,定义为公共的语句块,即可称为函数 使用函数的好处? 使脚本代码更简洁,增强易读性 提高Shell脚本的执行效率 函数定义方法 基本格式1 function ...

  2. 9. Palindrome Number QuestionEditorial Solution

    Determine whether an integer is a palindrome. Do this without extra space. click to show spoilers. S ...

  3. socket实现文件上传(客户端向服务器端上传照片示例)

    本示例在对socket有了基本了解之后,可以实现基本的文件上传.首先先介绍一下目录结构,server_data文件夹是用来存放客户端上传的文件,client_data是模拟客户端文件夹(目的是为了测试 ...

  4. YUM源部署和使用

    1.前言 为什么需要内部yum源呢,有可能是业务内部的服务器对外是不通了,居于一些安全方面的考虑.内部yum源又有什么好处呢,第一,速度快:第二,内网可控,外网有问题也不影响内网包的下载和安装等. 2 ...

  5. Linux服务器上搭建codis集群之——安装前环境准备

    codis是redis的分布式集群模式,由豌豆荚开源,本文简单记录一下它的集群搭建方法. 首先介绍一下我的实验环境.三台配置相同的虚拟机, [root@test ~]# ip a|grep -w &q ...

  6. Apache-Tomcat-Ajp漏洞(CVE-2020-1938)漏洞复现

    前言 Apache Tomcat会开启AJP连接器,方便与其他Web服务器通过AJP协议进行交互.由于Tomcat本身也内含了HTTP服务器,因此也可以视作单独的Web服务器.此漏洞为文件包含漏洞,攻 ...

  7. k8s系列---yaml文件格式

    https://www.bejson.com/validators/yaml_editor/ yaml文件大致格式解析,通过上面这个解析网站,可以看到yaml文件解析的格式长什么样,如果知道字典和列表 ...

  8. springboot 基于Tomcate的自启动流程

    Springboot 内置了Tomcat的容器,我们今天来说一下Springboot的自启动流程. 一.Spring通过注解导入Bean大体可分为四种方式,我们主要来说以下Import的两种实现方法: ...

  9. linux中的正则表达式知识梳理

    1. 正则表达式 1.1 正则表达式使用 正则表达式是开发者为了处理大量的字符串和文本而定义的一套规则和方法,使用正则表达式可以提高效率,快速获取想要的内容. 正则表达式常用于linux三剑客grep ...

  10. Mybatis随记(一)update动态SQL

    <update id="updateUser"> UPDATE user_info SET <if test="gzhOpenId != null an ...