在使用shiro集成时往往会遇到如下异常:

Authentication failed for token submission [org.apache.shiro.authc.UsernamePasswordToken - zhihuilijia12, rememberMe=false].  Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).

发生这种异常的原因很多,但有可能只是因为API或业务的使用不当导致的。

比如如下的业务代码:

@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从主体传过来的认证信息中,获取用户名
        String userName = (String)authenticationToken.getPrincipal();

        //通过用户名去到数据库中获取凭证
        String password = userService.getPasswordByUsername(userName);
        if (StringUtils.isEmpty(password)) {
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, password, "costomRealm");
        //设置盐salt
        simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("pyy"));

        return simpleAuthenticationInfo;
    }

有些朋友喜欢在doGetAuthenticationInfo中处理校验的业务逻辑,校验失败时抛出自定义异常等。这就会导致上述异常的出现,主要原因时在该方法中只允许抛出继承自AuthenticationException的异常。

那么,密码等的校验怎么处理?当然是在注册、登录或修改密码的业务Controller或Service层进行校验。校验通过之后,再调用对应的方法来处理,比如:

Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            //登录
        subject.login(usernamePasswordToken);

在校验之后,再调用上述代码,然后直接存储设置校验之后的用户登录信息即可。

其他情况一

比如

正常运行时
org.apache.shiro.authc.AuthenticationException: Authentication failed for token submission [org.apache.shiro.authc.UsernamePasswordToken – wjh, rememberMe=false].  Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).报错

原因:

//构建SecurityManager环境 DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager(); defaultSecurityManager.setRealm(simpleAccountRealm); //看看是不是少了这一行应该是少了一行代码吧。

其他情况二

在自定义的realm类里的方法doGetAuthenticationInfo处理加密验证的时候,password传成明文的了,应该是密文的。注意参数:userName明文, password密文。

ByteSource byteSourceSalt = ByteSource.Util.bytes(user.getSalt());
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, password, byteSourceSalt, getName());
return simpleAuthenticationInfo;

其他情况

当然,因此该问题,还有可能是依赖jar包错误,注入Bean错误等其比较简单而容易忽略的原因引起的。



shiro Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).异常插图

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:https://www.choupangxia.com/2020/12/17/shiro-authenticationexception/