shiro简单学习

admin 2022年1月6日01:45:28安全博客评论10 views11476字阅读38分15秒阅读模式

shiro学习

慕课视频:https://www.imooc.com/video/16952

Shiro认证,授权,自定义Realm

Shiro认证

shiro简单学习
pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?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.ye1s</groupId>
<artifactId>ye1s-shrio</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>

</dependencies>


</project>

AuthenticationTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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.Before;
import org.junit.Test;

public class AuthenticationTest {
SimpleAccountRealm simpleAccountRealm=new SimpleAccountRealm();
@Before
public void addUser(){
simpleAccountRealm.addAccount("admin","password");
}
@Test
public void testAuthentication(){
//构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
defaultSecurityManager.setRealm(simpleAccountRealm);

//提交主题认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject=SecurityUtils.getSubject();

UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("admin","password");

subject.login(usernamePasswordToken);
System.out.println("isAuthenticated is:" +subject.isAuthenticated());
subject.logout();
System.out.println("isAuthenticated is:" +subject.isAuthenticated());

}
}
/*
result:
isAuthenticated is:true
isAuthenticated is:false

*/

Shrio授权

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class AuthenticationTest {
SimpleAccountRealm simpleAccountRealm=new SimpleAccountRealm();
@Before
public void addUser(){
simpleAccountRealm.addAccount("admin","password","admin","user");
}
@Test
public void testAuthentication(){
//构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
defaultSecurityManager.setRealm(simpleAccountRealm);

//提交主题认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject=SecurityUtils.getSubject();

UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("admin","password");

subject.login(usernamePasswordToken);
System.out.println("isAuthenticated is:" +subject.isAuthenticated());
subject.checkRoles("admin","user");

}

IniRealm

user.ini

1
2
3
4
[users]
admin=password,admin
[roles]
admin=user:delete,user:update

IniRealmTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class IniRealmTest {
@Test
public void testAuthentication(){
IniRealm iniRealm=new IniRealm("classpath:user.ini");
//构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
defaultSecurityManager.setRealm(iniRealm);

//提交主题认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject=SecurityUtils.getSubject();

UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("admin","password");

subject.login(usernamePasswordToken);
System.out.println("isAuthenticated is:" +subject.isAuthenticated());
subject.checkRole("admin");
subject.checkPermissions("user:delete","user:update");

}
}

JdbcRealmTest

sql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for roles_permissions
-- ----------------------------
DROP TABLE IF EXISTS `roles_permissions`;
CREATE TABLE `roles_permissions` (
`id` int(11) NOT NULL DEFAULT 0,
`role_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`permission` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of roles_permissions
-- ----------------------------
INSERT INTO `roles_permissions` VALUES (1, 'system', 'update');

-- ----------------------------
-- Table structure for user_roles
-- ----------------------------
DROP TABLE IF EXISTS `user_roles`;
CREATE TABLE `user_roles` (
`id` int(11) NOT NULL DEFAULT 0,
`username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`role_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user_roles
-- ----------------------------
INSERT INTO `user_roles` VALUES (1, 'admin', 'system');

-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password_salt` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES (1, 'admin', '666', NULL);

SET FOREIGN_KEY_CHECKS = 1;

pom.xml添加相关依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>

JdbcRealmTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class JdbcRealmTest {
DruidDataSource dataSource=new DruidDataSource();
{
dataSource.setUrl("jdbc:mysql://localhost:3306/test?useSSL=false");
dataSource.setUsername("root");
dataSource.setPassword("w0nd4rful");
}
@Test
public void testAuthentication(){
JdbcRealm jdbcRealm=new JdbcRealm();
jdbcRealm.setDataSource(dataSource);
jdbcRealm.setPermissionsLookupEnabled(true);

//构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
defaultSecurityManager.setRealm(jdbcRealm);

//提交主题认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject=SecurityUtils.getSubject();

UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("admin","666");

subject.login(usernamePasswordToken);
System.out.println("isAuthenticated is:" +subject.isAuthenticated());


}
}

自定义Realm

CustomRealm.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class CustomRealm extends AuthorizingRealm {
Map<String,String > userMap=new HashMap<String, String>(16);
{
userMap.put("admin","password");
super.setName("customRealm");
}
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String userName=(String)principalCollection.getPrimaryPrincipal();
Set<String> roles=getRolesByUserName(userName);
Set<String> permissions=getPermissionsByUserName(userName);
SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
authorizationInfo.addRoles(roles);
authorizationInfo.addStringPermissions(permissions);
return authorizationInfo;
}

private Set<String> getPermissionsByUserName(String userName) {
Set<String> sets=new HashSet<String>();
sets.add("user:delete");
sets.add("user:update");
return sets;
}


protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//1.从主体传过来的信息中获取用户名
String userName=(String)authenticationToken.getPrincipal();
//通过用户名到数据中获取数据
String password=getPasswordByUserName(userName);
if (password==null){
return null;
}
SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(userName,password,"customRealm");
return authenticationInfo;


}
//模拟数据库获取
private String getPasswordByUserName(String userName){
return userMap.get(userName);

}
private Set<String> getRolesByUserName(String UserName){
Set<String> sets= new HashSet<String>();
sets.add("admin");
sets.add("users");
return sets;
}
}

CustomRealmTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class CustomRealmTest {
@Test
public void testAuthentication(){
CustomRealm customRealm=new CustomRealm();
//构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
defaultSecurityManager.setRealm(customRealm);

//提交主题认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject=SecurityUtils.getSubject();

UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("admin","password");

subject.login(usernamePasswordToken);
System.out.println("isAuthenticated is:" +subject.isAuthenticated());
subject.checkRole("admin");
subject.checkPermissions("user:delete");

}
}

Shiro加密

CustomRealm.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class CustomRealm extends AuthorizingRealm {
Map<String,String > userMap=new HashMap<String, String>(16);
{
userMap.put("admin",getHash("password"));
super.setName("customRealm");
}
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String userName=(String)principalCollection.getPrimaryPrincipal();
Set<String> roles=getRolesByUserName(userName);
Set<String> permissions=getPermissionsByUserName(userName);
SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
authorizationInfo.addRoles(roles);
authorizationInfo.addStringPermissions(permissions);
return authorizationInfo;
}


protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//1.从主体传过来的信息中获取用户名
String userName=(String)authenticationToken.getPrincipal();
//通过用户名到数据中获取数据
String password=getPasswordByUserName(userName);
if (password==null){
return null;
}
SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(userName,password,"customRealm");
authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("ye1s"));
return authenticationInfo;


}
//模拟数据库获取
private String getPasswordByUserName(String userName){
return userMap.get(userName);

}
private Set<String> getRolesByUserName(String UserName){
Set<String> sets= new HashSet<String>();
sets.add("admin");
sets.add("users");
return sets;
}
private Set<String> getPermissionsByUserName(String userName) {
Set<String> sets=new HashSet<String>();
sets.add("user:delete");
sets.add("user:update");
return sets;
}

private String getHash(String password){
Md5Hash md5Hash=new Md5Hash("password","ye1s");
return md5Hash.toString();
}
}

CustomRealmTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class CustomRealmTest {
@Test
public void testAuthentication(){
CustomRealm customRealm=new CustomRealm();
//构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
defaultSecurityManager.setRealm(customRealm);

HashedCredentialsMatcher matcher=new HashedCredentialsMatcher();
matcher.setHashAlgorithmName("md5");
matcher.setHashIterations(1);
customRealm.setCredentialsMatcher(matcher);

//提交主题认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject=SecurityUtils.getSubject();

UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("admin","password");

subject.login(usernamePasswordToken);
System.out.println("isAuthenticated is:" +subject.isAuthenticated());
subject.checkRole("admin");
subject.checkPermissions("user:delete");

}
}

Shiro集成Spring

Shiro过滤器

shiro简单学习

Shiro 会话管理

FROM :blog.cfyqy.com | Author:cfyqy

特别标注: 本站(CN-SEC.COM)所有文章仅供技术研究,若将其信息做其他用途,由用户承担全部法律及连带责任,本站不承担任何法律及连带责任,请遵守中华人民共和国安全法.
  • 我的微信
  • 微信扫一扫
  • weinxin
  • 我的微信公众号
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年1月6日01:45:28
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                  shiro简单学习 http://cn-sec.com/archives/722623.html

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: