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

Spring Boot集成PostgreSQL时API调用出现401认证错误求助

Spring Boot CRUD接口401认证错误解决方案

问题描述

我基于Spring Boot实现了基础CRUD接口,使用PostgreSQL数据库。通过Postman调用API时始终返回401认证错误,提示凭据不正确,但数据库凭据无误,且代码此前在PostgreSQL环境下测试正常。

application.properties配置

spring.application.name=users
spring.datasource.url=jdbc:postgresql://localhost:5432/resto
spring.datasource.username=name
spring.datasource.password=pass

spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
debug=true

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

logging.level.org.springframework.data.jpa=DEBUG

已尝试操作

  • 重新创建数据库
  • 在pgAdmin中新建testuser并授予所有表权限
  • 将testuser设为数据库所有者

添加logging.level.org.springframework.security=DEBUG后得到以下日志:

2024-08-24T20:54:35.426+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Detected org.springframework.web.servlet.support.SessionFlashMapManager@7ea8224b
2024-08-24T20:54:35.426+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2024-08-24T20:54:35.426+01:00  INFO 25524 --- [users] [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
2024-08-24T20:54:35.438+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Securing GET /user/find
2024-08-24T20:54:35.443+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-08-24T20:54:35.473+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] o.s.s.w.s.HttpSessionRequestCache        : Saved request http://localhost:8080/user/find?continue to session
2024-08-24T20:54:35.475+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using And [Not [RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@257d3968, matchingMediaTypes=[application/xhtml+xml, image/*, text/html, text/plain], useEquals=false, ignoredMediaTypes=[*/*]]]
2024-08-24T20:54:35.475+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using Or [RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest], And [Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@257d3968, matchingMediaTypes=[text/html], useEquals=false, ignoredMediaTypes=[]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@257d3968, matchingMediaTypes=[application/atom+xml, application/x-www-form-urlencoded, application/json, application/octet-stream, application/xml, multipart/form-data, text/xml], useEquals=false, ignoredMediaTypes=[*/*]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@257d3968, matchingMediaTypes=[*/*], useEquals=true, ignoredMediaTypes=[]]]
2024-08-24T20:54:35.475+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] s.w.a.DelegatingAuthenticationEntryPoint : Match found! Executing org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint@2e590e36
2024-08-24T20:54:35.475+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]
2024-08-24T20:54:35.475+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint@1554e681
2024-08-24T20:54:35.479+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Securing GET /error
2024-08-24T20:54:35.479+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-08-24T20:54:35.480+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] o.s.s.w.s.HttpSessionRequestCache        : Saved request http://localhost:8080/error?continue to session
2024-08-24T20:54:35.480+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using And [Not [RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@257d3968, matchingMediaTypes=[application/xhtml+xml, image/*, text/html, text/plain], useEquals=false, ignoredMediaTypes=[*/*]]]
2024-08-24T20:54:35.480+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using Or [RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest], And [Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@257d3968, matchingMediaTypes=[text/html], useEquals=false, ignoredMediaTypes=[]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@257d3968, matchingMediaTypes=[application/atom+xml, application/x-www-form-urlencoded, application/json, application/octet-stream, application/xml, multipart/form-data, text/xml], useEquals=false, ignoredMediaTypes=[*/*]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@257d3968, matchingMediaTypes=[*/*], useEquals=true, ignoredMediaTypes=[]]]
2024-08-24T20:54:35.480+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] s.w.a.DelegatingAuthenticationEntryPoint : Match found! Executing org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint@2e590e36
2024-08-24T20:54:35.480+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]
2024-08-24T20:54:35.480+01:00 DEBUG 25524 --- [users] [nio-8080-exec-2] s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint@1554e681

解决方案

从日志可以看出,这是Spring Security的Basic认证拦截,和数据库凭据无关,以下是几种解决方式:

1. 使用默认Spring Security凭据访问

如果项目引入了spring-boot-starter-security依赖,Spring Security会自动启用Basic认证:

  • 默认用户名是user
  • 密码会在应用启动时打印在控制台(格式类似:Using generated security password: xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
    在Postman中选择Basic Auth,填入上述用户名和密码即可访问接口。

2. 关闭Spring Security认证(开发环境适用)

如果不需要接口认证,添加一个Security配置类,允许所有请求访问:

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.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
            .csrf(csrf -> csrf.disable()); // POST/PUT/DELETE请求需关闭CSRF防护
        return http.build();
    }
}

3. 配置自定义Spring Security凭据

需要保留Basic认证时,在application.properties中添加自定义用户名密码:

spring.security.user.name=your-custom-username
spring.security.user.password=your-custom-password

然后在Postman中使用该凭据进行Basic认证。

4. 确认数据库连接正常

虽然当前错误由Spring Security导致,但仍需检查启动日志中是否有数据库连接失败的信息,确保PostgreSQL服务正常运行,数据库URL、用户名、密码配置正确。

内容的提问来源于stack exchange,提问作者Jawhar Chebbi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:15:55