自定义JWT插件转化算法

说明

  • 用户可以自定义JWT插件中转化算法

扩展

转化算法的默认实现为 org.apache.shenyu.plugin.jwt.strategy.DefaultJwtConvertStrategy,采用的是SPI机制进行扩展,步骤如下:

  1. 实现接口org.apache.shenyu.plugin.jwt.strategy.JwtConvertStrategy

    ``` /**

    • Represents a conversion strategy that convert jwt to some attributes of
    • serverWebExchange, especially attributes of the request header. */ @SPI public interface JwtConvertStrategy {
  1. /**
  2. * HandleJson needs to be parsed into jwtRuleHandle in order to
  3. * specify how to convert jwt.
  4. *
  5. * @param handleJson handleJson from rule
  6. * @return jwtRuleHandle
  7. */
  8. JwtRuleHandle parseHandleJson(String handleJson);
  9. /**
  10. * Converts jwt to some attributes of serverWebExchange based on jwtRuleHandle.
  11. *
  12. * @param jwtRuleHandle jwtRuleHandle
  13. * @param exchange exchange
  14. * @param jwtBody jwtBody
  15. * @return serverWebExchange
  16. */
  17. ServerWebExchange convert(JwtRuleHandle jwtRuleHandle, ServerWebExchange exchange, Map<String, Object> jwtBody);
  18. }
  19. ```
  20. ```
  21. @Join
  22. public class CustomJwtConvertStrategy implements JwtConvertStrategy {
  23. @Override
  24. public CustomJwtRuleHandle parseHandleJson(final String handleJson) {
  25. return GsonUtils.getInstance().fromJson(handleJson, CustomJwtRuleHandle.class);
  26. }
  27. @Override
  28. public ServerWebExchange convert(final JwtRuleHandle jwtRuleHandle, final ServerWebExchange exchange, final Map<String, Object> jwtBody) {
  29. final CustomJwtRuleHandle customJwtRuleHandle = (CustomJwtRuleHandle) jwtRuleHandle;
  30. String customConvert = customJwtRuleHandle.getCustomConvert();
  31. ServerHttpRequest modifiedRequest =
  32. exchange.getRequest().mutate().header("custom", customConvert).build();
  33. return exchange.mutate().request(modifiedRequest).build();
  34. }
  35. }
  36. ```
  1. 配置SPI

    1. custom=org.apache.shenyu.plugin.jwt.strategy.CustomJwtConvertStrategy

说明:系统会根据JwtRuleHandlehandleType参数来使用不同转化策略,比如下面的JwtRuleHandle系统会使用我们上面自定义的CustomJwtConvertStrategy。(注意:handleTypedefault或者不存在handleType属性,系统默认使用DefaultJwtConvertStrategy

  1. {
  2. "handleType":"custom",
  3. "customConvert":"customConvert"
  4. }

案例代码可查看org.apache.shenyu.plugin.jwt.strategy.CustomJwtConvertStrategy