当前位置:网站首页>Shrio study notes (II)
Shrio study notes (II)
2022-04-22 08:06:00 【I forgot my nickname】
stay Shrio There are two defaults in Realm.
One 、IniRealm
stay resources New directory user.ini , among ,users Is the user name and password written , For certification . Authorization is roles Permissions set under , Don't write .
In the case of : One admin user , The password is 123456, The role is admin, You have permission to delete 、 modify .
[users]
admin=123456,admin
[roles]
admin=user:delete,user:update
The test code is as follows
private DefaultSecurityManager defaultSecurityManager;
@Test
public void testAuthentication() {
//1. structure SecurityManager Environmental Science
defaultSecurityManager = new DefaultSecurityManager();
IniRealm iniRealm = new IniRealm("classpath:user.ini");
defaultSecurityManager.setRealm(iniRealm);
//2. The authentication request is submitted by the subject
SecurityUtils.setSecurityManager(defaultSecurityManager); // Set up manager Environmental Science
Subject subject = SecurityUtils.getSubject(); // Get the subject
// Default constructor , Build the test data to verify
UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456");
subject.login(token); // Submit authentication login
//3.1 Login authentication
System.out.println(" Certification results :" + subject.isAuthenticated());
//System.out.println(" to grant authorization :");
subject.checkRole("admin"); // Verify the role
//subject.checkPermission("user:delete");
//subject.checkPermission("user:insert"); // There is no such authority
//3.2 sign out
subject.logout();
System.out.println(" after , Certification results :" + subject.isAuthenticated());
}
Authentication success 、 Authorized success
Authentication failed ( Write a wrong account number )
privilege grant failed ( Write a role or permission that the user does not have )
Permission exception

Two 、JdbcRealm
Code similarity IniRealm.
Add two dependent packages
<!-- data source -->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<!--mysql-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
ad locum , We don't have to write sql Inquire about , Because JdbcRealm It's sealed , stay JdbcRealm You can take a look at its related in the code Sql, So control , Tables can be created , To store authorization related information

