Apache Shiro Hello World

举报
赵KK日常技术记录 发表于 2023/06/24 13:12:39 2023/06/24
【摘要】 Shiro 一个Apache 权限处理框架,现在更流行于security,能够指定用户的具体操作哪一个按钮,搭配接口,通过注解实现。官网:http://shiro.apache.org/download.html添加描述主要涉及权限管理,权限认证,session管理,加密支持web,缓存,并发,测试,记住我Shiro架构Subject 当前用户Security 管理subjectRea...

Shiro 一个Apache 权限处理框架,现在更流行于security,能够指定用户的具体操作哪一个按钮,搭配接口,通过注解实现。

官网:
http://shiro.apache.org/download.html

添加描述
主要涉及

权限管理,权限认证,session管理,加密
支持web,缓存,并发,测试,记住我
Shiro架构
Subject 当前用户
Security 管理subject

Realm 相当于RealmDao

Hello World

找到官网下载zip包。解压后

找到samples/quickstart/QuickStart.java

并将resource下面的配置复制
QuickStart.java
注释已经写在代码内

public class Quickstart {

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

public static void main(String[] args) {

    // The easiest way to create a Shiro SecurityManager with configured
    // realms, users, roles and permissions is to use the simple INI config.
    // We'll do that by using a factory that can ingest a .ini file and
    // return a SecurityManager instance:

    // Use the shiro.ini file at the root of the classpath
    // (file: and url: prefixes load from files and urls respectively):
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();

    // for this simple example quickstart, make the SecurityManager
    // accessible as a JVM singleton.  Most applications wouldn't do this
    // and instead rely on their container configuration or web.xml for
    // webapps.  That is outside the scope of this simple quickstart, so
    // we'll just do the bare minimum so you can continue to get a feel
    // for things.
    SecurityUtils.setSecurityManager(securityManager);

    // Now that a simple Shiro environment is set up, let's see what you can do:

    // get the currently executing user:

    //获取当前的subject   SecurityUtils.getSubject()
    Subject currentUser = SecurityUtils.getSubject();

    // Do some stuff with a Session (no need for a web or EJB container!!!)
    //获取session
    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 + "]");
    }

    // let's login the current user so we can check against roles and permissions:
    //测试是否被认证
    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 more exceptions here (maybe custom ones specific to your application?
        //总的认证异常处理
        catch (AuthenticationException ae) {
            //unexpected condition?  error?
        }
    }

    //say who they are:
    //print their identifying principal (in this case, a username):
    log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

    //test a role:
    //测试是否有某一个角色
    if (currentUser.hasRole("schwartz")) {
        log.info("May the Schwartz be with you!");
    } else {
        log.info("Hello, mere mortal.");
    }

    //test a typed permission (not instance-level)
    //测试用户是否有一个行为  weild
    //isPermitted   The 'schwartz' role can do anything (*) with any lightsaber:
    if (currentUser.isPermitted("lightsaber:weild")) {
        log.info("You may use a lightsaber ring.  Use it wisely.");
    } else {
        log.info("Sorry, lightsaber rings are for schwartz masters only.");
    }

    //a (very powerful) Instance Level permission:
    //goodguy = winnebago:drive:eagle5   更具体的行为
    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!");
    }

    //all done - log out!
    currentUser.logout();

    System.exit(0);
}

}

实际应用
@RequiresPermissions(“risk:thirdInterface:view”)
@GetMapping()
public String thirdInterface(ModelMap map, ThirdInterface thirdInterface) {

List<ThirdInterface> thirdInterfaceList = thirdInterfaceService.selectThirdInterfaceList(thirdInterface);
map.put("list", thirdInterfaceList);

return prefix + "/thirdInterface";

}
配合前端

var editFlag = [[ @ p e r m i s s i o n . h a s P e r m i ( s y s t e m : u s e r : e d i t ) ] ] ; v a r r e m o v e F l a g = [ [ {@permission.hasPermi('system:user:edit')}]]; var removeFlag = [[ {@permission.hasPermi(‘system:user:remove’)}]];

formatter: function(value, row, index) {
var actions = [];
actions.push('编辑 ');
actions.push(‘删除 ‘);
actions.push(‘重置’);
return actions.join(’’);
}
在角色的分配操作时指定是否拥有某个按钮的权限操作。

人生的焦虑来源对成功的渴望

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。