How to add Basic Auth for Azure HttpTrigger Java Function

321 Views Asked by At

I have created a sample Azure HTTP Trigger Java Function using Visual Studio Code and Deployed it to Azure Function App. Now it is Working Fine in Postman without authorization

Postman Basic Auth Screenshot

enter image description here

package com.function;

import com.microsoft.azure.functions.ExecutionContext;
import com.microsoft.azure.functions.HttpMethod;
import com.microsoft.azure.functions.HttpRequestMessage;
import com.microsoft.azure.functions.HttpResponseMessage;
import com.microsoft.azure.functions.HttpStatus;
import com.microsoft.azure.functions.annotation.AuthorizationLevel;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.annotation.HttpTrigger;

import java.util.Optional;

/**
 * Azure Functions with HTTP Trigger.
 */
public class Function {
    /**
     * This function listens at endpoint "/api/HttpExample". Two ways to invoke it using "curl" command in bash:
     * 1. curl -d "HTTP Body" {your host}/api/HttpExample
     * 2. curl "{your host}/api/HttpExample?name=HTTP%20Query"
     */
    @FunctionName("HttpExample")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req",
                methods = {HttpMethod.GET, HttpMethod.POST},
                authLevel = AuthorizationLevel.ANONYMOUS)
                HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {
        context.getLogger().info("Java HTTP trigger processed a request.");

        // Parse query parameter
        final String query = request.getQueryParameters().get("name");
        final String name = request.getBody().orElse(query);

  

          if (name == null) {
                return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("Please pass a name on the query string or in the request body").build();
            }

     else {
                    return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();
        
                }
        }
    }

Now I need to add basic auth to that Function. How do I accomplish this?

1

There are 1 best solutions below

2
On
  • For Authorization to your function app, one of the methods you can use is the Authorization Level keys appending at the end of the Function URL.*

enter image description here

  • You can find the Host Keys and System Keys at the App Keys in Azure Function App.

enter image description here

Refer to this MSDOC and this SO Thread for more information on configuring the Authentication and Authorization for securing the Azure Functions.