http 增加对token的校验

This commit is contained in:
anlicheng 2025-11-28 15:40:27 +08:00
parent 2de2bd6431
commit 9c10ccbfe0
2 changed files with 19 additions and 8 deletions

View File

@ -69,8 +69,15 @@ handle_call(get_stat, _From, State = #state{buffer = Buffer}) ->
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}).
handle_cast({forward, Metric}, State = #state{buffer = Buffer}) ->
NBuffer = endpoint_buffer:append(Metric, Buffer),
handle_cast({forward, Metric}, State = #state{buffer = Buffer, endpoint = #endpoint{config = #http_endpoint{token = Token}}}) ->
Tuple = case is_binary(Token) andalso Token /= <<>> of
true ->
Sign = iot_util:sha256(erlang:iolist_to_binary([Token, Metric, Token])),
{Metric, Sign};
false ->
{Metric, <<>>}
end,
NBuffer = endpoint_buffer:append(Tuple, Buffer),
{noreply, State#state{buffer = NBuffer}};
handle_cast(cleanup, State = #state{buffer = Buffer}) ->
@ -83,10 +90,14 @@ handle_cast(cleanup, State = #state{buffer = Buffer}) ->
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}).
handle_info({next_data, Id, Metric}, State = #state{buffer = Buffer, endpoint = #endpoint{config = #http_endpoint{url = Url}}}) ->
Headers = [
{<<"Content-Type">>, <<"application/json">>}
],
handle_info({next_data, Id, {Metric, Sign}}, State = #state{buffer = Buffer, endpoint = #endpoint{config = #http_endpoint{url = Url}}}) ->
BaseHeaders = [{<<"Content-Type">>, <<"application/json">>}],
ExtraHeaders = if
Sign =:= <<>> -> [];
true -> [{<<"X-Signature">>, Sign}]
end,
Headers = BaseHeaders ++ ExtraHeaders,
case hackney:request(post, Url, Headers, Metric) of
{ok, 200, _, ClientRef} ->
{ok, RespBody} = hackney:body(ClientRef),

View File

@ -113,13 +113,13 @@ assert_call(true, Fun) ->
assert_call(false, _) ->
ok.
-spec sha256(Str :: string() | binary()) -> string().
-spec sha256(Str :: string() | binary()) -> binary().
sha256(Str) when is_list(Str) ->
sha256(unicode:characters_to_binary(Str));
sha256(Bin) when is_binary(Bin) ->
HashBin = crypto:hash(sha256, Bin),
HexStr = lists:flatten([io_lib:format("~2.16.0B", [B]) || B <- binary:bin_to_list(HashBin)]),
string:lowercase(HexStr).
list_to_binary(string:lowercase(HexStr)).
-spec md5(Str :: binary()) -> binary().
md5(Str) when is_binary(Str) ->