Skip to content

Commit 3b5d958

Browse files
SeunMattzhendrikse
authored andcommitted
Example Code for Apache Shiro (eugenp#2441)
* added updated example codes * updated example code StringToCharStream * deleted StringToCharStream.java locally * removed redundant file * added code for apache commons collection SetUtils * refactored example code * added example code for bytebuddy * added example code for PCollections * update pom * refactored tests for PCollections * spring security xml config * spring security xml config * remove redundant comment * example code for apache-shiro * Fixed indentation. * Fix formatting issues
1 parent 1a9c33f commit 3b5d958

7 files changed

Lines changed: 270 additions & 0 deletions

File tree

apache-shiro/.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
2+
/.idea/
3+
/target/
4+
/apache-shiro.iml

apache-shiro/README.md

Whitespace-only changes.

apache-shiro/pom.xml

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>com.baeldung</groupId>
8+
<artifactId>apache-shiro</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
<parent>
12+
<groupId>com.baeldung</groupId>
13+
<artifactId>parent-modules</artifactId>
14+
<version>1.0.0-SNAPSHOT</version>
15+
</parent>
16+
17+
<properties>
18+
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
19+
<log4j-version>1.2.17</log4j-version>
20+
<slf4j-version>1.7.25</slf4j-version>
21+
</properties>
22+
23+
<dependencies>
24+
<dependency>
25+
<groupId>org.apache.shiro</groupId>
26+
<artifactId>shiro-core</artifactId>
27+
<version>${apache-shiro-core-version}</version>
28+
</dependency>
29+
<dependency>
30+
<groupId>org.slf4j</groupId>
31+
<artifactId>jcl-over-slf4j</artifactId>
32+
<version>${slf4j-version}</version>
33+
<scope>runtime</scope>
34+
</dependency>
35+
<dependency>
36+
<groupId>org.slf4j</groupId>
37+
<artifactId>slf4j-log4j12</artifactId>
38+
<version>${slf4j-version}</version>
39+
<scope>runtime</scope>
40+
</dependency>
41+
<dependency>
42+
<groupId>log4j</groupId>
43+
<artifactId>log4j</artifactId>
44+
<version>${log4j-version}</version>
45+
<scope>runtime</scope>
46+
</dependency>
47+
48+
</dependencies>
49+
50+
<build>
51+
<plugins>
52+
<plugin>
53+
<groupId>org.apache.maven.plugins</groupId>
54+
<artifactId>maven-compiler-plugin</artifactId>
55+
<version>3.6.2</version>
56+
<configuration>
57+
<source>1.8</source>
58+
<target>1.8</target>
59+
</configuration>
60+
</plugin>
61+
</plugins>
62+
</build>
63+
64+
65+
</project>
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package com.baeldung;
2+
3+
import org.apache.shiro.SecurityUtils;
4+
import org.apache.shiro.authc.*;
5+
import org.apache.shiro.config.IniSecurityManagerFactory;
6+
import org.apache.shiro.mgt.SecurityManager;
7+
import org.apache.shiro.session.Session;
8+
import org.apache.shiro.subject.Subject;
9+
import org.apache.shiro.util.Factory;
10+
import org.slf4j.Logger;
11+
import org.slf4j.LoggerFactory;
12+
13+
public class Main {
14+
private static final transient Logger log = LoggerFactory.getLogger(Main.class);
15+
16+
public static void main(String[] args) {
17+
18+
Factory<SecurityManager> factory
19+
= new IniSecurityManagerFactory("classpath:shiro.ini");
20+
SecurityManager securityManager = factory.getInstance();
21+
22+
SecurityUtils.setSecurityManager(securityManager);
23+
Subject currentUser = SecurityUtils.getSubject();
24+
25+
if (!currentUser.isAuthenticated()) {
26+
UsernamePasswordToken token
27+
= new UsernamePasswordToken("user", "password");
28+
token.setRememberMe(true);
29+
try {
30+
currentUser.login(token);
31+
} catch (UnknownAccountException uae) {
32+
log.error("Username Not Found!", uae);
33+
} catch (IncorrectCredentialsException ice) {
34+
log.error("Invalid Credentials!", ice);
35+
} catch (LockedAccountException lae) {
36+
log.error("Your Account is Locked!", lae);
37+
} catch (AuthenticationException ae) {
38+
log.error("Unexpected Error!", ae);
39+
}
40+
}
41+
42+
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
43+
44+
if (currentUser.hasRole("admin")) {
45+
log.info("Welcome Admin");
46+
} else if(currentUser.hasRole("editor")) {
47+
log.info("Welcome, Editor!");
48+
} else if(currentUser.hasRole("author")) {
49+
log.info("Welcome, Author");
50+
} else {
51+
log.info("Welcome, Guest");
52+
}
53+
54+
if(currentUser.isPermitted("articles:compose")) {
55+
log.info("You can compose an article");
56+
} else {
57+
log.info("You are not permitted to compose an article!");
58+
}
59+
60+
if(currentUser.isPermitted("articles:save")) {
61+
log.info("You can save articles");
62+
} else {
63+
log.info("You can not save articles");
64+
}
65+
66+
if(currentUser.isPermitted("articles:publish")) {
67+
log.info("You can publish articles");
68+
} else {
69+
log.info("You can not publish articles");
70+
}
71+
72+
Session session = currentUser.getSession();
73+
session.setAttribute("key", "value");
74+
String value = (String) session.getAttribute("key");
75+
if (value.equals("value")) {
76+
log.info("Retrieved the correct value! [" + value + "]");
77+
}
78+
79+
currentUser.logout();
80+
81+
System.exit(0);
82+
}
83+
84+
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package com.baeldung;
2+
3+
import org.apache.shiro.authc.*;
4+
import org.apache.shiro.authz.AuthorizationInfo;
5+
import org.apache.shiro.authz.SimpleAuthorizationInfo;
6+
import org.apache.shiro.realm.jdbc.JdbcRealm;
7+
import org.apache.shiro.subject.PrincipalCollection;
8+
import org.slf4j.Logger;
9+
import org.slf4j.LoggerFactory;
10+
11+
import java.sql.Connection;
12+
import java.sql.SQLException;
13+
import java.util.*;
14+
15+
public class MyCustomRealm extends JdbcRealm {
16+
17+
private Map<String, String> credentials = new HashMap<>();
18+
private Map<String, Set<String>> roles = new HashMap<>();
19+
private Map<String, Set<String>> perm = new HashMap<>();
20+
21+
{
22+
credentials.put("user", "password");
23+
credentials.put("user2", "password2");
24+
credentials.put("user3", "password3");
25+
26+
roles.put("user", new HashSet<>(Arrays.asList("admin")));
27+
roles.put("user2", new HashSet<>(Arrays.asList("editor")));
28+
roles.put("user3", new HashSet<>(Arrays.asList("author")));
29+
30+
perm.put("admin", new HashSet<>(Arrays.asList("*")));
31+
perm.put("editor", new HashSet<>(Arrays.asList("articles:*")));
32+
perm.put("author",
33+
new HashSet<>(Arrays.asList("articles:compose",
34+
"articles:save")));
35+
36+
}
37+
38+
@Override
39+
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
40+
throws AuthenticationException {
41+
42+
UsernamePasswordToken uToken = (UsernamePasswordToken) token;
43+
44+
if(uToken.getUsername() == null
45+
|| uToken.getUsername().isEmpty()
46+
|| !credentials.containsKey(uToken.getUsername())
47+
) {
48+
throw new UnknownAccountException("username not found!");
49+
}
50+
51+
52+
return new SimpleAuthenticationInfo(
53+
uToken.getUsername(), credentials.get(uToken.getUsername()),
54+
getName());
55+
}
56+
57+
@Override
58+
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
59+
Set<String> roleNames = new HashSet<>();
60+
Set<String> permissions = new HashSet<>();
61+
62+
principals.forEach(p -> {
63+
try {
64+
Set<String> roles = getRoleNamesForUser(null, (String) p);
65+
roleNames.addAll(roles);
66+
permissions.addAll(getPermissions(null, null,roles));
67+
} catch (SQLException e) {
68+
e.printStackTrace();
69+
}
70+
});
71+
72+
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
73+
info.setStringPermissions(permissions);
74+
return info;
75+
}
76+
77+
@Override
78+
protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
79+
if(!roles.containsKey(username)) {
80+
throw new SQLException("username not found!");
81+
}
82+
83+
return roles.get(username);
84+
}
85+
86+
@Override
87+
protected Set<String> getPermissions(Connection conn, String username, Collection<String> roleNames) throws SQLException {
88+
for (String role : roleNames) {
89+
if (!perm.containsKey(role)) {
90+
throw new SQLException("role not found!");
91+
}
92+
}
93+
94+
Set<String> finalSet = new HashSet<>();
95+
for (String role : roleNames) {
96+
finalSet.addAll(perm.get(role));
97+
}
98+
99+
return finalSet;
100+
}
101+
102+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
log4j.rootLogger=INFO, stdout
2+
3+
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
4+
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
5+
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
6+
7+
log4j.logger.org.apache=WARN
8+
9+
log4j.logger.org.apache.shiro=INFO
10+
11+
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
12+
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
jdbcRealm = com.baeldung.MyCustomRealm
2+
3+
securityManager.realms = $jdbcRealm

0 commit comments

Comments
 (0)