TokenFilter implements Filter { @Override public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { String token = invoker.getUrl().getParameter(TOKEN_KEY); if (ConfigUtils.isNotEmpty(token)) { Class<?> serviceType = invoker.getInterface(); Map<String, Object> attachments = inv.getObjectAttachments(); String remoteToken = (attachments == null ? null : (String) attachments.get(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); }  @Override Result invoke(Invoker<?> invoker, Invocation inv);  }
@Test public void testInvokeWithToken() throws Exception { String token = "token"; Invoker invoker = Mockito.mock(Invoker.class); URL url = URL.valueOf("test: when(invoker.getUrl()).thenReturn(url); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); Map<String, Object> attachments = new HashMap<>(); attachments.put(TOKEN_KEY, token); Invocation invocation = Mockito.mock(Invocation.class); when(invocation.getObjectAttachments()).thenReturn(attachments); Result result = tokenFilter.invoke(invoker, invocation); Assertions.assertEquals("result", result.getValue()); }
@Test public void testInvokeWithWrongToken() throws Exception { Assertions.assertThrows(RpcException.class, () -> { String token = "token"; Invoker invoker = Mockito.mock(Invoker.class); URL url = URL.valueOf("test: when(invoker.getUrl()).thenReturn(url); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); Map<String, Object> attachments = new HashMap<>(); attachments.put(TOKEN_KEY, "wrongToken"); Invocation invocation = Mockito.mock(Invocation.class); when(invocation.getObjectAttachments()).thenReturn(attachments); tokenFilter.invoke(invoker, invocation); }); }
@Test public void testInvokeWithoutToken() throws Exception { Assertions.assertThrows(RpcException.class, () -> { String token = "token"; Invoker invoker = Mockito.mock(Invoker.class); URL url = URL.valueOf("test: when(invoker.getUrl()).thenReturn(url); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); Invocation invocation = Mockito.mock(Invocation.class); tokenFilter.invoke(invoker, invocation); }); }