如何为Azure HttpTrigger Java函数添加Basic Auth认证
为Azure Java HTTP Trigger函数添加Basic Auth认证
你可以通过两种方式实现Basic Auth认证,优先推荐使用Azure平台内置的认证机制,其次可以在代码层面手动实现验证逻辑。
方案一:使用Azure Function App内置认证(推荐)
这种方式无需修改代码,直接通过Azure平台配置实现,更安全且易于维护。
调整函数授权级别
将代码中@HttpTrigger注解的authLevel从AuthorizationLevel.ANONYMOUS改为AuthorizationLevel.FUNCTION:@HttpTrigger( name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION)配置App Service基础认证
登录Azure门户,找到你的Function App:- 进入左侧菜单的Authentication选项卡
- 点击Add identity provider,选择Basic Authentication
- 设置允许的用户名和密码(支持Azure AD用户或本地账户)
- 保存配置后,函数会自动拦截未通过Basic Auth验证的请求,返回
401 Unauthorized
方案二:代码层面手动实现Basic Auth验证
如果需要自定义验证逻辑,可以在函数代码中手动解析并验证Authorization头:
准备Base64处理能力
Java 8及以上版本自带java.util.Base64,可直接使用;若使用低版本,需在pom.xml中添加依赖:<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.15</version> </dependency>修改函数代码添加验证逻辑
更新run方法,先完成身份验证,再处理原有业务逻辑: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; import java.util.Base64; /** * Azure Functions with HTTP Trigger. */ public class Function { // 建议从环境变量读取,不要硬编码 private static final String VALID_USERNAME = System.getenv("AUTH_USERNAME"); private static final String VALID_PASSWORD = System.getenv("AUTH_PASSWORD"); @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."); // 验证Basic Auth String authHeader = request.getHeaders().get("Authorization"); if (!isValidBasicAuth(authHeader)) { return request.createResponseBuilder(HttpStatus.UNAUTHORIZED) .header("WWW-Authenticate", "Basic realm=\"Azure Function\"") .body("Unauthorized: Invalid credentials") .build(); } // 原有业务逻辑 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(); } } // Basic Auth验证工具方法 private boolean isValidBasicAuth(String authHeader) { if (authHeader == null || !authHeader.startsWith("Basic ")) { return false; } // 解码Base64凭证 String base64Credentials = authHeader.substring("Basic ".length()).trim(); String credentials = new String(Base64.getDecoder().decode(base64Credentials)); final String[] values = credentials.split(":", 2); if (values.length != 2) { return false; } String username = values[0]; String password = values[1]; return VALID_USERNAME.equals(username) && VALID_PASSWORD.equals(password); } }优化建议
- 不要硬编码用户名密码,可在Azure Function的Application Settings中添加环境变量
AUTH_USERNAME和AUTH_PASSWORD - 可将验证逻辑封装为独立工具类,方便多个函数复用
- 不要硬编码用户名密码,可在Azure Function的Application Settings中添加环境变量
内容的提问来源于stack exchange,提问作者Venkatesh
相关产品推荐
相关产品推荐

