您的位置:首页 > 其它

Shiro认证过程--源码分析

2018-03-14 17:35 696 查看
Shiro认证过程源码分析

这篇文章会根据源码分析一下Shiro实现认证的过程,(不涉及Shiro的Filter对url的处理,只从Subject的login()方法开始分析)

注: 配置文件和代码都放在文章最下面

准备工作:

1.login.jsp: 登录界面,用户在此输入username和password 

2.success.jsp: 登录成功的界面

3.LoginController: 接收login.jsp的username和password,并开始执行Shiro的认证操作的控制器.

4.ShiroRealm: 自定义的Realm(因为本文只分析认证过程,所以只继承了AuthenticatingRealm),提供用户的安全数据,并返回给Shiro用来对比用户输入的信息,从而判断用户是否成功被认证, 本文着重根据源码分析认证过程, 故以静态数据模拟从数据库中获取数据.

现在开始分析认证的过程,我们以debug的方式来分析.


● 启动服务器,访问login.jsp页面,输入在ShiroRealm中准备好的用户名和密码,点击login



● 代码停在LoginController中的login方法



可以看到已经获取到了username和password,为了后续的认证,我们需要获取Subject对象,也就是代表当前用户的对象"user", 并且还要将两个变量设置到一个UsernamePasswordToken对象"token"中, 随后调用user的login方法,并将token作为参数传入.

● 接下来我们进入login方法 看看内部是怎样实现的.代码如下,(截取了一部分)



可以看到,正如Shiro的官方文档所说, 所有安全操作都会委托给SecurityManager来执行,

● 进入securityManager的login方法 代码如下:



注意, 这里才开始真正的认证操作, 在这个方法中定义了AuthenticationInfo对象用来接收从Realm传来的认证信息,

● 进入authenticate方法:



会看到该方法会继续调用authenticator的authenticate方法, 那么这个authenticator是谁呢? 继续往下走

● 进入authenticator的authenticate方法,



发现这是一个抽象类, 在它的authenticate方法中又调用了自己的doAuthenticate方法, 但该类中对doAuthenticate并没有具体实现,所以继续往下走, 看看哪个类对它进行了实现,

● 进入doAuthenticate方法,(该方法的实现比较长,不使用截图的方式,直接上代码) 
 ModularRealmAuthenticator:protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
this.assertRealmsConfigured();
Collection realms = this.getRealms();
return realms.size() == 1?this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken):this.doMultiRealmAuthentication(realms, authenticationToken);
}

这才是之前的那个authenticator的真正实现,它的assertRealmsConfigured方法是判断Realm是否存在,不存在则会抛出IllegalStateException.随后根据Realm的个数来判断执行哪个方法,我只配了一个Realm,故会执doSingleRealmAuthentication,并将realm和token作为参数传入, 当然, 传入的realm实际上就是我自定义的ShiroRealm.

● 进入doSingleRealmAuthentication方法:



首先判断该realm是否支持认证该token, 显然是支持的,所以执行else,

● 执行了realm的getAuthenticationInfo(token)方法:



可以看到, 执行了ShiroRealm所继承类的getAuthenticationInfo方法: 首先shiro会先从缓存中获取认证信息(对应getCachedAUthenticationInfo方法),如果没有才会继续从Realm中获取, 因为我们是第一次登录,所以缓存中肯定没有认证信息,所以会执行if语句中的代码

● 注意,这里是重点, 执行了doGetAuthenticationInfo方法



 

终于执行到了我们自定义Realm的doGetAuthenticationInfo方法, 该方法会从数据库中(本实现为模拟从数据中获取数据)获取用户的安全信息,封装为SimpleAuthenticationInfo对象并返回, 这个info对象就是shiro实现认证所需要的信息

● 我们再返回到AuthenticatingRealm的getAuthenticationInfo方法, 来看看shiro获取认证信息后是怎么进行认证的,



执行图中箭头指向的方法, 这个方法就是进行密码匹配的

● 进入assertCredentialsMatch(token, info)方法



