1.简介:
Apache Shiro是Java的一个安全(权限)框架,不仅可以用在Java SE环境,也可以用在Java EE环境。Shiro可以完成:认证、授权、加密、会话管理、与Web集成、缓存等。
下载:http://shiro.apache.org/
2.功能简介:
主要功能:
Authentication:认证(登录)。
Authorization:授权。
Session Management:管理Session,此Session不止Web环境下的HttpSession,它是Shiro自己的Session,在JavaSE的环境下也有。
Cryptography:加密。
支持:
Web Support:跟Java EE进行集成。
Concurrency:在多线程的情况下进行授权认证。
Testing:测试。
Caching:缓存模块。
Run As:让已经登录的用户以另外一个用户的身份来操作系统。
Remember Me:记住我。
3.Shiro架构:
3.1 外部架构:
Subject:应用代码直接交互的对象是Subject,也就是说Shiro对外API核心就是Subject。Subject代表了当前“用户”,这个用户不一定是具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫和机器人;与Subject的所有交互都会委托给SecurityManager;Subject是门面,SecurityManager是实际的执行者。
Shiro SecurityManager:安全管理器,所有与安全相关的操作都会与SecurityManager交互;并且管理着所有的Subject;是Shiro的核心;它负责和Shiro的其他组件交互。
Realm:Shiro从Realm获取安全数据(如用户、角色和权限),也就是SecurityManager需要验证身份,那么它需要从Realm中获得相应的用户进行比较等等,Realm相当于是一个DataSource。
3.2 内部架构:
4.HelloWorld:
先导入基本的Jar包到类路径下:
导入配置文件和Java文件到Src下面:
package com.shiro.helloworld;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.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) {
//使用工厂的方式获取.ini配置文件,返回一个SecurityManager实例
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
//在这个例子中SecurityManager在JVM中是单例可访问的
SecurityUtils.setSecurityManager(securityManager);
//获取当前的Subject
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("---> Retrieved the correct value! [" + value + "]");
}
//测试当前的用户是否已经被认证,即是否已经登录
if (!currentUser.isAuthenticated()) {
//把用户名和密码封装到UsernamePasswordToken对象
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
//Remember Me
token.setRememberMe(true);
try {
//执行登录
//能否登录成功取决于.ini配置文件是否存在对应的用户名和密码
currentUser.login(token);
}
catch (UnknownAccountException uae) {
//没有指定账户时,抛出该异常
log.info("----> There is no user with username of " + token.getPrincipal());
return;
}
catch (IncorrectCredentialsException ice) {
//密码不正确时,抛出该异常
log.info("----> Password for account " + token.getPrincipal() + " was incorrect!");
return;
}
catch (LockedAccountException lae) {
//用户被锁定时,抛出该异常
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
catch (AuthenticationException ae) {
//总的认证异常
//unexpected condition? error?
}
}
log.info("----> User [" + currentUser.getPrincipal() + "] logged in successfully.");
//测试是否有这个schwartz角色
if (currentUser.hasRole("schwartz")) {
log.info("----> May the Schwartz be with you!");
} else {
log.info("----> Hello, mere mortal.");
return;
}
//测试用户是否具备某一个行为
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.");
}
//同上,不过更具体,意思就是这个用户是否可以删除(delete)用户(user)张三(zhangsan)
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!");
}
System.out.println("---->" + currentUser.isAuthenticated());
//执行登出
currentUser.logout();
System.out.println("---->" + currentUser.isAuthenticated());
System.exit(0);
}
}
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================
# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[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 'delete' (action) the user (type) with
# license plate 'zhangsan' (instance specific id)
goodguy = user:delete:zhangsan