一、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. 如何优雅地使用containerd?这里有一份必读的技巧攻略

    前 言 Docker是我们常用的容器runtime,友好的CLI,丰富的社区资料,外加研发运维人员多年的经验积累,使用Docker几乎是没有任何门槛的事.而k3s为了降低资源消耗,将默认的runtim ...

  2. C语言宏的神奇写法:语句块作为参数,算半个函数式编程?

    我想要写几个循环做测试代码,每次都写 `for(size_t i = 0; i < n; i++)` 很烦人,然后就灵机一动,能不能用宏实现,然后就写出了: #define repeat(n, ...

  3. LeetCode 218. The Skyline Problem 天际线问题(C++/Java)

    题目: A city's skyline is the outer contour of the silhouette formed by all the buildings in that city ...

  4. 登录sql sever

    MSSQLSEVER是默认的实例名,一台计算机可以安装多个实例名,相当于多个服务器,互不影响. workbench是MySQL 服务器的一个图形化管理客户端,功能类似于MySQL Command 安装 ...

  5. learn about sqlserver partitition and partition table --- add or remove table partitions addition more

    Yes . In the previous. chapter , we see how to generate "partition function" "parttit ...

  6. 9.3.2 map端连接-CompositeInputFormat连接类

    1.1.1         map端连接-CompositeInputFormat连接类 (1)使用CompositeInputFormat连接类需要满足三个条件: 1)两个数据集都是大的数据集,不能 ...

  7. 手机控制电脑第二弹之HIPC

    点击蓝字关注我们 是否很多时候电脑不在身边,又急需要使用,比如正好要用一个文件,又没有放在我们的网盘中,想用手机查看电脑状态,但是很多太复杂的方式不会使用,需要简单的方式,今天方成分享给你 前言 故事 ...

  8. .NET Core之单元测试(二):使用内存数据库处理单元测试中的数据库依赖

    目录 定义一个待测试API 测试用例 为减少篇幅,隐藏了SampleEntity和SqliteDbContext 定义一个待测试API 如下,我们定义了一个名为Sample的API,其中有一个外部依赖 ...

  9. 14-Response

    今日知识 1. response 2. ServletContext对象 response * 功能:设置响应消息 1. 设置响应行 1. 格式:HTTP/1.1 200 ok 2. 设置状态码:se ...

  10. qt creator源码全方面分析(2-5)

    目录 Creating Wizards in Code 介绍 相关类 IWizardFactory的设置器和获取器 Creating Wizards in Code 介绍 如果基于模板的自定义向导提供 ...