example code for apache-shiro
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.apache.shiro.SecurityUtils;
|
||||
import org.apache.shiro.authc.*;
|
||||
import org.apache.shiro.config.IniSecurityManagerFactory;
|
||||
import org.apache.shiro.mgt.SecurityManager;
|
||||
import org.apache.shiro.session.Session;
|
||||
import org.apache.shiro.subject.Subject;
|
||||
import org.apache.shiro.util.Factory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Main {
|
||||
|
||||
private static final transient Logger log = LoggerFactory.getLogger(Main.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Factory<SecurityManager> factory
|
||||
= new IniSecurityManagerFactory("classpath:shiro.ini");
|
||||
SecurityManager securityManager = factory.getInstance();
|
||||
|
||||
SecurityUtils.setSecurityManager(securityManager);
|
||||
Subject currentUser = SecurityUtils.getSubject();
|
||||
|
||||
if (!currentUser.isAuthenticated()) {
|
||||
UsernamePasswordToken token
|
||||
= new UsernamePasswordToken("user", "password");
|
||||
token.setRememberMe(true);
|
||||
try {
|
||||
currentUser.login(token);
|
||||
} catch (UnknownAccountException uae) {
|
||||
log.error("Username Not Found!", uae);
|
||||
} catch (IncorrectCredentialsException ice) {
|
||||
log.error("Invalid Credentials!", ice);
|
||||
} catch (LockedAccountException lae) {
|
||||
log.error("Your Account is Locked!", lae);
|
||||
} catch (AuthenticationException ae) {
|
||||
log.error("Unexpected Error!", ae);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
|
||||
|
||||
if (currentUser.hasRole("admin")) {
|
||||
log.info("Welcome Admin");
|
||||
} else if(currentUser.hasRole("editor")) {
|
||||
log.info("Welcome, Editor!");
|
||||
} else if(currentUser.hasRole("author")) {
|
||||
log.info("Welcome, Author");
|
||||
} else {
|
||||
log.info("Welcome, Guest");
|
||||
}
|
||||
|
||||
if(currentUser.isPermitted("articles:compose")) {
|
||||
log.info("You can compose an article");
|
||||
} else {
|
||||
log.info("You are not permitted to compose an article!");
|
||||
}
|
||||
|
||||
if(currentUser.isPermitted("articles:save")) {
|
||||
log.info("You can save articles");
|
||||
} else {
|
||||
log.info("You can not save articles");
|
||||
}
|
||||
|
||||
if(currentUser.isPermitted("articles:publish")) {
|
||||
log.info("You can publish articles");
|
||||
} else {
|
||||
log.info("You can not publish articles");
|
||||
}
|
||||
|
||||
Session session = currentUser.getSession();
|
||||
session.setAttribute("key", "value");
|
||||
String value = (String) session.getAttribute("key");
|
||||
if (value.equals("value")) {
|
||||
log.info("Retrieved the correct value! [" + value + "]");
|
||||
}
|
||||
|
||||
currentUser.logout();
|
||||
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.apache.shiro.authc.*;
|
||||
import org.apache.shiro.authz.AuthorizationInfo;
|
||||
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
||||
import org.apache.shiro.realm.jdbc.JdbcRealm;
|
||||
import org.apache.shiro.subject.PrincipalCollection;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
|
||||
public class MyCustomRealm extends JdbcRealm {
|
||||
|
||||
private Map<String, String> credentials = new HashMap<>();
|
||||
private Map<String, Set<String>> roles = new HashMap<>();
|
||||
private Map<String, Set<String>> perm = new HashMap<>();
|
||||
|
||||
{
|
||||
credentials.put("user", "password");
|
||||
credentials.put("user2", "password2");
|
||||
credentials.put("user3", "password3");
|
||||
|
||||
roles.put("user", new HashSet<>(Arrays.asList("admin")));
|
||||
roles.put("user2", new HashSet<>(Arrays.asList("editor")));
|
||||
roles.put("user3", new HashSet<>(Arrays.asList("author")));
|
||||
|
||||
perm.put("admin", new HashSet<>(Arrays.asList("*")));
|
||||
perm.put("editor", new HashSet<>(Arrays.asList("articles:*")));
|
||||
perm.put("author",
|
||||
new HashSet<>(Arrays.asList("articles:compose",
|
||||
"articles:save")));
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
|
||||
throws AuthenticationException {
|
||||
|
||||
UsernamePasswordToken uToken = (UsernamePasswordToken) token;
|
||||
|
||||
if(uToken.getUsername() == null
|
||||
|| uToken.getUsername().isEmpty()
|
||||
|| !credentials.containsKey(uToken.getUsername())
|
||||
) {
|
||||
throw new UnknownAccountException("username not found!");
|
||||
}
|
||||
|
||||
|
||||
return new SimpleAuthenticationInfo(
|
||||
uToken.getUsername(), credentials.get(uToken.getUsername()),
|
||||
getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
|
||||
Set<String> roleNames = new HashSet<>();
|
||||
Set<String> permissions = new HashSet<>();
|
||||
|
||||
principals.forEach(p -> {
|
||||
try {
|
||||
Set<String> roles = getRoleNamesForUser(null, (String) p);
|
||||
roleNames.addAll(roles);
|
||||
permissions.addAll(getPermissions(null, null,roles));
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
|
||||
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
|
||||
info.setStringPermissions(permissions);
|
||||
return info;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
|
||||
if(!roles.containsKey(username)) {
|
||||
throw new SQLException("username not found!");
|
||||
}
|
||||
|
||||
return roles.get(username);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Set<String> getPermissions(Connection conn, String username, Collection<String> roleNames) throws SQLException {
|
||||
for (String role : roleNames) {
|
||||
if (!perm.containsKey(role)) {
|
||||
throw new SQLException("role not found!");
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> finalSet = new HashSet<>();
|
||||
for (String role : roleNames) {
|
||||
finalSet.addAll(perm.get(role));
|
||||
}
|
||||
|
||||
return finalSet;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user