Apache Shiro框架之认证

前言

在应用系统中,对于用户而言,登录系统时,一般需要提供如身份 ID等一些标识信息来表明登录者的身份,如提供 email,用户名/密码来证明,这就是所谓的身份验证;对于服务端,需要先收集用户(对应Shiro中的Subject)提供的 principals(身份)和 credentials(证明)并进行进行身份确认,这就是所谓的认证。


一、身份验证

在 shiro 中,用户需要提供 principals (身份)和 credentials(证 明)给 shiro,从而应用能验证用户身份:

  • principals:身份,即主体的标识属性,可以是任何属性,如用户名、邮箱等,唯一即可。一个主体可以有多个 principals,但只有一个Primary principals,一般是用户名/邮箱/手机号。
  • credentials:证明/凭证,即只有主体知道的安全值,如密码/数字证书等。
  • 最常见的 principals 和 credentials 组合就是用户名/密码了。

1.身份验证基本流程

  1. 收集用户身份/凭证,即如用户名/密码;
  2. 调用 Subject.login 进行登录,如果失败将得到相应的 AuthenticationException异常,根据异常提示用户 错误信息;否则登录成功;
  3. 创建自定义的 Realm类,继承 org.apache.shiro.realm.AuthorizingRealm类,实现 doGetAuthenticationInfo()方法;
  4. 如果身份验证失败请捕获 AuthenticationException或其子类。

示例:ShiroHandler.java

ShiroHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* @author sunys
*/
@Controller
@RequestMapping("/shiro")
public class ShiroHandler {

@RequestMapping("/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password) {
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
// 把用户名和密码封装为 UsernamePasswordToken 对象
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// rememberme
token.setRememberMe(true);
try {
// 执行登录.
currentUser.login(token);
}
// ... catch more exceptions here (maybe custom ones specific to your application?
// 所有认证时异常的父类.
catch (AuthenticationException ae) {
//unexpected condition? error?
System.out.println("登录失败: " + ae.getMessage());
}
}
return "redirect:/list.jsp";
}
}

ShiroRealm.java

ShiroRealm.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* @author sunys
*/
public class ShiroRealm extends AuthorizingRealm {

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
//1. 把 AuthenticationToken 转换为 UsernamePasswordToken
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
//2. 从 UsernamePasswordToken 中来获取 username
String username = upToken.getUsername();
//3. 调用数据库的方法, 从数据库中查询 username 对应的用户记录
System.out.println("从数据库中获取 username: " + username + " 所对应的用户信息.");
//4. 若用户不存在, 则可以抛出 UnknownAccountException 异常
if("unknown".equals(username)){
throw new UnknownAccountException("用户不存在!");
}
//5. 根据用户信息的情况, 决定是否需要抛出其他的 AuthenticationException 异常.
if("monster".equals(username)){
throw new LockedAccountException("用户被锁定");
}

//6. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo
//以下信息是从数据库中获取的.
//1). principal: 认证的实体信息. 可以是 username, 也可以是数据表对应的用户的实体类对象.
Object principal = username;
//2). credentials: 密码.
Object credentials = null; //"fc1709d0a95a6be30bc5926fdb7f22f4";
if("admin".equals(username)){
credentials = "038bdaf98f2037b31f1e75b5b4c9b26e";
}else if("user".equals(username)){
credentials = "098d2c478e9c11555ce2823231e02ec1";
}
//3). realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可
String realmName = getName();
//4). 盐值.
ByteSource credentialsSalt = ByteSource.Util.bytes(username);

SimpleAuthenticationInfo info = null; //new SimpleAuthenticationInfo(principal, credentials, realmName);
info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
return info;
}
}

AuthorizingRealm
AuthenticationExecption


二、身份认证

身份认证流程

1.身份认证流程

  1. 首先调用 Subject.login(token)进行登录,其会自动委托给 SecurityManager;
  2. SecurityManager负责真正的身份验证逻辑;它会委托给 Authenticator进行身份验证;
  3. Authenticator才是真正的身份验证者,Shiro API中核心的身份认证入口点,此处可以自定义插入自己的实现;
  4. Authenticator可能会委托给相应的 AuthenticationStrategy进行多 Realm身份验证,默认 ModularRealmAuthenticator会调用AuthenticationStrategy进行多 Realm身份验证;
  5. Authenticator 会把相应的 token 传入 Realm,从 Realm 获取身份验证信息,如果没有返回/抛出异常表示身份验证失败了。此处 可以配置多个Realm,将按照相应的顺序及策略进行访问。

1.1.Authenticator

Authenticator的职责是验证用户帐号,是 Shiro API中身份验证核心的入口点:如果验证成功,将返回AuthenticationInfo验证信息;此信息中包含了身份及凭证;如果验证失败将抛出相应的 AuthenticationException异常。
SecurityManager接口继承了 Authenticator,另外还有一个 ModularRealmAuthenticator实现,其委托给多个Realm进行验证,验证规则通过 AuthenticationStrategy接口指定。

Authenticator接口

1.2.Realm

Shiro从 Realm获取安全数据(如用户、角色、 权限),即 SecurityManager要验证用户身份,那么它需要从 Realm获取相应的用户进行比较以确定用户身份是否 合法;也需要从 Realm得到用户相应的角色/权限进行验证用户是否能进行操作,可以有一个或多个 Realm,将按照相应的顺序及策略进行访问。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realms">
<list>
<!-- 配置多个Realm ,采用不同的加密方式,将按照list相应的顺序-->
<ref bean="firstRealm"/>
<ref bean="secondRealm"/>
</list>
</property>
</bean>
<bean id="firstRealm" class="com.syshlang.shiro.realms.ShiroRealm">
<!-- 配置凭证算法匹配器 -->
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 采用MD5加密-->
<property name="hashAlgorithmName" value="MD5"></property>
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>
<bean id="secondRealm" class="com.syshlang.shiro.realms.SecondRealm">
<!-- 配置凭证算法匹配器 -->
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 采用SHA1加密-->
<property name="hashAlgorithmName" value="SHA1"></property>
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>

Realm接口如下:
Realm接口

  • String getName();//返回一个唯一的Realm名字
  • boolean supports(AuthenticationToken token);//判断此Realm是否支持Token
  • AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;//根据Token获取认证信息

实际开发中,一般继承 AuthorizingRealm(授权)即可;其继承了 AuthenticatingRealm(即身份验证),而且也间接继承了CachingRealm(带有缓存实现)。

Realm 的继承关系:
Realm接口继承关系

1.3.AuthenticationStrategy

Realm接口

  • AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有 Realm身份验证成功的认证信息,如果有一个失败就失败了;
  • AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和 FirstSuccessfulStrategy不同,将返回所有 Realm身份验证成功的认证信 息;
  • FirstSuccessfulStrategy:只要有一个 Realm 验证成功即可,只返回第一个 Realm身份验证成功的认证信息,其他的忽略。

ModularRealmAuthenticator 默认是 AtLeastOneSuccessfulStrategy策略:

1
2
3
4
//ModularRealmAuthenticator默认构造器
public ModularRealmAuthenticator() {
this.authenticationStrategy = new AtLeastOneSuccessfulStrategy();
}

自定义配置ModularRealmAuthenticator,更改默认策略:

1
2
3
4
5
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.FirstSuccessfulStrategy"></bean>
</property>
</bean>

附:身份验证相关的拦截器
身份验证相关的拦截器