1.目录结构

2.log4j.properties

  1. #
  2. # Licensed to the Apache Software Foundation (ASF) under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. The ASF licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing,
  13. # software distributed under the License is distributed on an
  14. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. # KIND, either express or implied. See the License for the
  16. # specific language governing permissions and limitations
  17. # under the License.
  18. #
  19. log4j.rootLogger=INFO, stdout
  20.  
  21. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  22. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  23. log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
  24.  
  25. # General Apache libraries
  26. log4j.logger.org.apache=WARN
  27.  
  28. # Spring
  29. log4j.logger.org.springframework=WARN
  30.  
  31. # Default Shiro logging
  32. log4j.logger.org.apache.shiro=TRACE
  33.  
  34. # Disable verbose logging
  35. log4j.logger.org.apache.shiro.util.ThreadContext=WARN
  36. log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

3.shiro.ini

  1. #
  2. # Licensed to the Apache Software Foundation (ASF) under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. The ASF licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing,
  13. # software distributed under the License is distributed on an
  14. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. # KIND, either express or implied. See the License for the
  16. # specific language governing permissions and limitations
  17. # under the License.
  18. #
  19. # =============================================================================
  20. # Quickstart INI Realm configuration
  21. #
  22. # For those that might not understand the references in this file, the
  23. # definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
  24. # =============================================================================
  25.  
  26. # -----------------------------------------------------------------------------
  27. # Users and their assigned roles
  28. #
  29. # Each line conforms to the format defined in the
  30. # org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
  31. # -----------------------------------------------------------------------------
  32. [users]
  33. # user 'root' with password 'secret' and the 'admin' role
  34. root = secret, admin
  35. # user 'guest' with the password 'guest' and the 'guest' role
  36. guest = guest, guest
  37. # user 'presidentskroob' with password '' ("That's the same combination on
  38. # my luggage!!!" ;)), and role 'president'
  39. presidentskroob = , president
  40. # user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
  41. darkhelmet = ludicrousspeed, darklord, schwartz
  42. # user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
  43. lonestarr = vespa, goodguy, schwartz
  44.  
  45. # -----------------------------------------------------------------------------
  46. # Roles with assigned permissions
  47. #
  48. # Each line conforms to the format defined in the
  49. # org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
  50. # -----------------------------------------------------------------------------
  51. [roles]
  52. # 'admin' role has all permissions, indicated by the wildcard '*'
  53. admin = *
  54. # The 'schwartz' role can do anything (*) with any lightsaber:
  55. schwartz = lightsaber:*
  56. # The 'goodguy' role is allowed to 'delete' (action) the user (type) with
  57. # license plate 'zhangsan' (instance specific id)
  58. goodguy = user:delete:zhangsan

4.Quickstart.java

  1. package com.hxlz.helloworld;
  2.  
  3. import org.apache.shiro.SecurityUtils;
  4. import org.apache.shiro.authc.*;
  5. import org.apache.shiro.config.IniSecurityManagerFactory;
  6. import org.apache.shiro.mgt.SecurityManager;
  7. import org.apache.shiro.session.Session;
  8. import org.apache.shiro.subject.Subject;
  9. import org.apache.shiro.util.Factory;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12.  
  13. public class Quickstart {
  14.  
  15. private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
  16.  
  17. public static void main(String[] args) {
  18.  
  19. Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
  20. SecurityManager securityManager = factory.getInstance();
  21.  
  22. SecurityUtils.setSecurityManager(securityManager);
  23.  
  24. // 获取当前的 Subject. 调用 SecurityUtils.getSubject();
  25. Subject currentUser = SecurityUtils.getSubject();
  26.  
  27. // 测试使用 Session
  28. // 获取 Session: Subject#getSession()
  29. Session session = currentUser.getSession();
  30. session.setAttribute("someKey", "aValue");
  31. String value = (String) session.getAttribute("someKey");
  32. if (value.equals("aValue")) {
  33. log.info("---> Retrieved the correct value! [" + value + "]");
  34. }
  35.  
  36. // 测试当前的用户是否已经被认证. 即是否已经登录.
  37. // 调动 Subject 的 isAuthenticated()
  38. if (!currentUser.isAuthenticated()) {
  39. // 把用户名和密码封装为 UsernamePasswordToken 对象
  40. UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
  41. // rememberme
  42. token.setRememberMe(true);
  43. try {
  44. // 执行登录.
  45. currentUser.login(token);
  46. log.info("----> 该用户已登录!");
  47. }
  48. // 若没有指定的账户, 则 shiro 将会抛出 UnknownAccountException 异常.
  49. catch (UnknownAccountException uae) {
  50. log.info("----> There is no user with username of " + token.getPrincipal());
  51. return;
  52. }
  53. // 若账户存在, 但密码不匹配, 则 shiro 会抛出 IncorrectCredentialsException 异常。
  54. catch (IncorrectCredentialsException ice) {
  55. log.info("----> Password for account " + token.getPrincipal() + " was incorrect!");
  56. return;
  57. }
  58. // 用户被锁定的异常 LockedAccountException
  59. catch (LockedAccountException lae) {
  60. log.info("The account for username " + token.getPrincipal() + " is locked. " +
  61. "Please contact your administrator to unlock it.");
  62. }
  63. // 所有认证时异常的父类.
  64. catch (AuthenticationException ae) {
  65. }
  66. }
  67. //通过currentUser.getPrincipal()获取登录用户名
  68. log.info("----> User [" + currentUser.getPrincipal() + "] logged in successfully.");
  69.  
  70. // 测试是否有某一个角色. 调用 Subject 的 hasRole 方法.
  71. if (currentUser.hasRole("schwartz")) {
  72. log.info("----> May the Schwartz be with you!");
  73. } else {
  74. log.info("----> Hello, mere mortal.");
  75. return;
  76. }
  77.  
  78. //test a typed permission (not instance-level)
  79. // 测试用户是否具备某一个行为. 调用 Subject 的 isPermitted() 方法。
  80. if (currentUser.isPermitted("lightsaber:weild")) {
  81. log.info("----> You may use a lightsaber ring. Use it wisely.");
  82. } else {
  83. log.info("Sorry, lightsaber rings are for schwartz masters only.");
  84. }
  85.  
  86. //a (very powerful) Instance Level permission:
  87. // 测试用户是否具备某一个行为.
  88. if (currentUser.isPermitted("user:delete:zhangsan")) {
  89. log.info("----> You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
  90. "Here are the keys - have fun!");
  91. } else {
  92. log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
  93. }
  94.  
  95. // 执行登出. 调用 Subject 的 Logout() 方法.
  96. System.out.println("---->" + currentUser.isAuthenticated());
  97. //登出
  98. currentUser.logout();
  99. System.out.println("---->" + currentUser.isAuthenticated());
  100.  
  101. System.exit(0);
  102. }
  103. }

