Shiro
Apache Shiro是一个强大且易用的Java安全框架,有身份验证、授权、密码学和会话管理。
使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序
到最大的网络和企业应用程序。
Shiro的四大基石
Shiro 开发团队称为“应用程序的四大基石” ——身份验证,授权,会话管理和加密作为其目标。
Authentication(身份认证):
有时也简称为“登录”,这是一个证明用户是他们所说的他们是谁的行为。 Authorization(授权):
访问控制的过程,也就是绝对“谁”去访问“什么”权限。
Session Management:管理用户特定的会话,即使在非Web或EJB 应用程序。
Cryptography:通过使用加密算法保持数据安全同时易于使用。
也提供了额外的功能来支持和加强在不同环境下所关注的方面,尤其是以下这些:
Web Support: Shiro 的 web 支持的 API 能够轻松地帮助保护 Web 应用程序。
Caching:缓存是 Apache Shiro 中的第一层公民,来确保安全操作快速而又高效。
Concurrency: Apache Shiro 利用它的并发特性来支持多线程应用程序。Testing:测试支持的存在来帮助你编写单元测试和集成测试,并确保你的能够如预期的一样安全。
“Run As”:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;
“Remember Me”:在会话中记住用户的身份,所以他们只需要在强制时候登录。
Shiro入门
导入jar
<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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
准备资源
shiro.ini
#所有的用户与对应的用户密码 ,用户的角色
[users]
#root用户有一个密码是secret,他的角色是admin
root = secret, admin
guest = guest, guest
presidentskroob = 12345, president
#darkhelmet用户有一个密码是ludicrousspeed,他的角色是darklord, schwartz
darkhelmet = ludicrousspeed, darklord, schwartz
lonestarr = vespa, goodguy, schwartz
#-----------------------------------------------------------------------------
#所有的用户的角色
#-----------------------------------------------------------------------------
[roles]
admin这个角色有所有权限功能
admin = *
#schwartz这个角色可以操作所有的lightsaber权限功能
schwartz = lightsaber:*
#goodguy 角色拥有对 id 为 eagle5 的 winnebago 资源执行 drive 的权限
自定义Realm
刚才咱们使用的是准备的好的一个Realm,在Shiro中,除了咱们 刚才使用的iniRealm,
还有普通SimpleAccountRealm,JDBCRealm等等.但是这些Realm都不能满足咱们的
需求(后期咱们Realm的数据肯定是通过JPA去拿的,下一个项目要使用MyBatis去拿),
而这种情况下,就需要我们自己定义一个Realm来实现相应的功能!
准备工作
自定义Realm一般直接继承AuthorizingRealm接口即可(里面包含身份认证与授权两个方法)
自定义一个Realm
public class MyRealm extends
AuthorizingRealm {
//获取到这个Realm的名称(随便取)
@Override
public String getName() {
return "MyRealm";
}
//进行授权判断(权限)
@Override
protected AuthorizationInfo
doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
//进行身份认证(登录)
@Override
protected AuthenticationInfo
doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws
AuthenticationException {
return null;
}
}
身份认证(登录)
/**
* 自定义一个Realm
*/
public class MyRealm extends AuthorizingRealm {
//获取到这个Realm的名称(随便取)
@Override
public String getName() {
return "MyRealm";
}
//进行授权的认证
@Override
protected AuthorizationInfo
doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
//进行登录的认证
@Override
protected AuthenticationInfo
doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws
AuthenticationException {
//明显的知道:这个authenticationToken就是UsernamePasswordtoken
UsernamePasswordToken token =
(UsernamePasswordToken)authenticationToken;
String username =
token.getUsername(); //拿到用户名(注:这个用户名是传过来的)
//这里根据用户名去获取密码(如果没有获取到,相当于这个用户不存在,就返回null值)
String password =
getByName(username);
if(password==null){
return null;
}
//创建一个简单的身份信息(把用户名与密码放进去-注:它会自动的比较获取的密码与你传过来的密码)
SimpleAuthenticationInfo
authenticationInfo = new SimpleAuthenticationInfo(username,password,getName());
return authenticationInfo;
}
//模拟从数据库中获取信息
private String getByName(String
username) {
if("admin".equals(username)){
return "123456";
}else
if("guest".equals(username)){
return "abcd";
}
return null;
}
}
身份认证测试
@Test
public void testMyRealm() throws Exception{
//创建自己定义的Realm
MyRealm
myRealm = new MyRealm();
//把Realm放到securityManager中去
DefaultSecurityManager
securityManager = new DefaultSecurityManager();
securityManager.setRealm(myRealm);
//把权限管理器放到相应的环境中(我们可以在项目任何位置拿到)
SecurityUtils.setSecurityManager(securityManager);
//拿到当前用户(Subject就是当前用户,游客)
Subject currentUser =
SecurityUtils.getSubject();
//准备登录的令牌(准备用户名与密码)
UsernamePasswordToken token = new
UsernamePasswordToken("admin","123456");
try {
//根据令牌进行功能登录(当前用户进行登录)
currentUser.login(token);
} catch (UnknownAccountException e) {
System.out.println("这个账号不存在!" +
token.getPrincipal());
e.printStackTrace();
} catch (IncorrectCredentialsException
ice) {
System.out.println("这个密码不存在!" +
token.getPrincipal());
ice.printStackTrace();
}catch (AuthenticationException e){
System.out.println("i don't
k");
}
}
授权(权限)认证
public
class MyRealm extends AuthorizingRealm {
//获取到这个Realm的名称(随便取)
@Override
public String getName() {
return "MyRealm";
}
//进行授权的认证
@Override
protected AuthorizationInfo
doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//拿到认证的主要信息(用户名)
String username =
(String) principalCollection.getPrimaryPrincipal();
//模拟根据用户名拿到角色信息与权限信息
Set<String> roles =
getRolesByUsername(username);
Set<String> permissions =
getPermissionsByUsername(username);
//拿到验证信息对象
SimpleAuthorizationInfo
authorizationInfo = new SimpleAuthorizationInfo();
//设置用户的角色
authorizationInfo.setRoles(roles);
//设置用户的权限
authorizationInfo.setStringPermissions(permissions);
return authorizationInfo;
}
//模拟根据用户名拿到角色的功能
private Set<String>
getRolesByUsername(String username) {
Set<String> roles = new
HashSet<>();
roles.add("admin");
roles.add("it");
return roles;
}
//模拟根据用户名拿到权限的功能
private Set<String>
getPermissionsByUsername(String username) {
Set<String> permissions =
new HashSet<>();
permissions.add("employee.*");
permissions.add("department.save");
return permissions;
}
}
//功能测试
System.out.println("是否是这个角色:"+currentUser.hasRole("admin"));
System.out.println("是否是拥有权限:"+currentUser.isPermitted("employee.save"));
Shiro中密码加密
/**
algorithmName:加密算法(md5,sha)
source:原始密码
salt,加盐
hashIterations:遍历次数
*/
SimpleHash simpleHash = new
SimpleHash("MD5","admin","itsource",10);
System.out.println(simpleHash);
//测试时让自定义Reaml加上算法
@Test
public void testMyRealm() throws
Exception{
//创建自己定义的Realm
MyRealm myRealm = new MyRealm();
//把Realm放到securityManager中去
DefaultSecurityManager
securityManager = new DefaultSecurityManager();
securityManager.setRealm(myRealm);
//把权限管理器放到相应的环境中(我们可以在项目任何位置拿到)
SecurityUtils.setSecurityManager(securityManager);
//设置咱们Realm的密码匹配器(我们的密码要怎么处理)
HashedCredentialsMatcher matcher
= new HashedCredentialsMatcher();
matcher.setHashAlgorithmName("md5"); //匹配器使用MD5的算法
matcher.setHashIterations(10);//加密算法要迭代多少次
myRealm.setCredentialsMatcher(matcher);
//拿到当前用户(Subject就是当前用户,游客)
Subject currentUser =
SecurityUtils.getSubject();
//准备登录的令牌(准备用户名与密码) -> 这里的密码进行了加密
UsernamePasswordToken token =
new UsernamePasswordToken("admin","123456");
try {
//根据令牌进行功能登录(当前用户进行登录)
currentUser.login(token);
System.out.println("登录成功啦。。。。");
} catch (UnknownAccountException
e) {
System.out.println("这个账号不存在!" +
token.getPrincipal());
e.printStackTrace();
} catch (IncorrectCredentialsException
ice) {
System.out.println("这个密码不存在!" +
token.getPrincipal());
ice.printStackTrace();
}catch (AuthenticationException
e){
System.out.println("i
don't k");
}
}
自定义Reaml加上盐值
//进行登录的认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken
authenticationToken) throws AuthenticationException {
//明显的知道:这个authenticationToken就是UsernamePasswordtoken
UsernamePasswordToken token =
(UsernamePasswordToken)authenticationToken;
String username =
token.getUsername(); //拿到用户名(注:这个用户名是传过来的)
//这里根据用户名去获取密码(如果没有获取到,相当于这个用户不存在,就返回陪我)
String password =
getByName(username);
if(password==null){
return null;
}
//在这里加盐值需一个ByteSource对象,而Shiro提供了一个ByteSource对象给咱们
ByteSource salt =
ByteSource.Util.bytes("itsource");
//创建一个简单的身份信息(把用户名与密码放进去-注:它会自动的比较获取的密码与你传过来的密码)
SimpleAuthenticationInfo
authenticationInfo = new SimpleAuthenticationInfo(username,password,salt,getName());
return authenticationInfo;
}
private String getByName(String username) {
if("admin".equals(username)){
//
4a95737b032e98a50c056c41f2fa9ec6: 123456 迭代10次不加盐的结果
//
831d092d59f6e305ebcfa77e05135eac: 123456 迭代10次加盐(itsource)的结果
return "831d092d59f6e305ebcfa77e05135eac"; //修改为加密加盐后的数据
}else
if("guest".equals(username)){
return "abcd";
}
return null;
}
Shiro集成Spring
我们的项目基本都是通过Spring来管理bean的,如果要想使用Shiro,那就要把shiro
集成到Spring。集成Spring的核心就是把shiro框架的核心类
(SecurityManager,Subject,Realm)交给Spring管理!
准备Spring-web项目
<!-- shiro的支持包
-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>1.4.0</version>
<type>pom</type>
</dependency>
<!-- shiro与Spring的集成包
-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
拷贝shiroFilter配置到web.xml
<!-- Spring与shiro集成:需要定义一个shiro过滤器(这是一个代理过滤器,它会到spring的配置中找一个名称相同的真实过滤器) -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
拷贝shiro Spring配置文件并集成到Spring
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!--
1.配置apache的管理器 -->
<bean id="securityManager"
class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- 配置一个realm,到数据库中获取权限数据 -->
<property name="realm" ref="jpaRealm"/>
</bean>
<!--
2.我们可以自定义一个realm【暂时未实现功能】这个必需实现org.apache.shiro.realm.Realm接口 -->
<bean id="jpaRealm" class="cn.itsource.yxb.shiro.realm.JpaRealm">
</bean>
<!--
3.lifecycleBeanPostProcessor:可以自动调用在Spring Ioc窗口中 Shiro bean的生成周期方法 -->
<bean id="lifecycleBeanPostProcessor"
class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!--
4.启动ioc容器中使用 shiro的注解,但是必需配置在Spring Ioc容器中Shiro bean的生成周期方法 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor"/>
<bean
class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager"
ref="securityManager"/>
</bean>
<!--
5.shiro的真实过滤器(注:这个名称必需和web.xml的代表过滤器【DelegatingFilterProxy】名称一样) -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager"
ref="securityManager"/>
<!-- 登录的url,如果没有登录,你访问的路径会跳到这个页面 -->
<property name="loginUrl" value="/s/login.jsp"/>
<!-- 登录成功的url,如果登录成功,会跳转到这个页面 -->
<property name="successUrl" value="/s/main.jsp"/>
<!-- 没有权限时跳转到这个位置 -->
<property name="unauthorizedUrl"
value="/s/unauthorized.jsp"/>
<!--
配置哪些资源被保护,哪些资源需要权限
anon:不需要登录也可以访问相应的权限
authc:需要权限才能访问
/** :所有文件及其子文件
-->
<property name="filterChainDefinitions">
<value>
/s/login.jsp = anon
/** = authc
</value>
</property>
</bean>
</beans>
Authentication(身份认证)
详细步骤分析:
要想实现登录,分前台和后台两部分:
前台:
实现一个login.jsp的页面,用来搜集登录信息(用户名和密码)!当点击登录时把登录信息提交到后台完成认证。
后台:
写一个Controller接收前台传入的登录信息,完成登录认证。
具体步骤如下:
1)创建LoginConroller,写一个方法接收前台登录请求并接受登录信息(用户名和密码)
2)获取当前的 Subject. 调用 SecurityUtils.getSubject();
3)测试当前的用户是否已经被认证. 即是否已经登录. 调用 Subject 的 isAuthenticated()
4)若没有被认证, 则把用户名和密码封装为
UsernamePasswordToken 对象
5)执行登录: 调用 Subject 的 login(AuthenticationToken) 方法.
6)自定义
Realm 的方法, 从数据库中获取对应的记录, 返回给 Shiro.
入门中使用的是Shiro自带的IniRealm,IniRealm从ini配置文件中读取用户的信息,大部分情况下需要从系统的数据库中读取用户信息,所以需要自定义realm。
实际上需要继承 org.apache.shiro.realm.AuthenticatingRealm 类
实现 doGetAuthenticationInfo(AuthenticationToken) 方法.
由 shiro 完成对密码的比对.
简单认证实现
login.jsp
<form action="/login" method="post">
用户名<input type="text" name="username" /> <br />
密码:<input type="password" name="password" /> <br />
<input type="submit" value="登录" />
</form>
LoginController
@Controller
public class LoginController {
@RequestMapping("/login")
public String
login(String username,String password){
/**
* 获取当前的 Subject. 调用
SecurityUtils.getSubject();
* 测试当前的用户是否已经被认证. 即是否已经登录. 调用 Subject 的 isAuthenticated()
* 若没有被认证, 则把用户名和密码封装为 UsernamePasswordToken 对象
* 执行登录: 调用 Subject 的
login(AuthenticationToken) 方法.
*/
//1.拿到访问的主体(当前登录用户)
Subject subject = SecurityUtils.getSubject();
//2.判断这个用户是否已经登录(通过验证)
if(!subject.isAuthenticated()){
//3.如果没有验证,就要完成登录
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
try{
//4.根据toke完成登录功能
subject.login(token);
}catch (UnknownAccountException
e){System.out.println("用户名不存在!!");
e.printStackTrace();
}catch (IncorrectCredentialsException
e){ System.out.println("密码不存在!");
e.printStackTrace();
}catch (AuthenticationException
e){System.out.println("登录出错!");
e.printStackTrace();
}
}
return "redirect:/s/main.jsp";
}
}
JpaRealm
public class JpaRealm extends AuthenticatingRealm {
//AuthenticationInfo:认证; 身份验证; 证明
//登录的时候就会调用这个方法来做验证
@Override
protected AuthenticationInfo
doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//System.out.println(token.getClass().getName());
//可以转成相应的token
//UsernamePasswordToken upToken
=(UsernamePasswordToken)token;
//拿到传过来的用户名
//String username =
upToken.getUsername();
//自定义Realm中,需要根据用户名到数据库中拿到密码,然后返回给shiro
//String password =
"123456";
//身份认证(用户名)
Object principal = token.getPrincipal();
Object credentials = "123456"; //密码假设是根据用户名到数据库中查询出来的
return new SimpleAuthenticationInfo(principal,credentials,getName());
}
}
加密认证
//完成登录的认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken
authenticationToken) throws AuthenticationException {
UsernamePasswordToken token =
(UsernamePasswordToken)authenticationToken;
String username =
token.getUsername();
String dbPassword = findByUsername(token.getUsername());
if(dbPassword==null){
return null;
}
SimpleAuthenticationInfo
authorizationInfo = new
SimpleAuthenticationInfo(username,dbPassword,getName());
return authorizationInfo;
}
private String findByUsername(String username) {
if("admin".equals(username)){
//这里是没有加盐的结果
return "4a95737b032e98a50c056c41f2fa9ec6";
}
return null;
}
设置Realm的匹配值:
<property name="credentialsMatcher">
<!—设置加密匹配方案-->
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 编码的方式使用:md5 -->
<property name="hashAlgorithmName" value="MD5"/>
<!-- 编码的次数:10 -->
<property name="hashIterations" value="10"/>
</bean>
</property>
数据库要加密保存
@Test
public void testHash() throws Exception{
/**
algorithmName:加密算法(md5,sha)
source:原始密码
salt,加盐
hashIterations:遍历次数
*/
SimpleHash simpleHash = new
SimpleHash("MD5","123456","itsource",10);
System.out.println(simpleHash);
}
认证时要支持盐值
//AuthenticationInfo:认证; 身份验证; 证明
//登录的时候就会调用这个方法来做验证
//进行登录的认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken
authenticationToken) throws AuthenticationException {
//明显的知道:这个authenticationToken就是UsernamePasswordtoken
UsernamePasswordToken token =
(UsernamePasswordToken)authenticationToken;
String username =
token.getUsername(); //拿到用户名(注:这个用户名是传过来的)
//这里根据用户名去获取密码(如果没有获取到,相当于这个用户不存在,就返回陪我)
String password =
getByName(username);
if(password==null){
return null;
}
//在这里加盐值需一个ByteSource对象,而Shiro提供了一个ByteSource对象给咱们
ByteSource salt =
ByteSource.Util.bytes(“itsource”);
//创建一个简单的身份信息(把用户名与密码放进去-注:它会自动的比较获取的密码与你传过来的密码)
SimpleAuthenticationInfo
authenticationInfo = new SimpleAuthenticationInfo(username,password,salt,getName());
return authenticationInfo;
}
private String getByName(String username) {
if(“admin”.equals(username)){
//4a95737b032e98a50c056c41f2fa9ec6: 123456 迭代10次不加盐的结果
// 831d092d59f6e305ebcfa77e05135eac:
123456 迭代10次加盐(itsource)的结果
return"831d092d59f6e305ebcfa77e05135eac"; //修改为加密加盐后的数据
}else
if(“guest”.equals(username)){
return "abcd";
}
return null;
}
授权拦截
<property name="securityManager" ref="securityManager"/>
<!-- 登录的url,如果没有登录,你访问的路径会跳到这个页面 -->
<property name="loginUrl"
value="/s/login.jsp"/>
<!-- 登录成功的url,如果登录成功,会跳转到这个页面 -->
<property name="successUrl"
value="/s/main.jsp"/>
<!-- 没有权限时跳转到这个位置 -->
<property name="unauthorizedUrl"
value="/s/unauthorized.jsp"/>
<!--
配置哪些资源被保护,哪些资源需要权限
anon:不需要登录也可以访问相应的权限
authc:需要权限才能访问
/** :所有文件及其子文件
-->
<property name="filterChainDefinitions">
<value>
/s/login.jsp = anon
/login = anon
<!--对资源进行权限控制,要控制的资源都应该从数据库查出,现在咱们先写死-->
/s/permission.jsp =
perms[user:*]
/** = authc
</value>
</property>
具体实现:
public class JpaRealm extends AuthorizingRealm {
//AuthorizationInfo:授权(是否有权限进入操作)
// 我们只需要把相应的权限交给Shiro,它就会自动比对
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
{
//拿到主体信息(指的就是当前登录用户名)
-> 咱们的权限应该是根据当前用户进行查询到的
String username = (String) principals.getPrimaryPrincipal();
System.out.println("后面需要根据用户名获取资源"+username);
//获取权限资源(这里假设已经根据用户名到数据库中获取到了)
Set<String> permissions = new HashSet<>();
permissions.add("user:*");
//拿到授权对象,并且所有权限交给它
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.setStringPermissions(permissions);
//返回授权对象
return simpleAuthorizationInfo;
}
//AuthenticationInfo:认证; 身份验证; 证明
//登录的时候就会调用这个方法来做验证
@Override
protected AuthenticationInfo
doGetAuthenticationInfo(AuthenticationToken token) throws
AuthenticationException {
/**
* Object principal:主体(现在就是登录的用户名)
* Object hashedCredentials:编码后的认证密码
* ByteSource credentialsSalt:加盐
* String realmName
*/
//身份认证(用户名)
Object principal = token.getPrincipal();
//密码假设是根据用户名到数据库中查询出来的(数据库密码是经过加密的)
Object credentials = “d5a3fedf6c59c2ecbe7f7a6c1a22da37”;
//加盐的数据
ByteSource byteSource =
ByteSource.Util.bytes(“itsource”);
return
new SimpleAuthenticationInfo(principal,credentials,byteSource,getName());
}
}