org.apache.shiro.authc.IncorrectCredentialsException: did not match the expected credentials

SpringBoot整合Shiro+JWT+Redis
本文介绍了一个SpringBoot项目中整合Shiro、JWT和Redis实现授权认证及缓存功能的过程。针对执行登录操作时出现的凭证不匹配错误,通过自定义证书匹配器解决了该问题。

项目场景

本demo是springboot整合shiro+jwt+redis实现授权认证以及缓存功能。

说明

进行授权测试时,一直未得到理想结果(返回自定义的异常信息),也未报错。Debug发现
执行subject.login(token);报如下错误:

did not match the expected credentials
//与预期的凭证不匹配

原因猜测:在执行是ShiroRealm的doGetAuthenticationInfo方法,最后的认证问题。

/**
* principal 认证的标识:可以是username/id,也可以是实体对象
* redentials 证书,凭证。可以是密码
* realmName realm的name 可以使用 getName()直接获得
* user为实体对象,最好是username或id
*/
 return new SimpleAuthenticationInfo(user,user,getName());;

debug查看认证策略:

1.无限F8。找到getAuthenticationInfo发现里面主要方法在
assertCredentialsMatch(token, info);在这里插入图片描述
2.点进去发现异常信息所在:
在这里插入图片描述
3.发现了doCredentialsMatch方法返回boolean类型,并且进行自定义equals方法比较,看到这我就知道问题所在了,凭证匹配失败!!!
我用的是token令牌,不需要这么比较。再想到之前项目要自定义凭证比较器,突然想骂自己!
在这里插入图片描述
如果未使用这种token令牌相关的比较,一般都是密码比对失败,比如你加密规则不一致等问题。

问题解决

1.自定义证书匹配器

/**
 * 自定义证书匹配器
 */
public class JwtCredentialsMatcher implements CredentialsMatcher {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean doCredentialsMatch(AuthenticationToken authToken, AuthenticationInfo info) {

        String token = authToken.getPrincipal().toString();
        //验证正确性和时效性
        return JwtUtils.verify(token, JwtUtils.getUsername(token), JwtUtils.SECRET) && !JwtUtils.isTokenExpired(token);
    }
}

shiroConfig中进行配置

    @Bean
    public ShiroRealm shiroRealm() {
        ShiroRealm shiroRealm = new ShiroRealm();
        //增加下两行
        CredentialsMatcher credentialsMatcher = new JwtCredentialsMatcher();
        shiroRealm.setCredentialsMatcher(credentialsMatcher);
        return shiroRealm;
    }

运行测试,OK!

总结

会抽时间将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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值