could not be authenticated by any configured realms. 。Please ensure that at least one realm问题

问题描述:

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值