shiro安全框架HelloWord入门篇

来源:互联网 发布:jacs在什么数据库 编辑:程序博客网 时间:2024/05/21 07:10

1、shiro:apache shiro是Java的一个安全(权限)框架,不同的用户登录具有不同的功能。

2、下载地址:http://shiro.apache.org/

3、shiro可以完成:认证、授权、加密、回话管理、缓存、与web继承。(内部架构图)


  • Authentication:身份认证/登录,验证用户是不是拥有相应的身份。
  • Authorization:授权,即权限验证。验证已登录的用户是否拥有某个权限。
  • Session Manager回话管理,即一个用户登录后就是一次会话,在没有退出之前,他的所有信息都在会话中。
  • Cryptography:加密,保护数据的安全性。例如:密码加密存入数据库中。
  • Web Support:Web支持,可以非常容易的集成在Web环境。
  • Caching:缓存。例如:用户登录后,其用户登录后的信息、角色和权限等都会放在缓存中,不用每次都去查询,从而提高效率。
  • Concurrency:多线程应用的并发验证。例如:在一个线程中开启另一个线程,shiro能够将用户的权限自动传递过去。
  • Testing:提供测试支持。
  • Run as:允许一个用户伪装成另一个用户的身份进行访问。
  • Remember Me:记住我。

4.Shiro外部架构图:

  • Subject:应用代码直接交互的对象。也就是Shiro的对外API核心就是Sbject。Subject代表了当前“用户”;与Subject的所有交互都会委托给SecurityManager,Subject其实就是一个门面,SecurityManager才是实际的执行者。
  • SecurityManager:安全管理器。即所有与安全相关的操作都要都会与SecurityManager交互;是Shiro的核心,负责于shiro的其他组件进行交互。相当于SpringMVC中的DispatcherServelt的角色。
  • Realm:shiro从Realm中获取安全数据(如:角色,权限,用户),可以把Realm看成DataSource。

5、HelloWord

  • 引入jar包---->shiro-all-1.3.2.jar
  • 引入配置文件----->shiro.ini
  • Java类helloword

public class HelloWord {    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);    public static void main(String[] args) {        // 利用配置文件创建一个SecurityManager实例,配置文件shiro.ini中具有用户名、密码和角色(仅限于helloWord)        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");        SecurityManager securityManager = factory.getInstance();        // 使securityManager在JVM中为单列的。*大部分应用都不这么用        SecurityUtils.setSecurityManager(securityManager);        // *获取当前的 Subject. 调用 SecurityUtils.getSubject();        Subject currentUser = SecurityUtils.getSubject();        // 测试使用 Session        //* 获取 Session: Subject#getSession()        Session session = currentUser.getSession();        // 测试当前的用户是否已经被认证. 即是否已经登录.        //* 调动 Subject 的 isAuthenticated()        if (!currentUser.isAuthenticated()) {            // 把用户名和密码封装为 UsernamePasswordToken 对象            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");            // rememberme            token.setRememberMe(true);            try {                // 执行登录.                currentUser.login(token);            }            // 若没有指定的账户, 则 shiro 将会抛出 UnknownAccountException 异常.            catch (UnknownAccountException uae) {                log.info("----> There is no user with username of " + token.getPrincipal());                return;            }            // 若账户存在, 但密码不匹配, 则 shiro 会抛出 IncorrectCredentialsException 异常。            catch (IncorrectCredentialsException ice) {                log.info("----> Password for account " + token.getPrincipal() + " was incorrect!");                return;            }            // 用户被锁定的异常 LockedAccountException            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:        // 测试是否有某一个角色. 调用 Subject 的 hasRole 方法.        if (currentUser.hasRole("schwartz")) {            log.info("----> May the Schwartz be with you!");        } else {            log.info("----> Hello, mere mortal.");            return;        }        // test a typed permission (not instance-level)        // 测试用户是否具备某一个行为. 调用 Subject 的 isPermitted() 方法。        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:        // 测试用户是否具备某一个行为.        if (currentUser.isPermitted("user:delete:zhangsan")) {            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!        // 执行登出. 调用 Subject 的 Logout() 方法.        System.out.println("---->" + currentUser.isAuthenticated());        currentUser.logout();        System.out.println("---->" + currentUser.isAuthenticated());        System.exit(0);    }}

6、以上只是简单的helloWord在项目中其实更多的用到的是注解和配置的方式,而并非上述的硬编码。如有想深入了解请关注shiro(2)






阅读全文
0 0
原创粉丝点击