Authentication is the process of verifying a user's identity.
Authentication是验证用户身份的过程。
本系列文章目录如下:
- 为什么要使用Apache Shiro(一)
- Apache Shiro的三个重要概念(二)
- Apache Shiro核心功能之Authentication(三)
- Apache Shiro核心功能之Authorization(四)
- Apache Shiro核心功能之Session Management(五)
- Apache Shiro核心功能之Cryptography(六)
- Apache Shiro集成
- 将Apache Shiro集成到Spring-Boot应用程序中
这通常有三个步骤:
- 收集用户的身份信息,称为principals,和支持身份的证明,称为credentials
- 提交principals和credentials到系统
- 如果提交的credentials的符合系统对该用户身份(principal)的期望,则认为该用户已经过身份验证。 如果它们不匹配,则认为用户没有经过身份验证。 这个步骤常见的例子是人们都熟悉的用户名/密码组合。当用户登录到系统的时候他们系统用户名(principals)和密码(credentials)。当用户名密码匹配,则认为验证通过。
Shiro以一种简单直观的方式支持相同的工作流
正如我们所说的,Shiro有一个以Subject为中心的API——几乎所有你想在运行时使用Shiro做的事情都是通过与当前执行的Subject交互来实现的。
Subject登录
//1. Get the current Subject:
Subject currentUser = SecurityUtils.getSubject();
if ( !currentUser.isAuthenticated() ) {
//2. Acquire submitted principals and credentials:
AuthenticationToken token = new UsernamePasswordToken(username, password);
//this is all you have to do to support 'remember me' (no config - built in!):
token.setRememberMe(true);
//3. Login:
currentUser.login(token);
}
当登录方法被调用的时候,SecurityManager会收到AuthenticationToken,并且分发到一个或多个配置好的Realm,以允许每个realm根据需要执行身份验证检查。每个Realm都有能力在必要时对提交的AuthenticationToken做出反应。
处理登录失败
//3. Login:
try {
currentUser.login(token);
//if no exception, that's it, we're done!
} catch ( UnknownAccountException uae ) {
//username wasn't in the system, show them an error message?
} catch (IncorrectCredentialsException ice) {
//password didn't match, try again?
…
} catch (LockedAccountException lae) {
//account for that username is locked - can't login. Show them a message?
…
}
... more types exceptions to check if you want ...
catch (AuthenticationException ae) {…
}
You can choose to catch one of the AuthenticationException subclasses and react specifically, or generically handle any AuthenticationException。
但是仅仅因为用户证明了他们的身份并不意味着他们可以在你的应用程序中做任何他们想做的事情。 这就引出了下一个问题:“我如何控制允许用户做什么或不允许做什么?” 决定允许用户做什么被称为授权(authorization)。 接下来我们将介绍Shiro如何启用授权。