Shiro一(入门)

    xiaoxiao2022-07-14  164

    Shiro—入门

    一.简介

    Shiro是一个安全方面的开源框架,主要用户-身份验证,授权,会话管理和加解密:

    身份验证:即用户登录,且具有rememberme等属性。授权:访问控制,即“谁”可以访问“什么”。会话管理:即使在非Web或EJB应用程序中,也可以管理特定用户的会话(Session)。密码:使用加密算法保护数据安全。

    二.Shiro示例

    1.新建maven项目,并引入依赖包:

    <dependencies> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> </dependencies>

    2.在src/main/resources中加入配置文件shiro.ini:

    [users] root = secret, admin guest = guest, guest presidentskroob = 12345, president darkhelmet = ludicrousspeed, darklord, schwartz lonestarr = vespa, goodguy, schwartz # ----------------------------------------------------------------------------- # Roles with assigned permissions # roleName = perm1, perm2, ..., permN # ----------------------------------------------------------------------------- [roles] admin = * schwartz = lightsaber:* goodguy = winnebago:drive:eagle5

    3.编写java代码:

    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(); Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); //"lonestarr":用户名,"vespa":密码 token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { System.out.println("帐号不存在"); } catch (IncorrectCredentialsException ice) { System.out.println("密码错误"); } catch (LockedAccountException lae) { System.out.println("帐号被锁定"); } catch (AuthenticationException ae) { System.out.println("其他错误"); } System.out.println("用户:【" + currentUser.getPrincipal() + "】登录成功"); if (currentUser.hasRole("schwartz")) { System.out.println("拥有schwartz角色!"); } else { System.out.println("没有schwartz角色."); } if (currentUser.isPermitted("lightsaber:weild")) { System.out.println("拥有lightsaber:weild权限"); } else { System.out.println("没有lightsaber:weild权限."); } if (currentUser.isPermitted("winnebago:otherrolesdddd")) { System.out.println("拥有winnebago:otherroles权限"); } else { System.out.println("没有winnebago:otherroles权限."); } currentUser.logout(); // } }

    3.运行结果:

    用户:【lonestarr】登录成功 拥有schwartz角色! 拥有lightsaber:weild权限 没有winnebago:otherroles权限.
    最新回复(0)