Files
SOP/doc/docs/files/10089_自定义校验token.md
tanghc 0fea955db9 4.0
2020-07-28 18:21:01 +08:00

55 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 自定义校验token
`@Open`注解中有一个属性`needToken`用来告诉网关是否校验token
```java
/**
* 是否需要appAuthToken设置为true网关端会校验token是否存在
*/
boolean needToken() default false;
```
使用方式:
```java
@ApiOperation(value="传递token", notes = "传递token")
@Open(value = "story.get.token", needToken = true/* 设置true网关会校验token是否存在 */)
@RequestMapping("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表达式示例代码如下
```java
@Component
public class MyConfig {
@PostConstruct
public void after() {
ApiConfig.getInstance().setTokenValidator(apiParam -> {
// 获取客户端传递过来的token
String token = apiParam.fetchAccessToken();
return !StringUtils.isBlank(token);
// TODO: 校验token有效性可以从redis中读取
// 返回true表示这个token真实、有效
});
}
}
```