shiro 基本知识测试

<!--shiro核心包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

AuhtorizationTest

package com.mozq.shiro.shiro01;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.junit.Test; public class AuhtorizationTest { @Test
public void testAuhtorization(){
//创建权限管理器,给定Realm提供认证和授权信息
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
simpleAccountRealm.addAccount("liubei", "123","砂场老板","砂场负责人"); defaultSecurityManager.setRealm(simpleAccountRealm);
SecurityUtils.setSecurityManager(defaultSecurityManager); //获取主体
Subject subject = SecurityUtils.getSubject(); //登录
subject.login(new UsernamePasswordToken("liubei", "123")); //检查权限
subject.checkRoles("砂场老板1");
// subject.checkRoles("砂场老板","砂场负责人");
}
}

AuthenticationTest

package com.mozq.shiro.shiro01;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test; public class AuthenticationTest { @Test
public void AuthenticationTest(){
//创建权限管理器,给定Realm提供认证和授权信息
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
simpleAccountRealm.addAccount("liubei", "123");
simpleAccountRealm.addAccount("sunquan", "123"); defaultSecurityManager.setRealm(simpleAccountRealm);
SecurityUtils.setSecurityManager(defaultSecurityManager); //获取主体
Subject subject = SecurityUtils.getSubject(); //登录
subject.login(new UsernamePasswordToken("liubei", "123"));
subject.login(new UsernamePasswordToken("sunquan", "123")); System.out.println("subject.isAuthenticated():" + subject.isAuthenticated());
//退出
subject.logout();
System.out.println("subject.isAuthenticated():" + subject.isAuthenticated()); }
}

IniRealmTest

package com.mozq.shiro.shiro01;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test; public class IniRealmTest { @Test
public void testIniRealm(){
//创建权限管理器,给定Realm提供认证和授权信息
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
IniRealm iniRealm = new IniRealm("classpath:user.ini");
defaultSecurityManager.setRealm(iniRealm);
SecurityUtils.setSecurityManager(defaultSecurityManager); //获取主体
Subject subject = SecurityUtils.getSubject(); //认证
subject.login(new UsernamePasswordToken("刘备", "123"));
System.out.println("subject.isAuthenticated():" + subject.isAuthenticated());
//授权
subject.checkRoles("砂场老板");
subject.checkRoles("砂场老板", "砂场负责人");
} }
# user.ini
[users]
刘备=123,砂场老板
sunquan=234,砂场负责人
[roles]
砂场老板=customer:select,order:select

JdbcRealmTest

package com.mozq.shiro.shiro01;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test; public class JdbcRealmTest { private DruidDataSource dataSource = new DruidDataSource(); @Before
public void setDataSource(){
dataSource.setUrl("jdbc:mysql:///perms");
dataSource.setUsername("root");
dataSource.setPassword("root");
} @Test
public void testJdbcRealm(){
//创建权限管理器,给定Realm提供认证和授权信息
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
JdbcRealm jdbcRealm = new JdbcRealm();
jdbcRealm.setDataSource(dataSource);
jdbcRealm.setPermissionsLookupEnabled(true);//开启权限查询,默认不会开启
//参数用户名,结果用户密码
jdbcRealm.setAuthenticationQuery("select password from user where username=?");
//参数用户名,结果角色名称
jdbcRealm.setUserRolesQuery(
"select R.role_name\n" +
"from role R\n" +
"left join user_role UR\n" +
"on R.id=UR.role_id\n" +
"left join user U\n" +
"on UR.user_id=U.id\n" +
"where U.username=?"
);
//参数角色名称,结果权限名称
jdbcRealm.setPermissionsQuery(
"select P.permission_name\n" +
"from permission P\n" +
"left join role_permission RP\n" +
"on RP.permission_id=P.id\n" +
"left join role R\n" +
"on RP.role_id=R.id\n" +
"where R.role_name=?"
);
defaultSecurityManager.setRealm(jdbcRealm); SecurityUtils.setSecurityManager(defaultSecurityManager); //获取主体
Subject subject = SecurityUtils.getSubject(); //认证
subject.login(new UsernamePasswordToken("刘备", "123"));
System.out.println("subject.isAuthenticated():" + subject.isAuthenticated());
//授权
subject.checkRoles("砂场老板");
// subject.checkRoles("砂场老板", "砂场负责人"); subject.checkPermission("customer:select");
} }

