Dubbo之令牌验证
dubbo版本
- dubbo版本2.6.7
令牌验证
-
通过令牌验证在注册中心控制权限。以决定要不要下发令牌给消费者,可以防止消费者绕过注册中心访问提供者,另外通过注册中心可灵活改变授权方式,而不需修改或升级提供者
-
配置
1. 可以全局设置开启令牌验证 <!--随机token令牌,使用UUID生成--> <dubbo:provider token="true" /> 2. <!--固定token令牌,相当于密码--> <dubbo:provider token="123456" /> 3. 服务级别 <!--随机token令牌,使用UUID生成--> <dubbo:service interface="com.foo.BarService" token="true" /> 4. 服务级别固定token <!--固定token令牌,相当于密码--> <dubbo:service interface="com.foo.BarService" token="123456" />
源码分析
-
TokenFilter
用于校验token@Activate(group = Constants.PROVIDER, value = Constants.TOKEN_KEY) public class TokenFilter implements Filter { @Override public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { //服务提供者的token String token = invoker.getUrl().getParameter(Constants.TOKEN_KEY); if (ConfigUtils.isNotEmpty(token)) { Class<?> serviceType = invoker.getInterface(); Map<String, String> attachments = inv.getAttachments(); //客户端请求带过来的token String remoteToken = attachments == null ? null : attachments.get(Constants.TOKEN_KEY); if (!token.equals(remoteToken)) { throw new RpcException("Invalid token! Forbid invoke remote service " + serviceType + " method " + inv.getMethodName() + "() from consumer " + RpcContext.getContext().getRemoteHost() + " to provider " + RpcContext.getContext().getLocalHost()); } } return invoker.invoke(inv); } }