You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中如何从Basic Auth请求获取账号密码(非Spring Security方案)

Spring Boot 无Spring Security场景下提取Basic Auth账号密码实现

HTTP Basic Auth的认证信息固定存放在Authorization请求头中,格式为Basic <base64编码的"账号:密码"字符串>,你可以直接在Controller层按以下逻辑提取凭据,全程不需要引入任何安全框架:

核心实现步骤

  • 从当前请求对象中读取Authorization请求头的值
  • 做基础格式校验:判断请求头是否存在、是否以Basic 作为固定前缀,不符合规则直接返回401未授权响应
  • 截取前缀后的Base64字符串,做Base64解码得到原始的账号:密码明文字符串
  • 按第一个冒号拆分字符串,前半段为登录账号,后半段为登录密码
  • 拿到账号密码后自行对接你的账号校验、权限判断逻辑即可

可直接复用的代码示例

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@RestController
public class BizController {

    // 自定义401异常,避免格式非法时返回500状态码
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public static class UnauthorizedException extends RuntimeException {
        public UnauthorizedException(String msg) {
            super(msg);
        }
    }

    @GetMapping("/api/biz")
    public String callBizApi(HttpServletRequest request) {
        // 1. 读取认证请求头
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Basic ")) {
            throw new UnauthorizedException("未携带合法认证信息");
        }

        try {
            // 2. 截取Base64段并解码,用JDK自带工具即可,无需额外引包
            String base64Credentials = authHeader.substring("Basic ".length()).trim();
            byte[] decodedBytes = Base64.getDecoder().decode(base64Credentials);
            String rawCredentials = new String(decodedBytes, StandardCharsets.UTF_8);

            // 3. 拆分账号密码,限制只拆2段,避免密码本身包含冒号导致拆分错误
            String[] accountPair = rawCredentials.split(":", 2);
            if (accountPair.length != 2) {
                throw new UnauthorizedException("认证信息格式非法");
            }
            String username = accountPair[0];
            String password = accountPair[1];

            // 此处编写你自己的账号密码校验逻辑
            // boolean loginValid = yourLoginCheckMethod(username, password);

            return "接口访问成功,当前登录账号:" + username;
        } catch (IllegalArgumentException e) {
            // 捕获Base64解码失败的异常场景
            throw new UnauthorizedException("认证信息编码非法");
        }
    }
}

落地注意事项

  • 如果多个接口都需要做认证,建议把这段解析逻辑抽成公共的Handler拦截器或者参数解析器,不用在每个Controller方法中重复编写解析代码
  • Basic Auth的Base64编码不等于加密,生产环境必须搭配HTTPS协议使用,避免凭据被中间人窃听
  • 认证失败的响应不要返回具体的错误原因(比如是编码错了还是密码错了),统一返回模糊的未授权提示,降低被暴力破解的风险

内容的提问来源于stack exchange,提问作者Alexander Tukanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.04 16:15:42