shiro-helloworld的更多相关文章

  1. 第一节:Shiro HelloWorld 实现

    1.新建maven工程,pom配置maven jar包 <dependency> <groupId>org.apache.shiro</groupId> <a ...

  2. Shiro学习

    Shiro学习资源 Shiro官网,http://shiro.apache.org/index.html 学习网站链接,http://blog.java1234.com/blog/articles/4 ...

  3. shiro(安全框架)

    shiro.apache.org JavaSE环境搭建Shiro框架 1/导入与 shiro相关的Jar包 所有集好的环境可以在如下目录查找 复制如上文件到工程中 2/配置文件:储存临时文件 shir ...

  4. Shiro-HelloWord

    HelloWorld Shiro的HelloWorld不是我们写的,而是看Shiro给我们提供的一段代码.通过这段代码可以看到Shiro大致的使用方式. 1.找到Shiro的jar包 目前的最新稳定版 ...

  5. shiro-core包引用的版本问题

    在做shiro学习时,遇到这样的问题: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/ ...

  6. Shrio第一天——入门与基本概述

    一.Shiro是什么 Apache Shiro是Java的一个安全框架.(希罗:/笑哭) Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境. sh ...

  7. Shrio Demo

    package com.atguigu.shiro.helloworld; import org.apache.shiro.SecurityUtils; import org.apache.shiro ...

  8. Shiro 的 HelloWorld

    密码文件 [users] zhang=123 wang=123 测试 package org.zln.hello; import org.apache.log4j.LogManager; import ...

  9. shiro的Helloworld

    package shiro; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePassword ...

  10. Shiro 加密helloWorld

    承接第一章 初解加密 只贴更改的源码,其他看上一篇. ShiroRealm.java package com.lkk.shiro.realms; import org.apache.shiro.aut ...

随机推荐

  1. Java基础(五) final关键字浅析

    前面在讲解String时提到了final关键字,本文将对final关键字进行解析. static和final是两个我们必须掌握的关键字.不同于其他关键字,他们都有多种用法,而且在一定环境下使用,可以提 ...

  2. 面试官:你了解过Redis对象底层实现吗

    上一章我们讲了Redis的底层数据结构,不了解的人可能会有疑问:这个和平时用的五大对象有啥关系呢?这一章我们就主要解释他们所建立的联系. 看这个文件之前,如果对ziplist.skiplist.int ...

  3. Ubuntu --- Xshell 连接 VirtualBox下安装的Ubuntu

    1.桥接模式 打开VirtualBox管理器---设置---网络---连接方式选择桥接网卡 2.安装ssh服务 安装: sudo apt-get install openssh-server 启动: ...

  4. Metasploit渗透测试

    原创博客,转载请注出处! 学习笔记 参考书籍<Metasploit渗透测试指南(修订版)> 经过多日学习,初步掌握metasploit基本参数和使用方法,现进行渗透测试实践 靶机IP:16 ...

  5. vue结合Ant Design实现后台系统的权限分配(支持无限子级嵌套)

    最近公司的业务需要,要做一个后台管理系统的管理系统类似于这样子 功能需求如下: 左边是权限菜单,右边对应的是具体权限. 1.父级权限菜单选中,父级权限菜单的权限包括其中所有子级权限菜单的权限也要选中, ...

  6. Flink UDF

    本文会主要讲三种udf: ScalarFunction TableFunction AggregateFunction 用户自定义函数是非常重要的一个特征,因为他极大地扩展了查询的表达能力.本文除了介 ...

  7. 微信商城小程序 带java后台源码

    微信小程序商城(Java版) 技术选型 1 后端使用技术 1.1 spring-web-4.0.2.RELEASE 1.2 mybatis3.2.8 1.3 shiro1.2.3 1.4 servle ...

  8. Linux五种IO模型 ——Java学习笔记

    本文摘自网络:     1.阻塞IO(blocking IO) 在linux中,默认情况下所有的socket都是blocking,一个典型的读操作流程大概是这样: 图1 阻塞IO 当用户进程调用了re ...

  9. ajax入门级

    AJAX AJAX:即异步的JavaScript 和 XML,是一种用于创建快速动态网页的技术: 传统的网页(不使用AJAX)如果需要更新内容,必需重载整个网页面: 使用AJAX则不与要加载更新整个网 ...

  10. Docker入门简介(一)

    Docker 介绍 Docker是Docker.lnc公司开源的一个基于LXC技术智商构建的Container容器引擎,源代码托管在GitHub上,基于Go语言并遵从Apache2.0协议开源. Do ...