Spring Boot应用浏览器Basic Authentication正常,Postman中失效
解决Postman使用Basic Authentication跳转登录页的问题
你的Spring Boot Web应用在浏览器中运行正常:未登录时访问任意URL会跳转至登录页,登录后可正常访问所有URL,Basic Authentication功能正常。但使用Postman选择Basic Authentication并提供用户名密码发送GET或其他请求时,始终被跳转回登录页。
原因分析
当前安全配置仅启用了表单登录(formLogin),未配置HTTP Basic认证支持。Postman发送的Basic Auth请求携带的是Authorization: Basic xxx头信息,Spring Security默认不会处理这种认证方式,依然会触发表单登录的跳转逻辑,导致返回登录页。
解决方案
在SecurityFilterChain的配置中添加HTTP Basic认证的支持,同时保留表单登录以兼容浏览器访问。修改后的filterChain方法如下:
@Bean protected SecurityFilterChain filterChain(HttpSecurity http, DaoAuthenticationProvider authenticationProvider) throws Exception { http.authorizeHttpRequests(authorize -> authorize .requestMatchers( new AntPathRequestMatcher("/registration**"), new AntPathRequestMatcher("/js/**"), new AntPathRequestMatcher("/css/**"), new AntPathRequestMatcher("/img/**")) .permitAll() .anyRequest().authenticated()) // 启用表单登录,兼容浏览器访问流程 .formLogin(login -> login.loginPage("/login").permitAll()) // 启用HTTP Basic认证,支持Postman等工具的Basic Auth请求 .httpBasic(Customizer.withDefaults()) .logout(logout -> logout .invalidateHttpSession(true) .clearAuthentication(true) .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/login?logout") .permitAll()); http.authenticationProvider(authenticationProvider); return http.build(); }
补充说明
- 添加
.httpBasic(Customizer.withDefaults())后,Spring Security会识别并处理Authorization: Basic头的认证请求,认证成功后直接返回请求资源,不再跳转登录页。 - 表单登录配置依然保留,浏览器访问时仍可使用原有登录流程,不影响现有功能。
内容的提问来源于stack exchange,提问作者fordprefect
相关产品推荐
相关产品推荐

