springboot集成shiro时认证出现报错Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToke

SpringBoot整合Shiro登录认证错误排查
本文介绍了SpringBoot集成Shiro时可能出现的登录认证错误,详细梳理了Shiro密码验证的流程,包括controller中的登录处理和realm中的doGetAuthenticationInfo方法。错误通常源于未设置加密算法、加密参数不匹配或配置文件错误。特别是配置文件问题,如忘记设置customerRealm.setCredentialsMatcher(credentialsMatcher())会导致密码匹配失败。

shiro密码验证的大致流程:

1. controller中login的时候

        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        try {
            SecurityUtils.getSubject().login(token);
        }

2. realm中调用doGetAuthenticationInfo

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
        String username = (String)authToken.getPrincipal();
        User user = userService.getUserByAccount(username);
        if (user == null) {
            throw new UnknownAccountException();
        }

        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现
        /**
         * 这里传入的user信息,只是从数据库中查询到的结果,
         * shiro会将token中的明文,按照配置中的加密方式进行加密,然后进行匹配。
         * 有些教程,在这里将明文的pwd加密后传入,是没有必要的
         */
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getAccount(),
                user.getPassword(),
//                ByteSource.Util.bytes(user.getAccount() + user.getSalt()),
                ByteSource.Util.bytes(user.getSalt()),
                getName()
        );

        /**
         * 写入session,但是移除password信息
         */
        user.setPassword("");
        user.setSalt("");
        SecurityUtils.getSubject().getSession().setAttribute(SessionConstant.SESS_USER_INFO, user);
        return authenticationInfo;
    }

需要注意的是,很多人认为需要在这里传入加密后的密码,进行匹配,这是个误解。

如果出现报错Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken,出现这种情况是因为密码验证不通过,原因有:

1. 没有设置加密算法,却进行加密匹配

2. 密码虽然加密,但是加密算法、迭代次数与配置文件中不一致

public HashedCredentialsMatcher credentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(2);
        // true 密码加密用hex编码; false 用base64编码
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }

3. 排除1和2后,很可能就是配置文件有问题了

针对情况3,我遇到过的情况如下:

忘记设置customerRealm.setCredentialsMatcher(credentialsMatcher())导致密码匹配出错

@Bean
    public CustomerRealm customerRealm() {
        CustomerRealm customerRealm = new CustomerRealm();
        /**
         * 密文匹配的时候,这里需要设置credentialsMatcher(),否则无法匹配
         */
        customerRealm.setCredentialsMatcher(credentialsMatcher());
        return customerRealm;
    }

 

@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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值