shiro官方示例

以下代码来自于shiro官方提供的代码,便于新手入门shiro api,中文为个人翻译,仅供参考

public class Quickstart {

    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {

        // 创建具有realms、users、roles 和permissions的Shiro SecurityManager,最简单方法是使用INI配置。
        // 我们将通过使用一个可以读取.ini文件并返回SecurityManager实例的工厂类来实现这一点:
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); // 使用classpath目录下的shiro.ini文件
        SecurityManager securityManager = factory.getInstance();

        // 对于这个简单的快速入门示例,将SecurityManager作为JVM单例进行访问。
        // 大多数应用程序不会这样做,而是依赖于它们的容器配置或者webapp的web.xml。
        // 但这超出了这个简单快速入门的范围,所以我们只做最简单的操作,这样您就可以继续对事物有所了解。
        SecurityUtils.setSecurityManager(securityManager);

        // 现在设置了一个简单的Shiro环境,让我们看看您可以做什么:

        // 获取当前正在执行的用户:
        Subject currentUser = SecurityUtils.getSubject();

        // 用session做一些事情(不需要web或EJB容器!!!)
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }

        // 让我们登录当前用户,以便检查角色和权限:
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);
            try {
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                log.info("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
            // ... 在此处捕获更多异常(可能是特定于应用程序的自定义异常)?
            catch (AuthenticationException ae) {
                // 意外情况?错误?
            }
        }

        // 打印其身份主体(在本例中为用户名):
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        // 测试一个权限:
        if (currentUser.hasRole("schwartz")) {
            log.info("May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
        }

        // 测试类型化权限(不是实例级)
        if (currentUser.isPermitted("lightsaber:wield")) {
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }

        //(非常强大的)实例级权限:
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        // 全部结束后退出
        currentUser.logout();

        System.exit(0);
    }
}

权限相关信息(shiro.ini):

# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz

# -----------------------------------------------------------------------------
# Roles with assigned permissions
# 
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5

如果有兴趣了解更多相关内容,欢迎来我的个人网站看看:瞳孔的个人空间

以下是一个简单的Apache Shiro代码示例,包括如何创建Shiro安全管理器,如何配置Shiro的认证和授权策略,以及如何使用Shiro进行认证和授权。 1. 创建Shiro安全管理器 ```java DefaultSecurityManager securityManager = new DefaultSecurityManager(); ``` 2. 配置Shiro的认证和授权策略 ```java // 配置认证策略 HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher("SHA-256"); credentialsMatcher.setHashIterations(2); MyRealm realm = new MyRealm(); realm.setCredentialsMatcher(credentialsMatcher); securityManager.setRealm(realm); // 配置授权策略 SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.addRole("admin"); authorizationInfo.addStringPermission("user:create"); authorizationInfo.addStringPermission("user:update"); authorizationInfo.addStringPermission("user:delete"); securityManager.setAuthorizationInfo(authorizationInfo); ``` 3. 实现Shiro的Realm接口 ```java public class MyRealm extends AuthorizingRealm { // 实现认证方法 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); String password = getPasswordByUsername(username); if (password == null) { throw new UnknownAccountException("用户名不存在!"); } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, getName()); return authenticationInfo; } // 实现授权方法 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String username = (String) principals.getPrimaryPrincipal(); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.setRoles(getRolesByUsername(username)); authorizationInfo.setStringPermissions(getPermissionsByUsername(username)); return authorizationInfo; } // 模拟数据库查询用户密码 private String getPasswordByUsername(String username) { return "123456"; } // 模拟数据库查询用户角色 private Set<String> getRolesByUsername(String username) { Set<String> roles = new HashSet<>(); roles.add("admin"); return roles; } // 模拟数据库查询用户权限 private Set<String> getPermissionsByUsername(String username) { Set<String> permissions = new HashSet<>(); permissions.add("user:create"); permissions.add("user:update"); permissions.add("user:delete"); return permissions; } } ``` 4. 使用Shiro进行认证和授权 ```java // 创建Subject对象 Subject subject = SecurityUtils.getSubject(); // 创建认证Token UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456"); // 进行认证 subject.login(token); // 进行授权 boolean hasRole = subject.hasRole("admin"); boolean hasPermission = subject.isPermitted("user:create"); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值