问题描述:
shiro配置多realm时出现的问题。
org.apache.shiro.authc.AuthenticationException: Authentication token of type [class com.finn.springboot002.common.config.shiro.JwtToken] could not be authenticated by any configured realms. Please ensure that at least one realm can authenticate these tokens.
我的理解是,该token没有配置的realm来认证。请你最少得整一个。百度许久得到解决办法!如下:
解决方案:
token错误或失效也会引起该错误。确保token正确但还会引起错误的话,下面是一种解决方案。
配置自定义证书匹配器
package com.finn.springboot002.common.config.shiro;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.finn.springboot002.common.utils.JwtUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 自定义证书匹配器
*/
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();
try {
Algorithm algorithm = Algorithm.HMAC256(JwtUtils.SECRET);
JWTVerifier verifier = JWT.require(algorithm).withClaim("username", JwtUtils.getUsername(token)).build();
verifier.verify(token);
return true;
} catch (JWTVerificationException e) {
logger.error(e.getMessage());
return false;
}
}
}
在shiroconfig配置类中的JwtRealm bean增加如下配置
/**
* JwtRealm 配置自定义匹配器
*/
@Bean
public JwtRealm jwtRealm() {
JwtRealm jwtRealm = new JwtRealm();
CredentialsMatcher credentialsMatcher = new JwtCredentialsMatcher();
jwtRealm.setCredentialsMatcher(credentialsMatcher);
return jwtRealm;
}
OK,问题解决!
感谢大佬:https://blog.csdn.net/pengjunlee/article/details/95600843