org.apache.shiro.authc.UnknownAccountException错误,亲测可用

踩坑记录

springboot整合shiro之后,测试登录报错【org.apache.shiro.authc.UnknownAccountException】

登录成功与否都报错。

错误原因

找了别人的博客都不行,自己debug走排坑。发现登录的时候Realm的认证方法走了两次。

等于说登录方法被拦截了,登陆之前走了一次,登录的时候又走了一次
登录之前走的Realm认证方法,里面token啥都没有或者已经过期了,所有拿不到东西,拿不到东西数据库就查不到数据,那你的user类就是null,就会报这个错

解决方法

shiro配置的时候,排出你的登录接口,如下。

在你配置的地方,添加filterRuleMap.put("/common/login", "anon");
/common/login是你的登录接口

//配置拦截器
  @Bean
  public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
      ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
      shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
      /**
       *添加Shiro内置过滤器
       * 常用的过滤器:
       *    anon:无需认证(登录)可以访问
       *    authc:必须认证才可以访问
       *    user:如果使用rememberMe的功能可以直接访问
       *    perms:该资源必须得到资源权限才可以访问
       *    role:该资源必须得到角色权限才可以访问
       */
      Map<String, Filter> filterMap = new HashMap<>();
      filterMap.put("jwt", new JWTFilter());
      filterMap.put("corsAuthenticationFilter", corsAuthenticationFilter());
      shiroFilterFactoryBean.setFilters(filterMap);
      Map<String, String> filterRuleMap = new HashMap<>();
      filterRuleMap.put("/**", "jwt");
      filterRuleMap.put("/common/login", "anon"); //放行登录接口
      shiroFilterFactoryBean.setFilterChainDefinitionMap(filterRuleMap);
      return shiroFilterFactoryBean;
  }

另外:如果需要spring boot 整合shiro的配置,可以参考我的仓库:springboot 整合shiro配置仓库
里面的登录接口认证 授权方法需要自己修改

@Component public class ShiroDbRealmImpl extends ShiroDbRealm { @Autowired private RedisTemplate<String, Long> redisTemplate; @Autowired private EmployeeService employeeService; @Autowired private EmployeeMapper employeeMapper; @Autowired private JwtProperties jwtProperties; @Override public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //token令牌信息 UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token; //查询user对象 Employee employee = employeeMapper.getByUsername(usernamePasswordToken.getUsername()); if (employee == null) { //账号不存在 throw new UnknownAccountException("账号不存在!"); } if (employee.getStatus() == StatusConstant.DISABLE) { //账号被禁止 throw new LockedAccountException("账号被禁止!"); } //构建认证信息对象:1、令牌对象 2、密文密码 3、加密因子 4、当前realm的名称 return new SimpleAuthenticationInfo(employee, employee.getPassword(), ByteSource.Util.bytes(jwtProperties.getAdminSecretKey()), getName()); } @Override public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){ Employee employee = (Employee) principals.getPrimaryPrincipal(); return employeeService.getAuthorizationInfo(employee); } @Override public void initCredentialsMatcher() { //指定密码算法 RetryLimitCredentialsMatcher hashedCredentialsMatcher = new RetryLimitCredentialsMatcher("MD5",redisTemplate); //指定迭代次数 hashedCredentialsMatcher.setHashIterations(1024); //生效密码比较器 setCredentialsMatcher(hashedCredentialsMatcher); } } package com.sky.realm.Impl; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.ExcessiveAttemptsException; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import java.util.concurrent.TimeUnit; /** * @Description:自定义密码比较器 - 基于RedisTemplate实现登录重试限制 */ public class RetryLimitCredentialsMatcher extends HashedCredentialsMatcher { private RedisTemplate<String, Long> redisTemplate; // 使用RedisTemplate操作Long类型值 private static final Long RETRY_LIMIT_NUM = 4L; // 允许的重试次数阈值 private static final long LOCK_TIME = 10; // 锁定时间(分钟) private static final String RETRY_COUNT_KEY_PREFIX = "LOGIN_RETRY:"; // Redis键前缀 public RetryLimitCredentialsMatcher(String hashAlgorithmName, RedisTemplate<String, Long> redisTemplate) { super(hashAlgorithmName); this.redisTemplate = redisTemplate; } @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { String loginName = (String) token.getPrincipal(); String redisKey = RETRY_COUNT_KEY_PREFIX + loginName; // 1. 获取Redis的Value操作对象 ValueOperations<String, Long> valueOps = redisTemplate.opsForValue(); // 2. 检查用户是否已被锁定 Long currentRetryCount = valueOps.get(redisKey); if (currentRetryCount != null && currentRetryCount > RETRY_LIMIT_NUM) { // 3. 如果已超过限制次数,抛出异常并刷新锁定时间 redisTemplate.expire(redisKey, LOCK_TIME, TimeUnit.MINUTES); throw new ExcessiveAttemptsException("密码错误次数过多,请" + LOCK_TIME + "分钟后再试"); } // 4. 执行密码验证 boolean isMatch = super.doCredentialsMatch(token, info); // 5. 处理验证结果 if (isMatch) { // 登录成功,清除失败计数 redisTemplate.delete(redisKey); } else { // 登录失败,增加失败计数 incrementFailureCount(redisKey); } return isMatch; } /** * 增加登录失败次数计数 * @param key Redis键 */ private void incrementFailureCount(String key) { ValueOperations<String, Long> valueOps = redisTemplate.opsForValue(); // 使用INCR原子操作增加计数,如果key不存在则会先初始化为0再增加 Long newCount = valueOps.increment(key); // 如果是第一次失败(即增加后的值为1),设置过期时间 if (newCount != null && newCount == 1) { redisTemplate.expire(key, LOCK_TIME, TimeUnit.MINUTES); } } } 2025-09-02 16:41:57.088 ERROR 12660 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.shiro.authc.IncorrectCredentialsException: Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - admin, rememberMe=false] did not match the expected credentials.] with root cause org.apache.shiro.authc.IncorrectCredentialsException: Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - admin, rememberMe=false] did not match the expected credentials.
最新发布
09-03
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值