You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 
SOP/doc/docs/files/10089_自定义校验token.md

1.7 KiB

自定义校验token(2.5.0)

从2.5.0开始在@ApiMapping注解中新增了一个属性needToken,用来告诉网关是否校验token

/**
* 是否需要appAuthToken,设置为true,网关端会校验token是否存在
*/
boolean needToken() default false;

使用方式:

@ApiMapping(value = "story.token.get", needToken = true/* 设置true,网关会校验token是否存在 */)
public StoryResult token(StoryParam story) {
    OpenContext openContext = ServiceContext.getCurrentContext().getOpenContext();
    String appAuthToken = openContext.getAppAuthToken();
    StoryResult result = new StoryResult();
    result.setName("appAuthToken:" + appAuthToken);
    return result;
}

指定了needToken=true后,网关会判断客户端是否传了app_auth_token参数,没有传则返回错误信息。

网关默认简单校验参数值是否存在,如果要校验有效性,需要自己实现。

自己实现步骤:

  • 在ZuulConfig类中重写doAfter方法
  • 设置ApiConfig中的tokenValidator属性

TokenValidator是一个函数式接口,可以直接使用Lambda表达式,示例代码如下:

public class ZuulConfig extends AlipayZuulConfiguration {

    @Override
    protected void doAfter() {
        ApiConfig.getInstance().setTokenValidator(apiParam -> {
            // 获取客户端传递过来的token
            String token = apiParam.fetchAccessToken();
            if (StringUtils.isBlank(token)) {
                return false;
            }
            // TODO: 校验token有效性,可以从redis中读取
            
            // 返回true表示这个token真实、有效
            return true;
        });
    }
}