该方法首先获取了一个CredentialsMatcher, 译为凭证匹配器, 这里获取的是HashedCredentialsMatcher类的对象(见配置文件),该类的作用是将用户输入的密码以某种算法加密(为了安全考虑,数据库中用户的密码都是以密文保存的).所以需要加密后再对比

● 进入doCredentialsMatch(token, info)



对token中的password加密后,执行equals方法进行对比,如果相同则认证成功,返回true.反之认证失败, 返回false,并在接下来抛出AuthenticationException.  到此,认证过程结束, 将info原路返回到DefaultSecurityManager.

 

--------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------

附件:

applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!--1. 配置 SecurityManager!-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="realm" ref="jdbcRealm"/>
</bean>

<!--2. 配置 CacheManager. 2.1 需要加入 ehcache 的 jar 包及配置文件.-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>

<!--3. 配置 Realm. 3.1 直接配置实现了 org.apache.shiro.realm.Realm 接口的 bean-->
<bean id="jdbcRealm" class="com.iamto.ld.ShiroRealm">
<property name="credentialsMatcher">
<bean name="hashedCredentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"/>
<property name="hashIterations" value="1024"/>
</bean>
</property>
</bean>

<!--4. 配置 LifecycleBeanPostProcessor. 可以自定的来调用配置在 Spring IOC 容器中 shiro bean 的生命周期方法.-->
<bean id="lifecycle
af68
BeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!--5. 启用 IOC 容器中使用 shiro 的注解. 但必须在配置了 LifecycleBeanPostProcessor 之后才可以使用.-->
<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>

<!--6. 配置 ShiroFilter.
6.1 id 必须和 web.xml 文件中配置的 DelegatingFilterProxy 的 <filter-name> 一致.
若不一致, 则会抛出: NoSuchBeanDefinitionException. 因为 Shiro 会来 IOC 容器中查找和 <filter-name> 名字对应的 filter bean.-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.jsp"/>
<property name="successUrl" value="/success.jsp"/>
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<!--
配置哪些页面需要受保护.
以及访问这些页面需要的权限.
1). anon 可以被匿名访问
2). authc 必须认证(即登录)后才可能访问的页面.
3). logout 登出.
4). roles 角色过滤器
-->
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/shiro/login = anon
/action.jsp = anon
/actions/action = anon
/logout = logout

/user.jsp = roles[user]
/admin.jsp = roles[admin]

# everything else requires authentication:
/** = authc
</value>
</property>
</bean>
</beans>
ShiroRealm:
public class ShiroRealm extends AuthenticatingRealm {

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("---------------First Realm---------------");

UsernamePasswordToken upToken = (UsernamePasswordToken) token;

String username = upToken.getUsername();

if(username.equals("unknown")) {
throw new UnknownAccountException("用户不存在");
} else if(username.equals("monster")) {
throw new AuthenticationException("认证出现问题");
}

Object principal = username;
Object hashedCredentials = "d017b0495d437902003dbec56a25c1a3";
Object credentialsSalt = username;
String realmName = getName();

SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,hashedCredentials,ByteSource.Util.bytes(credentialsSalt), realmName);
return info;
}

public static void main(String[] args) {
String hashAlgorithmName = "MD5";
String credentials = "123456";
String salt = "wyy";
int hashIterations = 1024;

SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
System.out.println(simpleHash);
}
}
LoginController:
@Controller
@RequestMapping("/shiro")
public class LoginController {

@RequestMapping("/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password) {

Subject user = SecurityUtils.getSubject();

if (!user.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//设置为记住我
//token.setRememberMe(true);
try {
user.login(token);
} catch (AuthenticationException ae) {
System.out.println("登录失败-----cause:" + ae.getMessage());
}
}

return "redirect:/success.jsp";
}
}
login.jsp:<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>insert title here</title>
</head>
<body>
<h4>Login page</h4>
<form action="shiro/login" method="post">
<input type="text" name="username"/>
<br/><br/>
<input type="password" name="password"/>
<br/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>success.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>insert title here</title>
</head>
<body>
<h4>Success page</h4>
<a href="logout">logout</a>
<br/><br/>
</body>
</html>



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: