Spring Boot Basic Auth浏览器正常 Postman返回HTML无数据
Spring Boot Basic Auth 接口Postman返回HTML问题修复
核心原因
当前Spring Security配置默认同时启用HTTP Basic认证与表单登录,未对API路径做鉴权规则隔离,触发逻辑冲突:
- 浏览器请求默认携带
Accept: text/html头,Spring Security自动匹配表单登录流程,跳转默认登录页,认证通过后重定向回目标接口,和观察到的浏览器访问表现一致 - Postman请求返回HTML响应的直接诱因有三个:
- 请求未携带
Accept: application/json请求头,Spring Security内容协商机制默认返回HTML类型响应 - 未显式关闭API路径下的表单登录拦截,安全过滤器链优先匹配表单登录逻辑,未正确解析传入的Basic Auth请求头
- Postman默认开启自动重定向,认证头在重定向过程中被丢弃,最终拿到登录页的HTML内容,状态码显示200 OK
- 请求未携带
修复步骤
重写Spring Security配置类,针对
/api/**前缀的接口单独定义鉴权规则,显式开启HTTP Basic认证,根据请求类型区分响应逻辑,接口请求未认证时直接返回401,不跳转登录页
参考配置代码(适配Spring Boot 3.x / Spring Security 6.x版本):import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/login", "/static/**", "/error").permitAll() .requestMatchers("/api/**").authenticated() .anyRequest().authenticated() ) .formLogin(form -> form.permitAll()) .httpBasic(basic -> basic .authenticationEntryPoint((request, response, authException) -> { String acceptHeader = request.getHeader("Accept"); // 接口请求直接返回401状态,不跳转登录页 if (acceptHeader != null && acceptHeader.contains("application/json")) { response.setStatus(401); response.setContentType("application/json;charset=UTF-8"); response.getWriter().write("{\"code\":401,\"message\":\"未授权访问\"}"); return; } // 普通页面请求走默认跳转登录页逻辑 response.sendRedirect("/login"); }) ) .csrf(csrf -> csrf.disable()); return http.build(); } }如果使用Spring Boot 2.x版本,把
authorizeHttpRequests换成authorizeRequests,配置逻辑不变。调整Postman请求配置
- 在请求Headers栏手动添加
Accept: application/json,明确告知服务端需要JSON格式响应 - 打开Postman请求的Settings标签,关闭
Automatically follow redirects选项;同时在Authorization标签页确认Add authorization data to选项选择Request Headers,不要选Request URL - 确认填入的账号密码合法:如果没有自定义用户配置,Spring Boot启动时会在日志中打印默认临时密码,格式为
Using generated security password: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,不要使用错误密码测试。
- 在请求Headers栏手动添加
校验配置
修改配置后重启服务,按Ctrl+Alt+C调出Postman控制台,发起请求后查看实际发送的请求头,确认存在Authorization: Basic 拼接后的凭证字符串头信息,此时接口会正常返回JSON格式的用户列表数据,不会再返回HTML内容。
内容的提问来源于stack exchange,提问作者DarkBot
相关产品推荐
相关产品推荐

