Shiro
时间:2020-07-12
本文章向大家介绍Shiro,主要包括Shiro使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
简介
● Apache Shiro是一个Java的安全(权限)框架。
● Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境, 也可以用在JavaEE环境。
● Shiro可以完成,认证,授权,加密,会话管理,Web集成,缓存等。
● 下载地址: http://shiro.apache.org/
功能
架构(外部)
架构(内部)
快速开始步骤
- 导入依赖
- 配置文件
- helloworld
resources.log4j.properties
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
resources.shiro.ini
[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
官方例子 Quickstart.java
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.ini.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.lang.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
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 session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Subject=>session[" + value + "]");
}
//判断当前的用户是否被认证
if (!currentUser.isAuthenticated()) {
//Token:令牌,没有获取,随机
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)
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.");
}
//细粒度
//a (very powerful) Instance Level permission:
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);
}
}
重点的几个函数
原文地址:https://www.cnblogs.com/peng8098/p/java_27.html
- WCF版的PetShop之一:PetShop简介[提供源代码下载]
- 维吉尼亚密码及程序实现
- 迪菲-赫尔曼密钥交换
- 分布式系统组件之配置中心
- github 提交报403 forbidden的错误解决
- Apache thrift - 使用,内部实现及构建一个可扩展的RPC框架
- redis主从集群搭建及容灾部署(哨兵sentinel)
- 浅谈ASP.NET的Postback
- redis配置详解(中英文)
- 我所理解的Remoting(1):Marshaling & Activation[下篇]
- 5分钟短视频,带你走进日志易SPL,助你日志分析更容易
- Unity Application Block 1.2 for Silverlight - December 2008
- 算法学堂 - 二分查找及其变形
- Zookeeper权限管理与Quota管理
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- 聊聊dubbo-go的failsafeCluster
- Phenotype : 大规模表型数据处理工具
- 聊聊dubbo-go的registryAwareCluster
- 老伙计,关于JDK并发包,这些不为人知的秘密你知道多少?
- 不能错过的分布式ID生成器(Leaf ),好用的一批
- 微信小程序开发实战(20):TabBar导航
- 饿了么备注输入框-不吃辣-少放辣-多放辣-不吃蒜-不吃香菜等
- From High Ceph Latency to Kernel Patch with eBPF/BCC
- JConsole、VisualVM 依赖的 JMX 技术到底是什么
- DHCP 中继实验
- 【NBA 可视化】使用Pyecharts实现湖人19-20赛季投篮数据可视化~
- 微信小程序开发实战(18):地图组件
- 教你几招,快速创建 MySQL 五百万级数据,愉快的学习各种优化技巧
- 【Pyecharts】2014-2019年高考数据可视化~
- 25.Python的循环与递归