The data table is as follows
User table : Save user name and password
CREATE TABLE `users` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
Role table : Save user name and role
CREATE TABLE `user_roles` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`role_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
Permissions on the table : Save roles and permissions
CREATE TABLE `roles_permissions` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`role_name` varchar(255) DEFAULT NULL,
`permission` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
The test code is as follows
private DefaultSecurityManager defaultSecurityManager;
DruidDataSource dataSource = new DruidDataSource();
{
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("123456");
}
@Test
public void testAuthentication(){
//1. structure SecurityManager Environmental Science
defaultSecurityManager = new DefaultSecurityManager();
JdbcRealm jdbcRealm = new JdbcRealm();
jdbcRealm.setDataSource(dataSource); // Set data source
jdbcRealm.setPermissionsLookupEnabled(true); // Default false, Open permission query
defaultSecurityManager.setRealm(jdbcRealm);
//2. The authentication request is submitted by the subject
SecurityUtils.setSecurityManager(defaultSecurityManager); // Set up manager Environmental Science
Subject subject = SecurityUtils.getSubject(); // Get the subject
// Default constructor , Build the test data to verify
UsernamePasswordToken token = new UsernamePasswordToken("admin","123456");
subject.login(token ); // Submit authentication login
//3.1 Login authentication
subject.checkRole("admin");
System.out.println(" Certification results :"+subject.isAuthenticated());
subject.checkRole("admin");
subject.checkPermission("user:select");
//3.2 sign out
subject.logout();
System.out.println(" after , Certification results :"+subject.isAuthenticated());
}
test , Like IniRealm.
If you don't want to use the default database , You can also use your own database .
The database settings are the same , Just write it yourself SQL
DruidDataSource dataSource = new DruidDataSource();
{
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("123456");
}
private final String USER_SQL = "select password from test_user where username=?";
private final String ROLE_SQL = "select role_name from test_user_roles where username=?";
Create good jdbcRealm after , Use your own database , Just put the relevant SQL write in .
jdbcRealm.setAuthenticationQuery(USER_SQL); // authentication
jdbcRealm.setUserRolesQuery(ROLE_SQL); // Verify the role
jdbcRealm.setPermissionsQuery(...);;// Verify your permissions
3、 ... and 、 Customize Realm
Through the top JDBCRealm, You can know , Inherit AuthorizingRealm that will do , Rewrite its two abstract methods . When use , to DefaultSecurityManager Set up Realm Use custom .
/**
* Customize dbcRealm
*/
public class CustomRealm extends AuthorizingRealm {
{
super.setName("customName");
}
/**
* to grant authorization
The main body * @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
// Get the user name from the cache or database
String username = (String) principalCollection.getPrimaryPrincipal();
// Get the role from the database or cache through the user name
Set<String> roles = getRolesByUsername(username);
// Get permissions from the database or cache
Set<String> permissions = getPermissionsByUsername(username);
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo() ;
authorizationInfo.setRoles(roles); // Set up characters
authorizationInfo.setStringPermissions(permissions); // Set the permissions
return authorizationInfo;
}
/**
* authentication
* @param authenticationToken : Authentication information sent by the principal
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//1. From cache or database ( Authentication body ) Get user name
String username = (String) authenticationToken.getPrincipal();
//2. Get the user name and verify it in the database
String password = getPasswordByUsername(username);
if(password == null){
return null;
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("admin",password,"customName");
return authenticationInfo;
}
}
When using :
@Test
public void testAuthentication() {
//1. structure SecurityManager Environmental Science
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
CustomRealm customRealm = new CustomRealm();
defaultSecurityManager.setRealm(customRealm);
... ...
}
The verification results can follow the example 1.
Insert a code chip here
Four 、Shiro encryption
In the test class , Add encryption , Then set the encryption to customRealm in
// Set up Shiro encryption
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
matcher.setHashAlgorithmName("md5");// Set encryption mode
matcher.setHashIterations(1); // Set the number of encryption
customRealm.setCredentialsMatcher(matcher);
in addition , To be more secure , It can be used ‘ Add salt ’, When the user password is stored, it is stored with salt , So it just needs to be modified customRealm.java, Add salt
// Add salt , In order not to be cracked ,“admin” Is custom
authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("admin"));
Combine the above two encryption , Can be interpreted as :
Md5Hash md5Hash = new Md5Hash(‘ password ’,"admin");
GOOD LUCK!!!
版权声明
本文为[I forgot my nickname]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220628165863.html
边栏推荐
- MySQL queries the attributes of all fields in the database
- web自动化:4.2selenium如何实现iframe窗口的切换(3种方法)
- 配置表及页面信息 自动生成CURD操作页面
- doc、pdf转换为swf文件预览
- SuperSocket在.Net5中使用——WebSocket Server篇
- Echars dynamically realizes the scatter diagram and customizes the information prompt box
- Redis listens for key expiration events
- Under the window environment, VirtualBox loads the virtual machine created in the mobile hard disk
- Seven steps of PLC project commissioning
- 世平信息数据安全合规检测实践论文入选中文核心期刊
猜你喜欢

八阿哥纪事【四】

专注数据安全,世平信息上榜中国网络安全行业全景图六大细分领域

Autoware demo test

昆仑通态 │ G系列屏如何与西门子300国产MPI适配器连接

职工信息的综合运算

行业应用 |从实践中读懂银行的敏感数据安全防护思路

Raspberry Pie: adafruit's I2C ssd1306 OLED driver

学生成绩管理

China network security industry panorama of ccsip 2021 listed by Shiping information

Web problem location: F12, how to find the corresponding interface
随机推荐
软件测试开发基础
昆仑通态 │ G系列屏如何与西门子300国产MPI适配器连接
Postman interface automation-3-tests assertion 3: get dynamic parameters and set environment variables (Interface Association)
unittest框架
Echars dynamically realizes the scatter diagram and customizes the information prompt box
mysql安装采坑
Raspberry Pie: access BitLocker to go encrypted disk
web问题定位:F12,如何找到对应接口
Redis listens for key expiration events
web自动化:5.1selenium鼠标操作-单击、双击、右击、悬停、拖拽
Web automation: how to realize browser window scrolling in 8.3 selenium
实验5 组件及事件处理
China network security industry panorama of ccsip 2021 listed by Shiping information
Seven steps of PLC project commissioning
专注数据安全,世平信息上榜中国网络安全行业全景图六大细分领域
技术解惑 | PLC是如何执行中断?又是如何去应用的?
为什么我那么看重文档命名?
Web automation: 5.2 selenium mouse operation principle: actionchains delay call
How to connect Kunlun on state │ G series screen with Siemens 300 domestic MPI adapter
VMware set fixed IP address -- bridge mode