CustomRealm

package com.mozq.shiro.shiro01;

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.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set; public class CustomRealm extends AuthorizingRealm { private Map<String, String> users = new HashMap<>();
{
users.put("刘备","123");
users.put("孙权","123");
}
private String getPasswordByUsername(String username){
return users.get(username);
}
private Set<String> getRolesByUsername(String username){
Set<String> roles = new HashSet<>();
if("刘备".equals(username)){
roles.add("砂场老板");
return roles;
}
return roles;
}
private Set<String> getPermsByUsername(String username){
Set<String> perms = new HashSet<>();
if("刘备".equals(username)){
perms.add("user:add");
perms.add("user:delete");
return perms;
}
return perms;
} @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String) principals.getPrimaryPrincipal();
Set<String> roles = getRolesByUsername(username);
Set<String> perms = getPermsByUsername(username); SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addRoles(roles);
simpleAuthorizationInfo.addStringPermissions(perms);
return simpleAuthorizationInfo;
} @Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = String.valueOf(token.getPrincipal());
String password = String.valueOf((char[]) token.getCredentials());
System.out.println(username + ":" + password); String rightPassword = getPasswordByUsername(username);
if(rightPassword != null && rightPassword.equals(password)){
return new SimpleAuthenticationInfo(username, password, "customRealm");
}
return null;
} }

CustomRealmTest

package com.mozq.shiro.shiro01;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.junit.Test; import java.util.HashSet; public class CustomRealmTest { @Test
public void testCustomRealm(){
//创建权限管理器,给定Realm提供认证和授权信息
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
CustomRealm customRealm = new CustomRealm();
defaultSecurityManager.setRealm(customRealm);
SecurityUtils.setSecurityManager(defaultSecurityManager); //获取主体
Subject subject = SecurityUtils.getSubject(); //认证
subject.login(new UsernamePasswordToken("刘备", "123"));
// subject.login(new UsernamePasswordToken("孙权", "123"));
System.out.println("subject.isAuthenticated():" + subject.isAuthenticated());
//授权
subject.checkRoles("砂场老板");
// subject.checkRoles("砂场老板", "砂场负责人");
subject.checkPermissions("user:add", "user:delete");
} @Test
public void testAddAll(){
HashSet<String> roles = new HashSet<>();
roles.addAll(null);//java.lang.NullPointerException
}
}

@startuml

interface Realm
abstract class CachingRealm
abstract class AuthenticatingRealm
abstract class AuthorizingRealm
class SimpleAccountRealm
class TextConfigurationRealm
class IniRealm
class PropertiesRealm
class JdbcRealm Realm <|.. CachingRealm
CachingRealm <|-- AuthenticatingRealm
AuthenticatingRealm <|-- AuthorizingRealm
AuthorizingRealm <|-- SimpleAccountRealm
SimpleAccountRealm <|-- TextConfigurationRealm
TextConfigurationRealm <|-- IniRealm
TextConfigurationRealm <|-- PropertiesRealm AuthorizingRealm <|-- JdbcRealm @enduml

