I am developing an API using filter routes to check the authorization with token bearier. The API itself work well if I test it in postman. But when i run the plumber documentation by Swagger, this eror always appear. I dont want to use the authorization on swagger routes.
I have put the route condition based on solution answered by @meztez (post page), but swagger doesn't seem to be able to continue to the next endpoint with plumber::forward() function.
Is there something wrong with my script? Please welcome your input and suggestions.
This is the screenshoot of swagger documentation.
This is the script I developed.
library(jose)
library(plumber)
library(jsonlite)
#Load secret_key
{
readRenviron(".Renviron")
secret_key <- Sys.getenv('SECRET_KEY')
}
#' @filter checkAuthentication
function(req, res){
if (req$PATH_INFO %in% c("/__docs__/", "/__swagger__/", "/openapi.json")) {
print('Run for document!')
plumber::forward() #no need authentication for api-document, continue
}
#filter
if (is.null(req$HTTP_TOKEN)){
res$status <- 401
return(list(error = 'Token not found in request header'))
}
token = req$HTTP_TOKEN
tryCatch(
expr = {
#decode
payload <- jwt_decode_hmac(token, secret = secret_key)
print(payload)
#Create a response message
plumber::forward() #User authenticated, continue
},
error = function(e){
#Create a message
msg <- "Signature verification failed!"
res$status <- 401 # Bad request
return(list(message=msg))
}
)
}
#* Scoring/predict data using model_scoring
#* @get /hit_model
function(req,res) {
print('Welcome!')
return(list(message=paste('You have an authorized. Ready to Predict Model.')))
}
Here is my R environment:
> sessionInfo()
R version 4.2.0 (2022-04-22 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 22631)
Matrix products: default
locale:
[1] LC_COLLATE=English_Indonesia.utf8
[2] LC_CTYPE=English_Indonesia.utf8
[3] LC_MONETARY=English_Indonesia.utf8
[4] LC_NUMERIC=C
[5] LC_TIME=English_Indonesia.utf8
attached base packages:
[1] stats graphics grDevices utils datasets
[6] methods base
other attached packages:
[1] jsonlite_1.8.7 plumber_1.2.2 jose_1.2.0
[4] openssl_2.1.1
loaded via a namespace (and not attached):
[1] Rcpp_1.0.11 ps_1.7.5
[3] later_1.3.1 R6_2.5.1
[5] lifecycle_1.0.4 magrittr_2.0.3
[7] stringi_1.7.12 rlang_1.1.2
[9] cli_3.6.1 swagger_3.33.1
[11] rstudioapi_0.15.0 promises_1.2.1
[13] callr_3.7.3 webutils_1.1
[15] tools_4.2.0 compiler_4.2.0
[17] processx_3.8.2 askpass_1.2.0


