import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;
/**
* login的过程: 1.subject是接口 调用了实现类DelegatingSubject的login方法
* 2.DelegatingSubject的login方法调用SecurityManager接口的login方法
* 3.SecurityManager接口转交给该类的实现类DefaultSecurityManager处理
* 4.DefaultSecurityManager调用AuthenticatingSecurityManager的authenticate(
* AuthenticationToken token)方法验证
* 5.验证方法是调用了Authenticator验证器的实现类AbstractAuthenticator的authenticate(
* AuthenticationToken token)方法
* 6.然后转交给ModularRealmAuthenticator的doAuthenticate(AuthenticationToken
* authenticationToken)方法处理
* 7.ModularRealmAuthenticator提供了一种可插拔的认证风格,你可以在此处插入自定义Realm实现。
* 如果配置了多个Realm,ModularRealmAuthenticator会根据配置的AuthenticationStrategy(身份验证策略)
* 进行多Realm认证过程。 注:如果应用程序中仅配置了一个Realm,Realm将被直接调用而无需再配置认证策略。
*
* 如果身份验证失败请捕获 AuthenticationException 或其子类, 常见的如:
* DisabledAccountException(禁用的帐号)
* LockedAccountException(锁定的帐号)
* UnknownAccountException(错误的帐号)
* ExcessiveAttemptsException(登录失败次数过多)
* IncorrectCredentialsException (错误的凭证)
* ExpiredCredentialsException(过期的凭证)等
* 具体请查看其继承关系;对于页面的错误消息展示
* 最好使用如 “用户名 / 密码错误” 而不是 “用户名错误”/“密码错误”,防止一些恶意用户非法扫描帐号库;
*
* @author listener
*
*/
public class ShiroTest {
public void main() {
// 创建工厂 注意:SecurityManager是org.apache.shiro.mgt.SecurityManager包中的
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
// 从工厂中获取SecurityManager实例
SecurityManager securityManager = factory.getInstance();
// 将SecurityManager实例放入SecurityUtils中
SecurityUtils.setSecurityManager(securityManager);
// 从SecurityUtils中获取subject实例
Subject subject = SecurityUtils.getSubject();
// 创建UsernamePasswordToken
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123");
// 在subject中验证
try {
subject.login(token);
// 身份验证 登入
System.out.println("验证成功");
} catch (AuthenticationException e) {
// 验证失败
System.out.println("验证失败");
}
}
}
01-shiro之subject.login(token)详解
最新推荐文章于 2025-06-02 11:39:57 发布
本文详细解析了Apache Shiro权限认证的整个流程,包括Subject、SecurityManager、DefaultSecurityManager、Authenticator及ModularRealmAuthenticator的角色与工作原理。同时介绍了如何通过Shiro进行用户登录验证,以及常见身份验证异常及其处理方式。

3621

被折叠的 条评论
为什么被折叠?