shiro 基本知识测试的更多相关文章

  1. Shiro框架 - 【shiro基础知识】

     转载:https://segmentfault.com/a/1190000013875092#articleHeader27  读完需要 63 分钟   前言 本文主要讲解的知识点有以下: 权限管理 ...

  2. Android SDK上手指南:知识测试

    Android SDK上手指南:知识测试 2014-01-22 10:00 核子可乐 译 51CTO 字号:T | T 在从零开始学习Android开发系列教程当中,我们已经了解了为Android平台 ...

  3. 【考试】java基础知识测试,看你能得多少分?

    1 前言 共有5道java基础知识的单项选择题,每道20分,共计100分.解析和答案在最后. 2 试题 2.1 如下程序运行结果是什么? class Parent { public Parent(St ...

  4. Shiro基础知识08----拦截器介绍(转)

    1 拦截器介绍 Shiro使用了与Servlet一样的Filter接口进行扩展:所以如果对Filter不熟悉可以参考<Servlet3.1规范>http://www.iteye.com/b ...

  5. Shiro基础知识03----shiro授权(编程式授权),Permission详解,授权流程(zz)

    授权,也叫访问控制,即在应用中控制谁能访问哪些资源(如访问页面/编辑数据/页面操作等).  在权限认证中,最核心的是:主体/用户(Subject).权限(Permission).角色(Role).资源 ...

  6. 安全小测试:介绍一个简单web安全知识测试的网站

    https://websecurity.firebaseapp.com/ 一次测试一共7道题,最后有答案,可以反复做,每次随机抽题

  7. 传智Java基础知识测试

    共40道选择题,每题2.5分.多选题有错则全错,全对才满分. 单选题: 1.   下列哪个声明是错误的?(B) A.  int  i=10; B.  float  f=1.1; C.  double  ...

  8. Js 正则表达式知识测试

    本文对javascript中正则表达式进行了总结汇总,将知识点和注意点都理了一下,并附上2个练习题,供大家参考学习. 正则表达式: 1.什么是RegExp?RegExp是正则表达式的缩写.RegExp ...

  9. Shiro入门这篇就够了【Shiro的基础知识、回顾URL拦截】

    前言 本文主要讲解的知识点有以下: 权限管理的基础知识 模型 粗粒度和细粒度的概念 回顾URL拦截的实现 Shiro的介绍与简单入门 一.Shiro基础知识 在学习Shiro这个框架之前,首先我们要先 ...

随机推荐

  1. LG3389 「模板」高斯消元法 高斯消元

    问题描述 LG3389 题解 高斯消元,是用来解\(n\)元一次方程组的算法,时间复杂度\(O(n^3)\) 这样就构造出了这个方程组的矩阵 目标就是把这个矩阵左边\(n \times n\)消为单位 ...

  2. windows server 2008配置多用户远程连接

    打开开始菜单->管理工具->远程桌面服务->远程桌面会话主机配置 右键限制每个用户只能进行一个会话->常规->勾掉限制每个与用户只能进行一个会话 右键远程桌面授权模式-& ...

  3. poj-3404 Bridge over a rough river Ad Hoc

    Bridge over a rough river POJ - 3404 Bridge over a rough river Time Limit: 1000MS   Memory Limit: 65 ...

  4. python Condition

    import threading # 必须要使用condition的例子 # class XiaoAi(threading.Thread):# def __init__(self, lock):# s ...

  5. 【题解】Ples [COCI2011]

    [题解]Ples [COCI2011] 依旧是没有传送门,只有提供了数据的官网. [题目描述] \(N\) 个汉子和 \(N\) 个妹纸一起参加舞会,跳舞时只能是一个汉子一个妹纸配对,现在给出每个人的 ...

  6. CentOS 配置阿里云 yum 源

    CentOS 1.备份 mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup 2.下载新的Cent ...

  7. My time is limited

    Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma - whic ...

  8. C# 方法默认访问级别 : private C# 类默认访问级别 : internal

    C# 方法默认访问级别 : private C# 类默认访问级别 : internalpublic:访问不受限制.protected:访问仅限于包含类或从包含类派生的类型.Internal:访问仅限于 ...

  9. Asp.net HttpContext 简介

    1.  Context    名词解析      Context 直接翻译就是上下文."上下文" 这个名词还是挺让人费解的,是一个非常泛化的概念.刚看到有点让人摸不着头脑,一个高端 ...

  10. C# 灵活切换开发/测试/生成环境web.config

    web.config <configuration> <connectionStrings configSource="config\Sit.db.config" ...