# HG changeset patch # User Kim Alvefur # Date 1577759866 -3600 # Node ID f88e07630e4e24f11a93955a70cd4b4c1e25b9ff # Parent d59fb4dcf1008b34c4a1d1f80513c0efd1254896 mod_rest: Add support for simple Bearer token auth Token specified in config diff -r d59fb4dcf100 -r f88e07630e4e mod_rest/README.markdown --- a/mod_rest/README.markdown Mon Dec 30 07:22:15 2019 +0100 +++ b/mod_rest/README.markdown Tue Dec 31 03:37:46 2019 +0100 @@ -12,13 +12,11 @@ # Usage -Note that there is currently **no authentication**, so be careful with -exposing the API endpoint to the Internet. - ## Enabling ``` {.lua} Component "rest.example.net" "rest" +rest_credentials = "Bearer dmVyeSBzZWNyZXQgdG9rZW4K" ``` ## Sending stanzas @@ -30,6 +28,7 @@ ``` {.sh} curl https://prosody.example:5281/rest \ + --oauth2-bearer dmVyeSBzZWNyZXQgdG9rZW4K \ -H 'Content-Type: application/xmpp+xml' \ --data-binary ' Hello! @@ -45,6 +44,7 @@ ``` {.sh} curl https://prosody.example:5281/rest \ + --oauth2-bearer dmVyeSBzZWNyZXQgdG9rZW4K \ -H 'Content-Type: application/xmpp+xml' \ --data-binary ' @@ -62,6 +62,7 @@ ``` {.lua} Component "rest.example.net" "rest" +rest_credentials = "Bearer dmVyeSBzZWNyZXQgdG9rZW4K" rest_callback_url = "http://my-api.example:9999/stanzas" ``` diff -r d59fb4dcf100 -r f88e07630e4e mod_rest/mod_rest.lua --- a/mod_rest/mod_rest.lua Mon Dec 30 07:22:15 2019 +0100 +++ b/mod_rest/mod_rest.lua Tue Dec 31 03:37:46 2019 +0100 @@ -13,9 +13,23 @@ local allow_any_source = module:get_host_type() == "component"; local validate_from_addresses = module:get_option_boolean("validate_from_addresses", true); +local secret = assert(module:get_option_string("rest_credentials"), "rest_credentials is a required setting"); +local auth_type = assert(secret:match("^%S+"), "Format of rest_credentials MUST be like 'Bearer secret'"); +assert(auth_type == "Bearer", "Only 'Bearer' is supported in rest_credentials"); + +-- Bearer token +local function check_credentials(request) + return request.headers.authorization == secret; +end local function handle_post(event) local request, response = event.request, event.response; + if not request.headers.authorization then + response.headers.www_authenticate = ("%s realm=%q"):format(auth_type, module.host.."/"..module.name); + return 401; + elseif not check_credentials(request) then + return 401; + end if request.headers.content_type ~= "application/xmpp+xml" then return errors.new({ code = 415, text = "'application/xmpp+xml' expected" }); end