rplumber

How to implement Basic Authentication in R-plumber?


I have an API built in R-Plumber. I want to add basic authentication to this API(i.e. username and password). How can I do that?


Solution

  • I have figured out how to use the req object provided in R Plumber to implement the Basic Authentication.

    We will access Basic Authentication parameters from req$HTTP_AUTHORIZATION, then use base64decode to Decode them into username:password format and then split the string to retrieve the username and password.

    Further, write a function to validate whether the user credentials are valid.

    # Define the authentication logic
    
    auth_basic <- function(username, password) {
      # Check if the username and password are valid
      valid_credentials <- username == "hello" && password == "user123"
      
      # Return TRUE if the credentials are valid, FALSE otherwise
      return(valid_credentials)
    }
    
    
    #* @get /secured
    function(req, res) {
      
      library(base64enc)
      encoded_string <- req$HTTP_AUTHORIZATION  
      encoded_string <- gsub("Basic ", "",encoded_string)
      decoded_string <- rawToChar(base64decode(what = encoded_string))
      username <- strsplit(decoded_string, ":")[[1]][1]
      password <- strsplit(decoded_string, ":")[[1]][2]
      
      cat("decoded string: ", decoded_string, "username: ", username, "password: ", password)
      
      if(is.na(username) | is.na(password)){
        return("credentials not provided")
      }
      
      if(auth_basic(username, password) == FALSE){
        return("invalid credentials")
      }
      
      return("This is a secured endpoint")
    
    }