聊聊dubbo-go的TokenFilter

/ distributedgolang / 没有评论 / 50浏览

本文主要研究一下dubbo-go的TokenFilter

TokenFilter

dubbo-go-v1.4.2/filter/filter_impl/token_filter.go

const (
	// TOKEN ...
	TOKEN = "token"
)

func init() {
	extension.SetFilter(TOKEN, GetTokenFilter)
}

// TokenFilter ...
type TokenFilter struct{}

GetTokenFilter

dubbo-go-v1.4.2/filter/filter_impl/token_filter.go

// GetTokenFilter ...
func GetTokenFilter() filter.Filter {
	return &TokenFilter{}
}

Invoke

dubbo-go-v1.4.2/filter/filter_impl/token_filter.go

// Invoke ...
func (tf *TokenFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
	invokerTkn := invoker.GetUrl().GetParam(constant.TOKEN_KEY, "")
	if len(invokerTkn) > 0 {
		attachs := invocation.Attachments()
		remoteTkn, exist := attachs[constant.TOKEN_KEY]
		if exist && strings.EqualFold(invokerTkn, remoteTkn) {
			return invoker.Invoke(ctx, invocation)
		}
		return &protocol.RPCResult{Err: perrors.Errorf("Invalid token! Forbid invoke remote service %v method %s ",
			invoker, invocation.MethodName())}
	}

	return invoker.Invoke(ctx, invocation)
}

OnResponse

dubbo-go-v1.4.2/filter/filter_impl/token_filter.go

// OnResponse ...
func (tf *TokenFilter) OnResponse(ctx context.Context, result protocol.Result, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
	return result
}

小结

TokenFilter的Invoke方法读取constant.TOKEN_KEY的值invokerTkn,在该值有配置的前提下,从invocation.Attachments()获取对应的remoteTkn,之后对比invokerTkn与remoteTkn,相等则执行invoker.Invoke(ctx, invocation),否则返回错误结果

doc